1 //===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple interprocedural pass which walks the
11 // call-graph, looking for functions which do not access or only read
12 // non-local memory, and marking them readnone/readonly. It does the
13 // same with function arguments independently, marking them readonly/
14 // readnone/nocapture. Finally, well-known library call declarations
15 // are marked with all attributes that are consistent with the
16 // function's standard definition. This pass is implemented as a
17 // bottom-up traversal of the call-graph.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AssumptionCache.h"
28 #include "llvm/Analysis/BasicAliasAnalysis.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Analysis/CallGraphSCCPass.h"
31 #include "llvm/Analysis/CaptureTracking.h"
32 #include "llvm/Analysis/TargetLibraryInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/InstIterator.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Analysis/TargetLibraryInfo.h"
43 #define DEBUG_TYPE "functionattrs"
45 STATISTIC(NumReadNone, "Number of functions marked readnone");
46 STATISTIC(NumReadOnly, "Number of functions marked readonly");
47 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
48 STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
49 STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
50 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
51 STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
52 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
55 struct FunctionAttrs : public CallGraphSCCPass {
56 static char ID; // Pass identification, replacement for typeid
57 FunctionAttrs() : CallGraphSCCPass(ID) {
58 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
61 bool runOnSCC(CallGraphSCC &SCC) override;
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
65 AU.addRequired<AssumptionCacheTracker>();
66 AU.addRequired<TargetLibraryInfoWrapperPass>();
67 CallGraphSCCPass::getAnalysisUsage(AU);
71 TargetLibraryInfo *TLI;
73 bool AddReadAttrs(const CallGraphSCC &SCC);
74 bool AddArgumentAttrs(const CallGraphSCC &SCC);
75 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
76 bool AddNonNullAttrs(const CallGraphSCC &SCC);
77 bool annotateLibraryCalls(const CallGraphSCC &SCC);
81 char FunctionAttrs::ID = 0;
82 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
83 "Deduce function attributes", false, false)
84 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
85 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
86 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
87 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
88 "Deduce function attributes", false, false)
90 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
93 /// The three kinds of memory access relevant to 'readonly' and
94 /// 'readnone' attributes.
95 enum MemoryAccessKind {
102 static MemoryAccessKind
103 checkFunctionMemoryAccess(Function &F, AAResults &AAR,
104 const SmallPtrSetImpl<Function *> &SCCNodes) {
105 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
106 if (MRB == FMRB_DoesNotAccessMemory)
110 // Definitions with weak linkage may be overridden at linktime with
111 // something that writes memory, so treat them like declarations.
112 if (F.isDeclaration() || F.mayBeOverridden()) {
113 if (AliasAnalysis::onlyReadsMemory(MRB))
116 // Conservatively assume it writes to memory.
120 // Scan the function body for instructions that may read or write memory.
121 bool ReadsMemory = false;
122 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
123 Instruction *I = &*II;
125 // Some instructions can be ignored even if they read or write memory.
126 // Detect these now, skipping to the next instruction if one is found.
127 CallSite CS(cast<Value>(I));
129 // Ignore calls to functions in the same SCC.
130 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
132 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
134 // If the call doesn't access memory, we're done.
135 if (!(MRB & MRI_ModRef))
138 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
139 // The call could access any memory. If that includes writes, give up.
142 // If it reads, note it.
148 // Check whether all pointer arguments point to local memory, and
149 // ignore calls that only access local memory.
150 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
153 if (!Arg->getType()->isPointerTy())
157 I->getAAMetadata(AAInfo);
158 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
160 // Skip accesses to local or constant memory as they don't impact the
161 // externally visible mod/ref behavior.
162 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
166 // Writes non-local memory. Give up.
169 // Ok, it reads non-local memory.
173 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
174 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
175 if (!LI->isVolatile()) {
176 MemoryLocation Loc = MemoryLocation::get(LI);
177 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
180 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
181 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
182 if (!SI->isVolatile()) {
183 MemoryLocation Loc = MemoryLocation::get(SI);
184 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
187 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
188 // Ignore vaargs on local memory.
189 MemoryLocation Loc = MemoryLocation::get(VI);
190 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
194 // Any remaining instructions need to be taken seriously! Check if they
195 // read or write memory.
196 if (I->mayWriteToMemory())
197 // Writes memory. Just give up.
200 // If this instruction may read memory, remember that.
201 ReadsMemory |= I->mayReadFromMemory();
204 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
207 /// Deduce readonly/readnone attributes for the SCC.
208 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
209 SmallPtrSet<Function *, 8> SCCNodes;
211 // Fill SCCNodes with the elements of the SCC. Used for quickly
212 // looking up whether a given CallGraphNode is in this SCC.
213 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
214 SCCNodes.insert((*I)->getFunction());
216 // Check if any of the functions in the SCC read or write memory. If they
217 // write memory then they can't be marked readnone or readonly.
218 bool ReadsMemory = false;
219 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
220 Function *F = (*I)->getFunction();
222 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
223 // External node or node we don't want to optimize - assume it may write
224 // memory and give up.
227 // We need to manually construct BasicAA directly in order to disable its
228 // use of other function analyses.
229 BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F));
231 // Construct our own AA results for this function. We do this manually to
232 // work around the limitations of the legacy pass manager.
233 AAResults AAR(createLegacyPMAAResults(*this, *F, BAR));
235 switch (checkFunctionMemoryAccess(*F, AAR, SCCNodes)) {
247 // Success! Functions in this SCC do not access memory, or only read memory.
248 // Give them the appropriate attribute.
249 bool MadeChange = false;
250 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
251 Function *F = (*I)->getFunction();
253 if (F->doesNotAccessMemory())
257 if (F->onlyReadsMemory() && ReadsMemory)
263 // Clear out any existing attributes.
265 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
267 AttributeSet::FunctionIndex,
268 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
270 // Add in the new attribute.
271 F->addAttribute(AttributeSet::FunctionIndex,
272 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
284 /// For a given pointer Argument, this retains a list of Arguments of functions
285 /// in the same SCC that the pointer data flows into. We use this to build an
286 /// SCC of the arguments.
287 struct ArgumentGraphNode {
288 Argument *Definition;
289 SmallVector<ArgumentGraphNode *, 4> Uses;
292 class ArgumentGraph {
293 // We store pointers to ArgumentGraphNode objects, so it's important that
294 // that they not move around upon insert.
295 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
297 ArgumentMapTy ArgumentMap;
299 // There is no root node for the argument graph, in fact:
300 // void f(int *x, int *y) { if (...) f(x, y); }
301 // is an example where the graph is disconnected. The SCCIterator requires a
302 // single entry point, so we maintain a fake ("synthetic") root node that
303 // uses every node. Because the graph is directed and nothing points into
304 // the root, it will not participate in any SCCs (except for its own).
305 ArgumentGraphNode SyntheticRoot;
308 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
310 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
312 iterator begin() { return SyntheticRoot.Uses.begin(); }
313 iterator end() { return SyntheticRoot.Uses.end(); }
314 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
316 ArgumentGraphNode *operator[](Argument *A) {
317 ArgumentGraphNode &Node = ArgumentMap[A];
319 SyntheticRoot.Uses.push_back(&Node);
324 /// This tracker checks whether callees are in the SCC, and if so it does not
325 /// consider that a capture, instead adding it to the "Uses" list and
326 /// continuing with the analysis.
327 struct ArgumentUsesTracker : public CaptureTracker {
328 ArgumentUsesTracker(const SmallPtrSet<Function *, 8> &SCCNodes)
329 : Captured(false), SCCNodes(SCCNodes) {}
331 void tooManyUses() override { Captured = true; }
333 bool captured(const Use *U) override {
334 CallSite CS(U->getUser());
335 if (!CS.getInstruction()) {
340 Function *F = CS.getCalledFunction();
341 if (!F || !SCCNodes.count(F)) {
347 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
348 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
349 PI != PE; ++PI, ++AI) {
351 assert(F->isVarArg() && "More params than args in non-varargs call");
356 Uses.push_back(&*AI);
361 assert(Found && "Capturing call-site captured nothing?");
366 bool Captured; // True only if certainly captured (used outside our SCC).
367 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
369 const SmallPtrSet<Function *, 8> &SCCNodes;
374 template <> struct GraphTraits<ArgumentGraphNode *> {
375 typedef ArgumentGraphNode NodeType;
376 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
378 static inline NodeType *getEntryNode(NodeType *A) { return A; }
379 static inline ChildIteratorType child_begin(NodeType *N) {
380 return N->Uses.begin();
382 static inline ChildIteratorType child_end(NodeType *N) {
383 return N->Uses.end();
387 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
388 static NodeType *getEntryNode(ArgumentGraph *AG) {
389 return AG->getEntryNode();
391 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
394 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
398 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
399 static Attribute::AttrKind
400 determinePointerReadAttrs(Argument *A,
401 const SmallPtrSet<Argument *, 8> &SCCNodes) {
403 SmallVector<Use *, 32> Worklist;
404 SmallSet<Use *, 32> Visited;
406 // inalloca arguments are always clobbered by the call.
407 if (A->hasInAllocaAttr())
408 return Attribute::None;
411 // We don't need to track IsWritten. If A is written to, return immediately.
413 for (Use &U : A->uses()) {
415 Worklist.push_back(&U);
418 while (!Worklist.empty()) {
419 Use *U = Worklist.pop_back_val();
420 Instruction *I = cast<Instruction>(U->getUser());
423 switch (I->getOpcode()) {
424 case Instruction::BitCast:
425 case Instruction::GetElementPtr:
426 case Instruction::PHI:
427 case Instruction::Select:
428 case Instruction::AddrSpaceCast:
429 // The original value is not read/written via this if the new value isn't.
430 for (Use &UU : I->uses())
431 if (Visited.insert(&UU).second)
432 Worklist.push_back(&UU);
435 case Instruction::Call:
436 case Instruction::Invoke: {
437 bool Captures = true;
439 if (I->getType()->isVoidTy())
442 auto AddUsersToWorklistIfCapturing = [&] {
444 for (Use &UU : I->uses())
445 if (Visited.insert(&UU).second)
446 Worklist.push_back(&UU);
450 if (CS.doesNotAccessMemory()) {
451 AddUsersToWorklistIfCapturing();
455 Function *F = CS.getCalledFunction();
457 if (CS.onlyReadsMemory()) {
459 AddUsersToWorklistIfCapturing();
462 return Attribute::None;
465 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
466 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
467 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
470 assert(F->isVarArg() &&
471 "More params than args in non-varargs call.");
472 return Attribute::None;
474 Captures &= !CS.doesNotCapture(A - B);
475 if (SCCNodes.count(&*AI))
477 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
478 return Attribute::None;
479 if (!CS.doesNotAccessMemory(A - B))
483 AddUsersToWorklistIfCapturing();
487 case Instruction::Load:
491 case Instruction::ICmp:
492 case Instruction::Ret:
496 return Attribute::None;
500 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
503 /// Deduce nocapture attributes for the SCC.
504 bool FunctionAttrs::AddArgumentAttrs(const CallGraphSCC &SCC) {
505 bool Changed = false;
507 SmallPtrSet<Function *, 8> SCCNodes;
509 // Fill SCCNodes with the elements of the SCC. Used for quickly
510 // looking up whether a given CallGraphNode is in this SCC.
511 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
512 Function *F = (*I)->getFunction();
513 if (F && !F->isDeclaration() && !F->mayBeOverridden() &&
514 !F->hasFnAttribute(Attribute::OptimizeNone))
521 B.addAttribute(Attribute::NoCapture);
523 // Check each function in turn, determining which pointer arguments are not
525 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
526 Function *F = (*I)->getFunction();
528 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
529 // External node or function we're trying not to optimize - only a problem
530 // for arguments that we pass to it.
533 // Definitions with weak linkage may be overridden at linktime with
534 // something that captures pointers, so treat them like declarations.
535 if (F->isDeclaration() || F->mayBeOverridden())
538 // Functions that are readonly (or readnone) and nounwind and don't return
539 // a value can't capture arguments. Don't analyze them.
540 if (F->onlyReadsMemory() && F->doesNotThrow() &&
541 F->getReturnType()->isVoidTy()) {
542 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
544 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
545 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
553 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
555 if (!A->getType()->isPointerTy())
557 bool HasNonLocalUses = false;
558 if (!A->hasNoCaptureAttr()) {
559 ArgumentUsesTracker Tracker(SCCNodes);
560 PointerMayBeCaptured(&*A, &Tracker);
561 if (!Tracker.Captured) {
562 if (Tracker.Uses.empty()) {
563 // If it's trivially not captured, mark it nocapture now.
565 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
569 // If it's not trivially captured and not trivially not captured,
570 // then it must be calling into another function in our SCC. Save
571 // its particulars for Argument-SCC analysis later.
572 ArgumentGraphNode *Node = AG[&*A];
573 for (SmallVectorImpl<Argument *>::iterator
574 UI = Tracker.Uses.begin(),
575 UE = Tracker.Uses.end();
577 Node->Uses.push_back(AG[*UI]);
579 HasNonLocalUses = true;
583 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
585 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
586 // Can we determine that it's readonly/readnone without doing an SCC?
587 // Note that we don't allow any calls at all here, or else our result
588 // will be dependent on the iteration order through the functions in the
590 SmallPtrSet<Argument *, 8> Self;
592 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
593 if (R != Attribute::None) {
596 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
598 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
604 // The graph we've collected is partial because we stopped scanning for
605 // argument uses once we solved the argument trivially. These partial nodes
606 // show up as ArgumentGraphNode objects with an empty Uses list, and for
607 // these nodes the final decision about whether they capture has already been
608 // made. If the definition doesn't have a 'nocapture' attribute by now, it
611 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
612 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
613 if (ArgumentSCC.size() == 1) {
614 if (!ArgumentSCC[0]->Definition)
615 continue; // synthetic root node
617 // eg. "void f(int* x) { if (...) f(x); }"
618 if (ArgumentSCC[0]->Uses.size() == 1 &&
619 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
620 Argument *A = ArgumentSCC[0]->Definition;
621 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
628 bool SCCCaptured = false;
629 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
630 I != E && !SCCCaptured; ++I) {
631 ArgumentGraphNode *Node = *I;
632 if (Node->Uses.empty()) {
633 if (!Node->Definition->hasNoCaptureAttr())
640 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
641 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
642 // quickly looking up whether a given Argument is in this ArgumentSCC.
643 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
644 ArgumentSCCNodes.insert((*I)->Definition);
647 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
648 I != E && !SCCCaptured; ++I) {
649 ArgumentGraphNode *N = *I;
650 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
653 Argument *A = (*UI)->Definition;
654 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
663 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
664 Argument *A = ArgumentSCC[i]->Definition;
665 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
670 // We also want to compute readonly/readnone. With a small number of false
671 // negatives, we can assume that any pointer which is captured isn't going
672 // to be provably readonly or readnone, since by definition we can't
673 // analyze all uses of a captured pointer.
675 // The false negatives happen when the pointer is captured by a function
676 // that promises readonly/readnone behaviour on the pointer, then the
677 // pointer's lifetime ends before anything that writes to arbitrary memory.
678 // Also, a readonly/readnone pointer may be returned, but returning a
679 // pointer is capturing it.
681 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
682 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
683 Argument *A = ArgumentSCC[i]->Definition;
684 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
685 if (K == Attribute::ReadNone)
687 if (K == Attribute::ReadOnly) {
688 ReadAttr = Attribute::ReadOnly;
695 if (ReadAttr != Attribute::None) {
697 B.addAttribute(ReadAttr);
698 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
699 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
700 Argument *A = ArgumentSCC[i]->Definition;
701 // Clear out existing readonly/readnone attributes
702 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
703 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
704 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
713 /// Tests whether a function is "malloc-like".
715 /// A function is "malloc-like" if it returns either null or a pointer that
716 /// doesn't alias any other pointer visible to the caller.
717 static bool isFunctionMallocLike(Function *F,
718 SmallPtrSet<Function *, 8> &SCCNodes) {
719 SmallSetVector<Value *, 8> FlowsToReturn;
720 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
721 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
722 FlowsToReturn.insert(Ret->getReturnValue());
724 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
725 Value *RetVal = FlowsToReturn[i];
727 if (Constant *C = dyn_cast<Constant>(RetVal)) {
728 if (!C->isNullValue() && !isa<UndefValue>(C))
734 if (isa<Argument>(RetVal))
737 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
738 switch (RVI->getOpcode()) {
739 // Extend the analysis by looking upwards.
740 case Instruction::BitCast:
741 case Instruction::GetElementPtr:
742 case Instruction::AddrSpaceCast:
743 FlowsToReturn.insert(RVI->getOperand(0));
745 case Instruction::Select: {
746 SelectInst *SI = cast<SelectInst>(RVI);
747 FlowsToReturn.insert(SI->getTrueValue());
748 FlowsToReturn.insert(SI->getFalseValue());
751 case Instruction::PHI: {
752 PHINode *PN = cast<PHINode>(RVI);
753 for (Value *IncValue : PN->incoming_values())
754 FlowsToReturn.insert(IncValue);
758 // Check whether the pointer came from an allocation.
759 case Instruction::Alloca:
761 case Instruction::Call:
762 case Instruction::Invoke: {
764 if (CS.paramHasAttr(0, Attribute::NoAlias))
766 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
770 return false; // Did not come from an allocation.
773 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
780 /// Deduce noalias attributes for the SCC.
781 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
782 SmallPtrSet<Function *, 8> SCCNodes;
784 // Fill SCCNodes with the elements of the SCC. Used for quickly
785 // looking up whether a given CallGraphNode is in this SCC.
786 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
787 SCCNodes.insert((*I)->getFunction());
789 // Check each function in turn, determining which functions return noalias
791 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
792 Function *F = (*I)->getFunction();
794 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
795 // External node or node we don't want to optimize - skip it;
799 if (F->doesNotAlias(0))
802 // Definitions with weak linkage may be overridden at linktime, so
803 // treat them like declarations.
804 if (F->isDeclaration() || F->mayBeOverridden())
807 // We annotate noalias return values, which are only applicable to
809 if (!F->getReturnType()->isPointerTy())
812 if (!isFunctionMallocLike(F, SCCNodes))
816 bool MadeChange = false;
817 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
818 Function *F = (*I)->getFunction();
819 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
822 F->setDoesNotAlias(0);
830 /// Tests whether this function is known to not return null.
832 /// Requires that the function returns a pointer.
834 /// Returns true if it believes the function will not return a null, and sets
835 /// \p Speculative based on whether the returned conclusion is a speculative
836 /// conclusion due to SCC calls.
837 static bool isReturnNonNull(Function *F, SmallPtrSet<Function *, 8> &SCCNodes,
838 const TargetLibraryInfo &TLI, bool &Speculative) {
839 assert(F->getReturnType()->isPointerTy() &&
840 "nonnull only meaningful on pointer types");
843 SmallSetVector<Value *, 8> FlowsToReturn;
844 for (BasicBlock &BB : *F)
845 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
846 FlowsToReturn.insert(Ret->getReturnValue());
848 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
849 Value *RetVal = FlowsToReturn[i];
851 // If this value is locally known to be non-null, we're good
852 if (isKnownNonNull(RetVal, &TLI))
855 // Otherwise, we need to look upwards since we can't make any local
857 Instruction *RVI = dyn_cast<Instruction>(RetVal);
860 switch (RVI->getOpcode()) {
861 // Extend the analysis by looking upwards.
862 case Instruction::BitCast:
863 case Instruction::GetElementPtr:
864 case Instruction::AddrSpaceCast:
865 FlowsToReturn.insert(RVI->getOperand(0));
867 case Instruction::Select: {
868 SelectInst *SI = cast<SelectInst>(RVI);
869 FlowsToReturn.insert(SI->getTrueValue());
870 FlowsToReturn.insert(SI->getFalseValue());
873 case Instruction::PHI: {
874 PHINode *PN = cast<PHINode>(RVI);
875 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
876 FlowsToReturn.insert(PN->getIncomingValue(i));
879 case Instruction::Call:
880 case Instruction::Invoke: {
882 Function *Callee = CS.getCalledFunction();
883 // A call to a node within the SCC is assumed to return null until
885 if (Callee && SCCNodes.count(Callee)) {
892 return false; // Unknown source, may be null
894 llvm_unreachable("should have either continued or returned");
900 /// Deduce nonnull attributes for the SCC.
901 bool FunctionAttrs::AddNonNullAttrs(const CallGraphSCC &SCC) {
902 SmallPtrSet<Function *, 8> SCCNodes;
904 // Fill SCCNodes with the elements of the SCC. Used for quickly
905 // looking up whether a given CallGraphNode is in this SCC.
906 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
907 SCCNodes.insert((*I)->getFunction());
909 // Speculative that all functions in the SCC return only nonnull
910 // pointers. We may refute this as we analyze functions.
911 bool SCCReturnsNonNull = true;
913 bool MadeChange = false;
915 // Check each function in turn, determining which functions return nonnull
917 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
918 Function *F = (*I)->getFunction();
920 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
921 // External node or node we don't want to optimize - skip it;
925 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
929 // Definitions with weak linkage may be overridden at linktime, so
930 // treat them like declarations.
931 if (F->isDeclaration() || F->mayBeOverridden())
934 // We annotate nonnull return values, which are only applicable to
936 if (!F->getReturnType()->isPointerTy())
939 bool Speculative = false;
940 if (isReturnNonNull(F, SCCNodes, *TLI, Speculative)) {
942 // Mark the function eagerly since we may discover a function
943 // which prevents us from speculating about the entire SCC
944 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
945 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
951 // At least one function returns something which could be null, can't
952 // speculate any more.
953 SCCReturnsNonNull = false;
956 if (SCCReturnsNonNull) {
957 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
958 Function *F = (*I)->getFunction();
959 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
960 Attribute::NonNull) ||
961 !F->getReturnType()->isPointerTy())
964 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
965 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
974 static void setDoesNotAccessMemory(Function &F) {
975 if (!F.doesNotAccessMemory()) {
976 F.setDoesNotAccessMemory();
981 static void setOnlyReadsMemory(Function &F) {
982 if (!F.onlyReadsMemory()) {
983 F.setOnlyReadsMemory();
988 static void setDoesNotThrow(Function &F) {
989 if (!F.doesNotThrow()) {
995 static void setDoesNotCapture(Function &F, unsigned n) {
996 if (!F.doesNotCapture(n)) {
997 F.setDoesNotCapture(n);
1002 static void setOnlyReadsMemory(Function &F, unsigned n) {
1003 if (!F.onlyReadsMemory(n)) {
1004 F.setOnlyReadsMemory(n);
1009 static void setDoesNotAlias(Function &F, unsigned n) {
1010 if (!F.doesNotAlias(n)) {
1011 F.setDoesNotAlias(n);
1016 /// Analyze the name and prototype of the given function and set any applicable
1019 /// Returns true if any attributes were set and false otherwise.
1020 static bool inferPrototypeAttributes(Function &F, const TargetLibraryInfo &TLI) {
1021 if (F.hasFnAttribute(Attribute::OptimizeNone))
1024 FunctionType *FTy = F.getFunctionType();
1025 LibFunc::Func TheLibFunc;
1026 if (!(TLI.getLibFunc(F.getName(), TheLibFunc) && TLI.has(TheLibFunc)))
1029 switch (TheLibFunc) {
1030 case LibFunc::strlen:
1031 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1033 setOnlyReadsMemory(F);
1035 setDoesNotCapture(F, 1);
1037 case LibFunc::strchr:
1038 case LibFunc::strrchr:
1039 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1040 !FTy->getParamType(1)->isIntegerTy())
1042 setOnlyReadsMemory(F);
1045 case LibFunc::strtol:
1046 case LibFunc::strtod:
1047 case LibFunc::strtof:
1048 case LibFunc::strtoul:
1049 case LibFunc::strtoll:
1050 case LibFunc::strtold:
1051 case LibFunc::strtoull:
1052 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1055 setDoesNotCapture(F, 2);
1056 setOnlyReadsMemory(F, 1);
1058 case LibFunc::strcpy:
1059 case LibFunc::stpcpy:
1060 case LibFunc::strcat:
1061 case LibFunc::strncat:
1062 case LibFunc::strncpy:
1063 case LibFunc::stpncpy:
1064 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1067 setDoesNotCapture(F, 2);
1068 setOnlyReadsMemory(F, 2);
1070 case LibFunc::strxfrm:
1071 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1072 !FTy->getParamType(1)->isPointerTy())
1075 setDoesNotCapture(F, 1);
1076 setDoesNotCapture(F, 2);
1077 setOnlyReadsMemory(F, 2);
1079 case LibFunc::strcmp: // 0,1
1080 case LibFunc::strspn: // 0,1
1081 case LibFunc::strncmp: // 0,1
1082 case LibFunc::strcspn: // 0,1
1083 case LibFunc::strcoll: // 0,1
1084 case LibFunc::strcasecmp: // 0,1
1085 case LibFunc::strncasecmp: //
1086 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1087 !FTy->getParamType(1)->isPointerTy())
1089 setOnlyReadsMemory(F);
1091 setDoesNotCapture(F, 1);
1092 setDoesNotCapture(F, 2);
1094 case LibFunc::strstr:
1095 case LibFunc::strpbrk:
1096 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1098 setOnlyReadsMemory(F);
1100 setDoesNotCapture(F, 2);
1102 case LibFunc::strtok:
1103 case LibFunc::strtok_r:
1104 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1107 setDoesNotCapture(F, 2);
1108 setOnlyReadsMemory(F, 2);
1110 case LibFunc::scanf:
1111 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1114 setDoesNotCapture(F, 1);
1115 setOnlyReadsMemory(F, 1);
1117 case LibFunc::setbuf:
1118 case LibFunc::setvbuf:
1119 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1122 setDoesNotCapture(F, 1);
1124 case LibFunc::strdup:
1125 case LibFunc::strndup:
1126 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1127 !FTy->getParamType(0)->isPointerTy())
1130 setDoesNotAlias(F, 0);
1131 setDoesNotCapture(F, 1);
1132 setOnlyReadsMemory(F, 1);
1135 case LibFunc::statvfs:
1136 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1137 !FTy->getParamType(1)->isPointerTy())
1140 setDoesNotCapture(F, 1);
1141 setDoesNotCapture(F, 2);
1142 setOnlyReadsMemory(F, 1);
1144 case LibFunc::sscanf:
1145 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1146 !FTy->getParamType(1)->isPointerTy())
1149 setDoesNotCapture(F, 1);
1150 setDoesNotCapture(F, 2);
1151 setOnlyReadsMemory(F, 1);
1152 setOnlyReadsMemory(F, 2);
1154 case LibFunc::sprintf:
1155 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1156 !FTy->getParamType(1)->isPointerTy())
1159 setDoesNotCapture(F, 1);
1160 setDoesNotCapture(F, 2);
1161 setOnlyReadsMemory(F, 2);
1163 case LibFunc::snprintf:
1164 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1165 !FTy->getParamType(2)->isPointerTy())
1168 setDoesNotCapture(F, 1);
1169 setDoesNotCapture(F, 3);
1170 setOnlyReadsMemory(F, 3);
1172 case LibFunc::setitimer:
1173 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1174 !FTy->getParamType(2)->isPointerTy())
1177 setDoesNotCapture(F, 2);
1178 setDoesNotCapture(F, 3);
1179 setOnlyReadsMemory(F, 2);
1181 case LibFunc::system:
1182 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1184 // May throw; "system" is a valid pthread cancellation point.
1185 setDoesNotCapture(F, 1);
1186 setOnlyReadsMemory(F, 1);
1188 case LibFunc::malloc:
1189 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1192 setDoesNotAlias(F, 0);
1194 case LibFunc::memcmp:
1195 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1196 !FTy->getParamType(1)->isPointerTy())
1198 setOnlyReadsMemory(F);
1200 setDoesNotCapture(F, 1);
1201 setDoesNotCapture(F, 2);
1203 case LibFunc::memchr:
1204 case LibFunc::memrchr:
1205 if (FTy->getNumParams() != 3)
1207 setOnlyReadsMemory(F);
1211 case LibFunc::modff:
1212 case LibFunc::modfl:
1213 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1216 setDoesNotCapture(F, 2);
1218 case LibFunc::memcpy:
1219 case LibFunc::memccpy:
1220 case LibFunc::memmove:
1221 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1224 setDoesNotCapture(F, 2);
1225 setOnlyReadsMemory(F, 2);
1227 case LibFunc::memalign:
1228 if (!FTy->getReturnType()->isPointerTy())
1230 setDoesNotAlias(F, 0);
1232 case LibFunc::mkdir:
1233 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1236 setDoesNotCapture(F, 1);
1237 setOnlyReadsMemory(F, 1);
1239 case LibFunc::mktime:
1240 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1243 setDoesNotCapture(F, 1);
1245 case LibFunc::realloc:
1246 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1247 !FTy->getReturnType()->isPointerTy())
1250 setDoesNotAlias(F, 0);
1251 setDoesNotCapture(F, 1);
1254 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1256 // May throw; "read" is a valid pthread cancellation point.
1257 setDoesNotCapture(F, 2);
1259 case LibFunc::rewind:
1260 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1263 setDoesNotCapture(F, 1);
1265 case LibFunc::rmdir:
1266 case LibFunc::remove:
1267 case LibFunc::realpath:
1268 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1271 setDoesNotCapture(F, 1);
1272 setOnlyReadsMemory(F, 1);
1274 case LibFunc::rename:
1275 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1276 !FTy->getParamType(1)->isPointerTy())
1279 setDoesNotCapture(F, 1);
1280 setDoesNotCapture(F, 2);
1281 setOnlyReadsMemory(F, 1);
1282 setOnlyReadsMemory(F, 2);
1284 case LibFunc::readlink:
1285 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1286 !FTy->getParamType(1)->isPointerTy())
1289 setDoesNotCapture(F, 1);
1290 setDoesNotCapture(F, 2);
1291 setOnlyReadsMemory(F, 1);
1293 case LibFunc::write:
1294 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1296 // May throw; "write" is a valid pthread cancellation point.
1297 setDoesNotCapture(F, 2);
1298 setOnlyReadsMemory(F, 2);
1300 case LibFunc::bcopy:
1301 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1302 !FTy->getParamType(1)->isPointerTy())
1305 setDoesNotCapture(F, 1);
1306 setDoesNotCapture(F, 2);
1307 setOnlyReadsMemory(F, 1);
1310 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1311 !FTy->getParamType(1)->isPointerTy())
1314 setOnlyReadsMemory(F);
1315 setDoesNotCapture(F, 1);
1316 setDoesNotCapture(F, 2);
1318 case LibFunc::bzero:
1319 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1322 setDoesNotCapture(F, 1);
1324 case LibFunc::calloc:
1325 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1328 setDoesNotAlias(F, 0);
1330 case LibFunc::chmod:
1331 case LibFunc::chown:
1332 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1335 setDoesNotCapture(F, 1);
1336 setOnlyReadsMemory(F, 1);
1338 case LibFunc::ctermid:
1339 case LibFunc::clearerr:
1340 case LibFunc::closedir:
1341 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1344 setDoesNotCapture(F, 1);
1349 case LibFunc::atoll:
1350 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1353 setOnlyReadsMemory(F);
1354 setDoesNotCapture(F, 1);
1356 case LibFunc::access:
1357 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1360 setDoesNotCapture(F, 1);
1361 setOnlyReadsMemory(F, 1);
1363 case LibFunc::fopen:
1364 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1365 !FTy->getParamType(0)->isPointerTy() ||
1366 !FTy->getParamType(1)->isPointerTy())
1369 setDoesNotAlias(F, 0);
1370 setDoesNotCapture(F, 1);
1371 setDoesNotCapture(F, 2);
1372 setOnlyReadsMemory(F, 1);
1373 setOnlyReadsMemory(F, 2);
1375 case LibFunc::fdopen:
1376 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1377 !FTy->getParamType(1)->isPointerTy())
1380 setDoesNotAlias(F, 0);
1381 setDoesNotCapture(F, 2);
1382 setOnlyReadsMemory(F, 2);
1386 case LibFunc::fseek:
1387 case LibFunc::ftell:
1388 case LibFunc::fgetc:
1389 case LibFunc::fseeko:
1390 case LibFunc::ftello:
1391 case LibFunc::fileno:
1392 case LibFunc::fflush:
1393 case LibFunc::fclose:
1394 case LibFunc::fsetpos:
1395 case LibFunc::flockfile:
1396 case LibFunc::funlockfile:
1397 case LibFunc::ftrylockfile:
1398 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1401 setDoesNotCapture(F, 1);
1403 case LibFunc::ferror:
1404 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1407 setDoesNotCapture(F, 1);
1408 setOnlyReadsMemory(F);
1410 case LibFunc::fputc:
1411 case LibFunc::fstat:
1412 case LibFunc::frexp:
1413 case LibFunc::frexpf:
1414 case LibFunc::frexpl:
1415 case LibFunc::fstatvfs:
1416 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1419 setDoesNotCapture(F, 2);
1421 case LibFunc::fgets:
1422 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1423 !FTy->getParamType(2)->isPointerTy())
1426 setDoesNotCapture(F, 3);
1428 case LibFunc::fread:
1429 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1430 !FTy->getParamType(3)->isPointerTy())
1433 setDoesNotCapture(F, 1);
1434 setDoesNotCapture(F, 4);
1436 case LibFunc::fwrite:
1437 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1438 !FTy->getParamType(3)->isPointerTy())
1441 setDoesNotCapture(F, 1);
1442 setDoesNotCapture(F, 4);
1444 case LibFunc::fputs:
1445 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1446 !FTy->getParamType(1)->isPointerTy())
1449 setDoesNotCapture(F, 1);
1450 setDoesNotCapture(F, 2);
1451 setOnlyReadsMemory(F, 1);
1453 case LibFunc::fscanf:
1454 case LibFunc::fprintf:
1455 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1456 !FTy->getParamType(1)->isPointerTy())
1459 setDoesNotCapture(F, 1);
1460 setDoesNotCapture(F, 2);
1461 setOnlyReadsMemory(F, 2);
1463 case LibFunc::fgetpos:
1464 if (FTy->getNumParams() < 2 || !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 || !FTy->getParamType(0)->isPointerTy() ||
1532 !FTy->getParamType(1)->isPointerTy())
1535 setDoesNotCapture(F, 1);
1536 setDoesNotCapture(F, 2);
1537 setOnlyReadsMemory(F, 1);
1538 setOnlyReadsMemory(F, 2);
1541 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1544 setDoesNotCapture(F, 2);
1547 case LibFunc::printf:
1548 case LibFunc::perror:
1549 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1552 setDoesNotCapture(F, 1);
1553 setOnlyReadsMemory(F, 1);
1555 case LibFunc::pread:
1556 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1558 // May throw; "pread" is a valid pthread cancellation point.
1559 setDoesNotCapture(F, 2);
1561 case LibFunc::pwrite:
1562 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1564 // May throw; "pwrite" is a valid pthread cancellation point.
1565 setDoesNotCapture(F, 2);
1566 setOnlyReadsMemory(F, 2);
1568 case LibFunc::putchar:
1571 case LibFunc::popen:
1572 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1573 !FTy->getParamType(0)->isPointerTy() ||
1574 !FTy->getParamType(1)->isPointerTy())
1577 setDoesNotAlias(F, 0);
1578 setDoesNotCapture(F, 1);
1579 setDoesNotCapture(F, 2);
1580 setOnlyReadsMemory(F, 1);
1581 setOnlyReadsMemory(F, 2);
1583 case LibFunc::pclose:
1584 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1587 setDoesNotCapture(F, 1);
1589 case LibFunc::vscanf:
1590 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1593 setDoesNotCapture(F, 1);
1594 setOnlyReadsMemory(F, 1);
1596 case LibFunc::vsscanf:
1597 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1598 !FTy->getParamType(2)->isPointerTy())
1601 setDoesNotCapture(F, 1);
1602 setDoesNotCapture(F, 2);
1603 setOnlyReadsMemory(F, 1);
1604 setOnlyReadsMemory(F, 2);
1606 case LibFunc::vfscanf:
1607 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1608 !FTy->getParamType(2)->isPointerTy())
1611 setDoesNotCapture(F, 1);
1612 setDoesNotCapture(F, 2);
1613 setOnlyReadsMemory(F, 2);
1615 case LibFunc::valloc:
1616 if (!FTy->getReturnType()->isPointerTy())
1619 setDoesNotAlias(F, 0);
1621 case LibFunc::vprintf:
1622 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1625 setDoesNotCapture(F, 1);
1626 setOnlyReadsMemory(F, 1);
1628 case LibFunc::vfprintf:
1629 case LibFunc::vsprintf:
1630 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1631 !FTy->getParamType(1)->isPointerTy())
1634 setDoesNotCapture(F, 1);
1635 setDoesNotCapture(F, 2);
1636 setOnlyReadsMemory(F, 2);
1638 case LibFunc::vsnprintf:
1639 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1640 !FTy->getParamType(2)->isPointerTy())
1643 setDoesNotCapture(F, 1);
1644 setDoesNotCapture(F, 3);
1645 setOnlyReadsMemory(F, 3);
1648 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1650 // May throw; "open" is a valid pthread cancellation point.
1651 setDoesNotCapture(F, 1);
1652 setOnlyReadsMemory(F, 1);
1654 case LibFunc::opendir:
1655 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1656 !FTy->getParamType(0)->isPointerTy())
1659 setDoesNotAlias(F, 0);
1660 setDoesNotCapture(F, 1);
1661 setOnlyReadsMemory(F, 1);
1663 case LibFunc::tmpfile:
1664 if (!FTy->getReturnType()->isPointerTy())
1667 setDoesNotAlias(F, 0);
1669 case LibFunc::times:
1670 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1673 setDoesNotCapture(F, 1);
1675 case LibFunc::htonl:
1676 case LibFunc::htons:
1677 case LibFunc::ntohl:
1678 case LibFunc::ntohs:
1680 setDoesNotAccessMemory(F);
1682 case LibFunc::lstat:
1683 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1684 !FTy->getParamType(1)->isPointerTy())
1687 setDoesNotCapture(F, 1);
1688 setDoesNotCapture(F, 2);
1689 setOnlyReadsMemory(F, 1);
1691 case LibFunc::lchown:
1692 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1695 setDoesNotCapture(F, 1);
1696 setOnlyReadsMemory(F, 1);
1698 case LibFunc::qsort:
1699 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1701 // May throw; places call through function pointer.
1702 setDoesNotCapture(F, 4);
1704 case LibFunc::dunder_strdup:
1705 case LibFunc::dunder_strndup:
1706 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1707 !FTy->getParamType(0)->isPointerTy())
1710 setDoesNotAlias(F, 0);
1711 setDoesNotCapture(F, 1);
1712 setOnlyReadsMemory(F, 1);
1714 case LibFunc::dunder_strtok_r:
1715 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1718 setDoesNotCapture(F, 2);
1719 setOnlyReadsMemory(F, 2);
1721 case LibFunc::under_IO_getc:
1722 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1725 setDoesNotCapture(F, 1);
1727 case LibFunc::under_IO_putc:
1728 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1731 setDoesNotCapture(F, 2);
1733 case LibFunc::dunder_isoc99_scanf:
1734 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1737 setDoesNotCapture(F, 1);
1738 setOnlyReadsMemory(F, 1);
1740 case LibFunc::stat64:
1741 case LibFunc::lstat64:
1742 case LibFunc::statvfs64:
1743 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1744 !FTy->getParamType(1)->isPointerTy())
1747 setDoesNotCapture(F, 1);
1748 setDoesNotCapture(F, 2);
1749 setOnlyReadsMemory(F, 1);
1751 case LibFunc::dunder_isoc99_sscanf:
1752 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1753 !FTy->getParamType(1)->isPointerTy())
1756 setDoesNotCapture(F, 1);
1757 setDoesNotCapture(F, 2);
1758 setOnlyReadsMemory(F, 1);
1759 setOnlyReadsMemory(F, 2);
1761 case LibFunc::fopen64:
1762 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1763 !FTy->getParamType(0)->isPointerTy() ||
1764 !FTy->getParamType(1)->isPointerTy())
1767 setDoesNotAlias(F, 0);
1768 setDoesNotCapture(F, 1);
1769 setDoesNotCapture(F, 2);
1770 setOnlyReadsMemory(F, 1);
1771 setOnlyReadsMemory(F, 2);
1773 case LibFunc::fseeko64:
1774 case LibFunc::ftello64:
1775 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1778 setDoesNotCapture(F, 1);
1780 case LibFunc::tmpfile64:
1781 if (!FTy->getReturnType()->isPointerTy())
1784 setDoesNotAlias(F, 0);
1786 case LibFunc::fstat64:
1787 case LibFunc::fstatvfs64:
1788 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1791 setDoesNotCapture(F, 2);
1793 case LibFunc::open64:
1794 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1796 // May throw; "open" is a valid pthread cancellation point.
1797 setDoesNotCapture(F, 1);
1798 setOnlyReadsMemory(F, 1);
1800 case LibFunc::gettimeofday:
1801 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1802 !FTy->getParamType(1)->isPointerTy())
1804 // Currently some platforms have the restrict keyword on the arguments to
1805 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1808 setDoesNotCapture(F, 1);
1809 setDoesNotCapture(F, 2);
1812 // Didn't mark any attributes.
1819 /// Adds attributes to well-known standard library call declarations.
1820 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1821 bool MadeChange = false;
1823 // Check each function in turn annotating well-known library function
1824 // declarations with attributes.
1825 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1826 Function *F = (*I)->getFunction();
1828 if (F && F->isDeclaration())
1829 MadeChange |= inferPrototypeAttributes(*F, *TLI);
1835 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1836 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1838 bool Changed = annotateLibraryCalls(SCC);
1839 Changed |= AddReadAttrs(SCC);
1840 Changed |= AddArgumentAttrs(SCC);
1841 Changed |= AddNoAliasAttrs(SCC);
1842 Changed |= AddNonNullAttrs(SCC);