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 // runOnSCC - Analyze the SCC, performing the transformation if possible.
62 bool runOnSCC(CallGraphSCC &SCC) override;
64 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
65 bool AddReadAttrs(const CallGraphSCC &SCC);
67 // AddArgumentAttrs - Deduce nocapture attributes for the SCC.
68 bool AddArgumentAttrs(const CallGraphSCC &SCC);
70 // IsFunctionMallocLike - Does this function allocate new memory?
71 bool IsFunctionMallocLike(Function *F,
72 SmallPtrSet<Function*, 8> &) const;
74 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
75 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
77 /// \brief Does this function return null?
78 bool ReturnsNonNull(Function *F, SmallPtrSet<Function*, 8> &,
79 bool &Speculative) const;
81 /// \brief Deduce nonnull attributes for the SCC.
82 bool AddNonNullAttrs(const CallGraphSCC &SCC);
84 // Utility methods used by inferPrototypeAttributes to add attributes
85 // and maintain annotation statistics.
87 void setDoesNotAccessMemory(Function &F) {
88 if (!F.doesNotAccessMemory()) {
89 F.setDoesNotAccessMemory();
94 void setOnlyReadsMemory(Function &F) {
95 if (!F.onlyReadsMemory()) {
96 F.setOnlyReadsMemory();
101 void setDoesNotThrow(Function &F) {
102 if (!F.doesNotThrow()) {
108 void setDoesNotCapture(Function &F, unsigned n) {
109 if (!F.doesNotCapture(n)) {
110 F.setDoesNotCapture(n);
115 void setOnlyReadsMemory(Function &F, unsigned n) {
116 if (!F.onlyReadsMemory(n)) {
117 F.setOnlyReadsMemory(n);
122 void setDoesNotAlias(Function &F, unsigned n) {
123 if (!F.doesNotAlias(n)) {
124 F.setDoesNotAlias(n);
129 // inferPrototypeAttributes - Analyze the name and prototype of the
130 // given function and set any applicable attributes. Returns true
131 // if any attributes were set and false otherwise.
132 bool inferPrototypeAttributes(Function &F);
134 // annotateLibraryCalls - Adds attributes to well-known standard library
135 // call declarations.
136 bool annotateLibraryCalls(const CallGraphSCC &SCC);
138 void getAnalysisUsage(AnalysisUsage &AU) const override {
139 AU.setPreservesCFG();
140 AU.addRequired<AssumptionCacheTracker>();
141 AU.addRequired<TargetLibraryInfoWrapperPass>();
142 CallGraphSCCPass::getAnalysisUsage(AU);
146 TargetLibraryInfo *TLI;
150 char FunctionAttrs::ID = 0;
151 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
152 "Deduce function attributes", false, false)
153 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
154 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
155 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
156 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
157 "Deduce function attributes", false, false)
159 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
162 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
163 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
164 SmallPtrSet<Function*, 8> SCCNodes;
166 // Fill SCCNodes with the elements of the SCC. Used for quickly
167 // looking up whether a given CallGraphNode is in this SCC.
168 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
169 SCCNodes.insert((*I)->getFunction());
171 // Check if any of the functions in the SCC read or write memory. If they
172 // write memory then they can't be marked readnone or readonly.
173 bool ReadsMemory = false;
174 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
175 Function *F = (*I)->getFunction();
177 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
178 // External node or node we don't want to optimize - assume it may write
179 // memory and give up.
182 // We need to manually construct BasicAA directly in order to disable its
183 // use of other function analyses.
184 BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F));
186 // Construct our own AA results for this function. We do this manually to
187 // work around the limitations of the legacy pass manager.
188 AAResults AAR(createLegacyPMAAResults(*this, *F, BAR));
190 FunctionModRefBehavior MRB = AAR.getModRefBehavior(F);
191 if (MRB == FMRB_DoesNotAccessMemory)
195 // Definitions with weak linkage may be overridden at linktime with
196 // something that writes memory, so treat them like declarations.
197 if (F->isDeclaration() || F->mayBeOverridden()) {
198 if (!AliasAnalysis::onlyReadsMemory(MRB))
199 // May write memory. Just give up.
206 // Scan the function body for instructions that may read or write memory.
207 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
208 Instruction *I = &*II;
210 // Some instructions can be ignored even if they read or write memory.
211 // Detect these now, skipping to the next instruction if one is found.
212 CallSite CS(cast<Value>(I));
214 // Ignore calls to functions in the same SCC.
215 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
217 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
218 // If the call doesn't access arbitrary memory, we may be able to
219 // figure out something.
220 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
221 // If the call does access argument pointees, check each argument.
222 if (AliasAnalysis::doesAccessArgPointees(MRB))
223 // Check whether all pointer arguments point to local memory, and
224 // ignore calls that only access local memory.
225 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
228 if (Arg->getType()->isPointerTy()) {
230 I->getAAMetadata(AAInfo);
232 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
233 if (!AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
235 // Writes non-local memory. Give up.
238 // Ok, it reads non-local memory.
245 // The call could access any memory. If that includes writes, give up.
248 // If it reads, note it.
252 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
253 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
254 if (!LI->isVolatile()) {
255 MemoryLocation Loc = MemoryLocation::get(LI);
256 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
259 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
260 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
261 if (!SI->isVolatile()) {
262 MemoryLocation Loc = MemoryLocation::get(SI);
263 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
266 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
267 // Ignore vaargs on local memory.
268 MemoryLocation Loc = MemoryLocation::get(VI);
269 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
273 // Any remaining instructions need to be taken seriously! Check if they
274 // read or write memory.
275 if (I->mayWriteToMemory())
276 // Writes memory. Just give up.
279 // If this instruction may read memory, remember that.
280 ReadsMemory |= I->mayReadFromMemory();
284 // Success! Functions in this SCC do not access memory, or only read memory.
285 // Give them the appropriate attribute.
286 bool MadeChange = false;
287 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
288 Function *F = (*I)->getFunction();
290 if (F->doesNotAccessMemory())
294 if (F->onlyReadsMemory() && ReadsMemory)
300 // Clear out any existing attributes.
302 B.addAttribute(Attribute::ReadOnly)
303 .addAttribute(Attribute::ReadNone);
304 F->removeAttributes(AttributeSet::FunctionIndex,
305 AttributeSet::get(F->getContext(),
306 AttributeSet::FunctionIndex, B));
308 // Add in the new attribute.
309 F->addAttribute(AttributeSet::FunctionIndex,
310 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
322 // For a given pointer Argument, this retains a list of Arguments of functions
323 // in the same SCC that the pointer data flows into. We use this to build an
324 // SCC of the arguments.
325 struct ArgumentGraphNode {
326 Argument *Definition;
327 SmallVector<ArgumentGraphNode*, 4> Uses;
330 class ArgumentGraph {
331 // We store pointers to ArgumentGraphNode objects, so it's important that
332 // that they not move around upon insert.
333 typedef std::map<Argument*, ArgumentGraphNode> ArgumentMapTy;
335 ArgumentMapTy ArgumentMap;
337 // There is no root node for the argument graph, in fact:
338 // void f(int *x, int *y) { if (...) f(x, y); }
339 // is an example where the graph is disconnected. The SCCIterator requires a
340 // single entry point, so we maintain a fake ("synthetic") root node that
341 // uses every node. Because the graph is directed and nothing points into
342 // the root, it will not participate in any SCCs (except for its own).
343 ArgumentGraphNode SyntheticRoot;
346 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
348 typedef SmallVectorImpl<ArgumentGraphNode*>::iterator iterator;
350 iterator begin() { return SyntheticRoot.Uses.begin(); }
351 iterator end() { return SyntheticRoot.Uses.end(); }
352 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
354 ArgumentGraphNode *operator[](Argument *A) {
355 ArgumentGraphNode &Node = ArgumentMap[A];
357 SyntheticRoot.Uses.push_back(&Node);
362 // This tracker checks whether callees are in the SCC, and if so it does not
363 // consider that a capture, instead adding it to the "Uses" list and
364 // continuing with the analysis.
365 struct ArgumentUsesTracker : public CaptureTracker {
366 ArgumentUsesTracker(const SmallPtrSet<Function*, 8> &SCCNodes)
367 : Captured(false), SCCNodes(SCCNodes) {}
369 void tooManyUses() override { Captured = true; }
371 bool captured(const Use *U) override {
372 CallSite CS(U->getUser());
373 if (!CS.getInstruction()) { Captured = true; return true; }
375 Function *F = CS.getCalledFunction();
376 if (!F || !SCCNodes.count(F)) { Captured = true; return true; }
379 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
380 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
381 PI != PE; ++PI, ++AI) {
383 assert(F->isVarArg() && "More params than args in non-varargs call");
393 assert(Found && "Capturing call-site captured nothing?");
398 bool Captured; // True only if certainly captured (used outside our SCC).
399 SmallVector<Argument*, 4> Uses; // Uses within our SCC.
401 const SmallPtrSet<Function*, 8> &SCCNodes;
406 template<> struct GraphTraits<ArgumentGraphNode*> {
407 typedef ArgumentGraphNode NodeType;
408 typedef SmallVectorImpl<ArgumentGraphNode*>::iterator ChildIteratorType;
410 static inline NodeType *getEntryNode(NodeType *A) { return A; }
411 static inline ChildIteratorType child_begin(NodeType *N) {
412 return N->Uses.begin();
414 static inline ChildIteratorType child_end(NodeType *N) {
415 return N->Uses.end();
418 template<> struct GraphTraits<ArgumentGraph*>
419 : public GraphTraits<ArgumentGraphNode*> {
420 static NodeType *getEntryNode(ArgumentGraph *AG) {
421 return AG->getEntryNode();
423 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
426 static ChildIteratorType nodes_end(ArgumentGraph *AG) {
432 // Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
433 static Attribute::AttrKind
434 determinePointerReadAttrs(Argument *A,
435 const SmallPtrSet<Argument*, 8> &SCCNodes) {
437 SmallVector<Use*, 32> Worklist;
438 SmallSet<Use*, 32> Visited;
440 // inalloca arguments are always clobbered by the call.
441 if (A->hasInAllocaAttr())
442 return Attribute::None;
445 // We don't need to track IsWritten. If A is written to, return immediately.
447 for (Use &U : A->uses()) {
449 Worklist.push_back(&U);
452 while (!Worklist.empty()) {
453 Use *U = Worklist.pop_back_val();
454 Instruction *I = cast<Instruction>(U->getUser());
457 switch (I->getOpcode()) {
458 case Instruction::BitCast:
459 case Instruction::GetElementPtr:
460 case Instruction::PHI:
461 case Instruction::Select:
462 case Instruction::AddrSpaceCast:
463 // The original value is not read/written via this if the new value isn't.
464 for (Use &UU : I->uses())
465 if (Visited.insert(&UU).second)
466 Worklist.push_back(&UU);
469 case Instruction::Call:
470 case Instruction::Invoke: {
471 bool Captures = true;
473 if (I->getType()->isVoidTy())
476 auto AddUsersToWorklistIfCapturing = [&] {
478 for (Use &UU : I->uses())
479 if (Visited.insert(&UU).second)
480 Worklist.push_back(&UU);
484 if (CS.doesNotAccessMemory()) {
485 AddUsersToWorklistIfCapturing();
489 Function *F = CS.getCalledFunction();
491 if (CS.onlyReadsMemory()) {
493 AddUsersToWorklistIfCapturing();
496 return Attribute::None;
499 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
500 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
501 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
504 assert(F->isVarArg() &&
505 "More params than args in non-varargs call.");
506 return Attribute::None;
508 Captures &= !CS.doesNotCapture(A - B);
509 if (SCCNodes.count(AI))
511 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
512 return Attribute::None;
513 if (!CS.doesNotAccessMemory(A - B))
517 AddUsersToWorklistIfCapturing();
521 case Instruction::Load:
525 case Instruction::ICmp:
526 case Instruction::Ret:
530 return Attribute::None;
534 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
537 /// AddArgumentAttrs - Deduce nocapture attributes for the SCC.
538 bool FunctionAttrs::AddArgumentAttrs(const CallGraphSCC &SCC) {
539 bool Changed = false;
541 SmallPtrSet<Function*, 8> SCCNodes;
543 // Fill SCCNodes with the elements of the SCC. Used for quickly
544 // looking up whether a given CallGraphNode is in this SCC.
545 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
546 Function *F = (*I)->getFunction();
547 if (F && !F->isDeclaration() && !F->mayBeOverridden() &&
548 !F->hasFnAttribute(Attribute::OptimizeNone))
555 B.addAttribute(Attribute::NoCapture);
557 // Check each function in turn, determining which pointer arguments are not
559 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
560 Function *F = (*I)->getFunction();
562 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
563 // External node or function we're trying not to optimize - only a problem
564 // for arguments that we pass to it.
567 // Definitions with weak linkage may be overridden at linktime with
568 // something that captures pointers, so treat them like declarations.
569 if (F->isDeclaration() || F->mayBeOverridden())
572 // Functions that are readonly (or readnone) and nounwind and don't return
573 // a value can't capture arguments. Don't analyze them.
574 if (F->onlyReadsMemory() && F->doesNotThrow() &&
575 F->getReturnType()->isVoidTy()) {
576 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end();
578 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
579 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
587 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end();
589 if (!A->getType()->isPointerTy()) continue;
590 bool HasNonLocalUses = false;
591 if (!A->hasNoCaptureAttr()) {
592 ArgumentUsesTracker Tracker(SCCNodes);
593 PointerMayBeCaptured(A, &Tracker);
594 if (!Tracker.Captured) {
595 if (Tracker.Uses.empty()) {
596 // If it's trivially not captured, mark it nocapture now.
597 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo()+1, B));
601 // If it's not trivially captured and not trivially not captured,
602 // then it must be calling into another function in our SCC. Save
603 // its particulars for Argument-SCC analysis later.
604 ArgumentGraphNode *Node = AG[A];
605 for (SmallVectorImpl<Argument*>::iterator UI = Tracker.Uses.begin(),
606 UE = Tracker.Uses.end(); UI != UE; ++UI) {
607 Node->Uses.push_back(AG[*UI]);
609 HasNonLocalUses = true;
613 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
615 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
616 // Can we determine that it's readonly/readnone without doing an SCC?
617 // Note that we don't allow any calls at all here, or else our result
618 // will be dependent on the iteration order through the functions in the
620 SmallPtrSet<Argument*, 8> Self;
622 Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
623 if (R != Attribute::None) {
626 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
628 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
634 // The graph we've collected is partial because we stopped scanning for
635 // argument uses once we solved the argument trivially. These partial nodes
636 // show up as ArgumentGraphNode objects with an empty Uses list, and for
637 // these nodes the final decision about whether they capture has already been
638 // made. If the definition doesn't have a 'nocapture' attribute by now, it
641 for (scc_iterator<ArgumentGraph*> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
642 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
643 if (ArgumentSCC.size() == 1) {
644 if (!ArgumentSCC[0]->Definition) continue; // synthetic root node
646 // eg. "void f(int* x) { if (...) f(x); }"
647 if (ArgumentSCC[0]->Uses.size() == 1 &&
648 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
649 Argument *A = ArgumentSCC[0]->Definition;
650 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
657 bool SCCCaptured = false;
658 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
659 I != E && !SCCCaptured; ++I) {
660 ArgumentGraphNode *Node = *I;
661 if (Node->Uses.empty()) {
662 if (!Node->Definition->hasNoCaptureAttr())
666 if (SCCCaptured) continue;
668 SmallPtrSet<Argument*, 8> ArgumentSCCNodes;
669 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
670 // quickly looking up whether a given Argument is in this ArgumentSCC.
671 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
672 ArgumentSCCNodes.insert((*I)->Definition);
675 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
676 I != E && !SCCCaptured; ++I) {
677 ArgumentGraphNode *N = *I;
678 for (SmallVectorImpl<ArgumentGraphNode*>::iterator UI = N->Uses.begin(),
679 UE = N->Uses.end(); UI != UE; ++UI) {
680 Argument *A = (*UI)->Definition;
681 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
687 if (SCCCaptured) continue;
689 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
690 Argument *A = ArgumentSCC[i]->Definition;
691 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
696 // We also want to compute readonly/readnone. With a small number of false
697 // negatives, we can assume that any pointer which is captured isn't going
698 // to be provably readonly or readnone, since by definition we can't
699 // analyze all uses of a captured pointer.
701 // The false negatives happen when the pointer is captured by a function
702 // that promises readonly/readnone behaviour on the pointer, then the
703 // pointer's lifetime ends before anything that writes to arbitrary memory.
704 // Also, a readonly/readnone pointer may be returned, but returning a
705 // pointer is capturing it.
707 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
708 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
709 Argument *A = ArgumentSCC[i]->Definition;
710 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
711 if (K == Attribute::ReadNone)
713 if (K == Attribute::ReadOnly) {
714 ReadAttr = Attribute::ReadOnly;
721 if (ReadAttr != Attribute::None) {
723 B.addAttribute(ReadAttr);
724 R.addAttribute(Attribute::ReadOnly)
725 .addAttribute(Attribute::ReadNone);
726 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
727 Argument *A = ArgumentSCC[i]->Definition;
728 // Clear out existing readonly/readnone attributes
729 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
730 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
731 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
740 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
741 /// or a pointer that doesn't alias any other pointer visible to the caller.
742 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
743 SmallPtrSet<Function*, 8> &SCCNodes) const {
744 SmallSetVector<Value *, 8> FlowsToReturn;
745 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
746 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
747 FlowsToReturn.insert(Ret->getReturnValue());
749 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
750 Value *RetVal = FlowsToReturn[i];
752 if (Constant *C = dyn_cast<Constant>(RetVal)) {
753 if (!C->isNullValue() && !isa<UndefValue>(C))
759 if (isa<Argument>(RetVal))
762 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
763 switch (RVI->getOpcode()) {
764 // Extend the analysis by looking upwards.
765 case Instruction::BitCast:
766 case Instruction::GetElementPtr:
767 case Instruction::AddrSpaceCast:
768 FlowsToReturn.insert(RVI->getOperand(0));
770 case Instruction::Select: {
771 SelectInst *SI = cast<SelectInst>(RVI);
772 FlowsToReturn.insert(SI->getTrueValue());
773 FlowsToReturn.insert(SI->getFalseValue());
776 case Instruction::PHI: {
777 PHINode *PN = cast<PHINode>(RVI);
778 for (Value *IncValue : PN->incoming_values())
779 FlowsToReturn.insert(IncValue);
783 // Check whether the pointer came from an allocation.
784 case Instruction::Alloca:
786 case Instruction::Call:
787 case Instruction::Invoke: {
789 if (CS.paramHasAttr(0, Attribute::NoAlias))
791 if (CS.getCalledFunction() &&
792 SCCNodes.count(CS.getCalledFunction()))
796 return false; // Did not come from an allocation.
799 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
806 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
807 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
808 SmallPtrSet<Function*, 8> SCCNodes;
810 // Fill SCCNodes with the elements of the SCC. Used for quickly
811 // looking up whether a given CallGraphNode is in this SCC.
812 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
813 SCCNodes.insert((*I)->getFunction());
815 // Check each function in turn, determining which functions return noalias
817 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
818 Function *F = (*I)->getFunction();
820 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
821 // External node or node we don't want to optimize - skip it;
825 if (F->doesNotAlias(0))
828 // Definitions with weak linkage may be overridden at linktime, so
829 // treat them like declarations.
830 if (F->isDeclaration() || F->mayBeOverridden())
833 // We annotate noalias return values, which are only applicable to
835 if (!F->getReturnType()->isPointerTy())
838 if (!IsFunctionMallocLike(F, SCCNodes))
842 bool MadeChange = false;
843 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
844 Function *F = (*I)->getFunction();
845 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
848 F->setDoesNotAlias(0);
856 bool FunctionAttrs::ReturnsNonNull(Function *F,
857 SmallPtrSet<Function*, 8> &SCCNodes,
858 bool &Speculative) const {
859 assert(F->getReturnType()->isPointerTy() &&
860 "nonnull only meaningful on pointer types");
863 SmallSetVector<Value *, 8> FlowsToReturn;
864 for (BasicBlock &BB : *F)
865 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
866 FlowsToReturn.insert(Ret->getReturnValue());
868 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
869 Value *RetVal = FlowsToReturn[i];
871 // If this value is locally known to be non-null, we're good
872 if (isKnownNonNull(RetVal, TLI))
875 // Otherwise, we need to look upwards since we can't make any local
877 Instruction *RVI = dyn_cast<Instruction>(RetVal);
880 switch (RVI->getOpcode()) {
881 // Extend the analysis by looking upwards.
882 case Instruction::BitCast:
883 case Instruction::GetElementPtr:
884 case Instruction::AddrSpaceCast:
885 FlowsToReturn.insert(RVI->getOperand(0));
887 case Instruction::Select: {
888 SelectInst *SI = cast<SelectInst>(RVI);
889 FlowsToReturn.insert(SI->getTrueValue());
890 FlowsToReturn.insert(SI->getFalseValue());
893 case Instruction::PHI: {
894 PHINode *PN = cast<PHINode>(RVI);
895 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
896 FlowsToReturn.insert(PN->getIncomingValue(i));
899 case Instruction::Call:
900 case Instruction::Invoke: {
902 Function *Callee = CS.getCalledFunction();
903 // A call to a node within the SCC is assumed to return null until
905 if (Callee && SCCNodes.count(Callee)) {
912 return false; // Unknown source, may be null
914 llvm_unreachable("should have either continued or returned");
920 bool FunctionAttrs::AddNonNullAttrs(const CallGraphSCC &SCC) {
921 SmallPtrSet<Function*, 8> SCCNodes;
923 // Fill SCCNodes with the elements of the SCC. Used for quickly
924 // looking up whether a given CallGraphNode is in this SCC.
925 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
926 SCCNodes.insert((*I)->getFunction());
928 // Speculative that all functions in the SCC return only nonnull
929 // pointers. We may refute this as we analyze functions.
930 bool SCCReturnsNonNull = true;
932 bool MadeChange = false;
934 // Check each function in turn, determining which functions return nonnull
936 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
937 Function *F = (*I)->getFunction();
939 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
940 // External node or node we don't want to optimize - skip it;
944 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
948 // Definitions with weak linkage may be overridden at linktime, so
949 // treat them like declarations.
950 if (F->isDeclaration() || F->mayBeOverridden())
953 // We annotate nonnull return values, which are only applicable to
955 if (!F->getReturnType()->isPointerTy())
958 bool Speculative = false;
959 if (ReturnsNonNull(F, SCCNodes, Speculative)) {
961 // Mark the function eagerly since we may discover a function
962 // which prevents us from speculating about the entire SCC
963 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
964 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
970 // At least one function returns something which could be null, can't
971 // speculate any more.
972 SCCReturnsNonNull = false;
975 if (SCCReturnsNonNull) {
976 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
977 Function *F = (*I)->getFunction();
978 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
979 Attribute::NonNull) ||
980 !F->getReturnType()->isPointerTy())
983 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
984 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
993 /// inferPrototypeAttributes - Analyze the name and prototype of the
994 /// given function and set any applicable attributes. Returns true
995 /// if any attributes were set and false otherwise.
996 bool FunctionAttrs::inferPrototypeAttributes(Function &F) {
997 if (F.hasFnAttribute(Attribute::OptimizeNone))
1000 FunctionType *FTy = F.getFunctionType();
1001 LibFunc::Func TheLibFunc;
1002 if (!(TLI->getLibFunc(F.getName(), TheLibFunc) && TLI->has(TheLibFunc)))
1005 switch (TheLibFunc) {
1006 case LibFunc::strlen:
1007 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1009 setOnlyReadsMemory(F);
1011 setDoesNotCapture(F, 1);
1013 case LibFunc::strchr:
1014 case LibFunc::strrchr:
1015 if (FTy->getNumParams() != 2 ||
1016 !FTy->getParamType(0)->isPointerTy() ||
1017 !FTy->getParamType(1)->isIntegerTy())
1019 setOnlyReadsMemory(F);
1022 case LibFunc::strtol:
1023 case LibFunc::strtod:
1024 case LibFunc::strtof:
1025 case LibFunc::strtoul:
1026 case LibFunc::strtoll:
1027 case LibFunc::strtold:
1028 case LibFunc::strtoull:
1029 if (FTy->getNumParams() < 2 ||
1030 !FTy->getParamType(1)->isPointerTy())
1033 setDoesNotCapture(F, 2);
1034 setOnlyReadsMemory(F, 1);
1036 case LibFunc::strcpy:
1037 case LibFunc::stpcpy:
1038 case LibFunc::strcat:
1039 case LibFunc::strncat:
1040 case LibFunc::strncpy:
1041 case LibFunc::stpncpy:
1042 if (FTy->getNumParams() < 2 ||
1043 !FTy->getParamType(1)->isPointerTy())
1046 setDoesNotCapture(F, 2);
1047 setOnlyReadsMemory(F, 2);
1049 case LibFunc::strxfrm:
1050 if (FTy->getNumParams() != 3 ||
1051 !FTy->getParamType(0)->isPointerTy() ||
1052 !FTy->getParamType(1)->isPointerTy())
1055 setDoesNotCapture(F, 1);
1056 setDoesNotCapture(F, 2);
1057 setOnlyReadsMemory(F, 2);
1059 case LibFunc::strcmp: //0,1
1060 case LibFunc::strspn: // 0,1
1061 case LibFunc::strncmp: // 0,1
1062 case LibFunc::strcspn: //0,1
1063 case LibFunc::strcoll: //0,1
1064 case LibFunc::strcasecmp: // 0,1
1065 case LibFunc::strncasecmp: //
1066 if (FTy->getNumParams() < 2 ||
1067 !FTy->getParamType(0)->isPointerTy() ||
1068 !FTy->getParamType(1)->isPointerTy())
1070 setOnlyReadsMemory(F);
1072 setDoesNotCapture(F, 1);
1073 setDoesNotCapture(F, 2);
1075 case LibFunc::strstr:
1076 case LibFunc::strpbrk:
1077 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1079 setOnlyReadsMemory(F);
1081 setDoesNotCapture(F, 2);
1083 case LibFunc::strtok:
1084 case LibFunc::strtok_r:
1085 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1088 setDoesNotCapture(F, 2);
1089 setOnlyReadsMemory(F, 2);
1091 case LibFunc::scanf:
1092 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1095 setDoesNotCapture(F, 1);
1096 setOnlyReadsMemory(F, 1);
1098 case LibFunc::setbuf:
1099 case LibFunc::setvbuf:
1100 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1103 setDoesNotCapture(F, 1);
1105 case LibFunc::strdup:
1106 case LibFunc::strndup:
1107 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1108 !FTy->getParamType(0)->isPointerTy())
1111 setDoesNotAlias(F, 0);
1112 setDoesNotCapture(F, 1);
1113 setOnlyReadsMemory(F, 1);
1116 case LibFunc::statvfs:
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);
1126 case LibFunc::sscanf:
1127 if (FTy->getNumParams() < 2 ||
1128 !FTy->getParamType(0)->isPointerTy() ||
1129 !FTy->getParamType(1)->isPointerTy())
1132 setDoesNotCapture(F, 1);
1133 setDoesNotCapture(F, 2);
1134 setOnlyReadsMemory(F, 1);
1135 setOnlyReadsMemory(F, 2);
1137 case LibFunc::sprintf:
1138 if (FTy->getNumParams() < 2 ||
1139 !FTy->getParamType(0)->isPointerTy() ||
1140 !FTy->getParamType(1)->isPointerTy())
1143 setDoesNotCapture(F, 1);
1144 setDoesNotCapture(F, 2);
1145 setOnlyReadsMemory(F, 2);
1147 case LibFunc::snprintf:
1148 if (FTy->getNumParams() != 3 ||
1149 !FTy->getParamType(0)->isPointerTy() ||
1150 !FTy->getParamType(2)->isPointerTy())
1153 setDoesNotCapture(F, 1);
1154 setDoesNotCapture(F, 3);
1155 setOnlyReadsMemory(F, 3);
1157 case LibFunc::setitimer:
1158 if (FTy->getNumParams() != 3 ||
1159 !FTy->getParamType(1)->isPointerTy() ||
1160 !FTy->getParamType(2)->isPointerTy())
1163 setDoesNotCapture(F, 2);
1164 setDoesNotCapture(F, 3);
1165 setOnlyReadsMemory(F, 2);
1167 case LibFunc::system:
1168 if (FTy->getNumParams() != 1 ||
1169 !FTy->getParamType(0)->isPointerTy())
1171 // May throw; "system" is a valid pthread cancellation point.
1172 setDoesNotCapture(F, 1);
1173 setOnlyReadsMemory(F, 1);
1175 case LibFunc::malloc:
1176 if (FTy->getNumParams() != 1 ||
1177 !FTy->getReturnType()->isPointerTy())
1180 setDoesNotAlias(F, 0);
1182 case LibFunc::memcmp:
1183 if (FTy->getNumParams() != 3 ||
1184 !FTy->getParamType(0)->isPointerTy() ||
1185 !FTy->getParamType(1)->isPointerTy())
1187 setOnlyReadsMemory(F);
1189 setDoesNotCapture(F, 1);
1190 setDoesNotCapture(F, 2);
1192 case LibFunc::memchr:
1193 case LibFunc::memrchr:
1194 if (FTy->getNumParams() != 3)
1196 setOnlyReadsMemory(F);
1200 case LibFunc::modff:
1201 case LibFunc::modfl:
1202 if (FTy->getNumParams() < 2 ||
1203 !FTy->getParamType(1)->isPointerTy())
1206 setDoesNotCapture(F, 2);
1208 case LibFunc::memcpy:
1209 case LibFunc::memccpy:
1210 case LibFunc::memmove:
1211 if (FTy->getNumParams() < 2 ||
1212 !FTy->getParamType(1)->isPointerTy())
1215 setDoesNotCapture(F, 2);
1216 setOnlyReadsMemory(F, 2);
1218 case LibFunc::memalign:
1219 if (!FTy->getReturnType()->isPointerTy())
1221 setDoesNotAlias(F, 0);
1223 case LibFunc::mkdir:
1224 if (FTy->getNumParams() == 0 ||
1225 !FTy->getParamType(0)->isPointerTy())
1228 setDoesNotCapture(F, 1);
1229 setOnlyReadsMemory(F, 1);
1231 case LibFunc::mktime:
1232 if (FTy->getNumParams() == 0 ||
1233 !FTy->getParamType(0)->isPointerTy())
1236 setDoesNotCapture(F, 1);
1238 case LibFunc::realloc:
1239 if (FTy->getNumParams() != 2 ||
1240 !FTy->getParamType(0)->isPointerTy() ||
1241 !FTy->getReturnType()->isPointerTy())
1244 setDoesNotAlias(F, 0);
1245 setDoesNotCapture(F, 1);
1248 if (FTy->getNumParams() != 3 ||
1249 !FTy->getParamType(1)->isPointerTy())
1251 // May throw; "read" is a valid pthread cancellation point.
1252 setDoesNotCapture(F, 2);
1254 case LibFunc::rewind:
1255 if (FTy->getNumParams() < 1 ||
1256 !FTy->getParamType(0)->isPointerTy())
1259 setDoesNotCapture(F, 1);
1261 case LibFunc::rmdir:
1262 case LibFunc::remove:
1263 case LibFunc::realpath:
1264 if (FTy->getNumParams() < 1 ||
1265 !FTy->getParamType(0)->isPointerTy())
1268 setDoesNotCapture(F, 1);
1269 setOnlyReadsMemory(F, 1);
1271 case LibFunc::rename:
1272 if (FTy->getNumParams() < 2 ||
1273 !FTy->getParamType(0)->isPointerTy() ||
1274 !FTy->getParamType(1)->isPointerTy())
1277 setDoesNotCapture(F, 1);
1278 setDoesNotCapture(F, 2);
1279 setOnlyReadsMemory(F, 1);
1280 setOnlyReadsMemory(F, 2);
1282 case LibFunc::readlink:
1283 if (FTy->getNumParams() < 2 ||
1284 !FTy->getParamType(0)->isPointerTy() ||
1285 !FTy->getParamType(1)->isPointerTy())
1288 setDoesNotCapture(F, 1);
1289 setDoesNotCapture(F, 2);
1290 setOnlyReadsMemory(F, 1);
1292 case LibFunc::write:
1293 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1295 // May throw; "write" is a valid pthread cancellation point.
1296 setDoesNotCapture(F, 2);
1297 setOnlyReadsMemory(F, 2);
1299 case LibFunc::bcopy:
1300 if (FTy->getNumParams() != 3 ||
1301 !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 ||
1311 !FTy->getParamType(0)->isPointerTy() ||
1312 !FTy->getParamType(1)->isPointerTy())
1315 setOnlyReadsMemory(F);
1316 setDoesNotCapture(F, 1);
1317 setDoesNotCapture(F, 2);
1319 case LibFunc::bzero:
1320 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1323 setDoesNotCapture(F, 1);
1325 case LibFunc::calloc:
1326 if (FTy->getNumParams() != 2 ||
1327 !FTy->getReturnType()->isPointerTy())
1330 setDoesNotAlias(F, 0);
1332 case LibFunc::chmod:
1333 case LibFunc::chown:
1334 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1337 setDoesNotCapture(F, 1);
1338 setOnlyReadsMemory(F, 1);
1340 case LibFunc::ctermid:
1341 case LibFunc::clearerr:
1342 case LibFunc::closedir:
1343 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1346 setDoesNotCapture(F, 1);
1351 case LibFunc::atoll:
1352 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1355 setOnlyReadsMemory(F);
1356 setDoesNotCapture(F, 1);
1358 case LibFunc::access:
1359 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1362 setDoesNotCapture(F, 1);
1363 setOnlyReadsMemory(F, 1);
1365 case LibFunc::fopen:
1366 if (FTy->getNumParams() != 2 ||
1367 !FTy->getReturnType()->isPointerTy() ||
1368 !FTy->getParamType(0)->isPointerTy() ||
1369 !FTy->getParamType(1)->isPointerTy())
1372 setDoesNotAlias(F, 0);
1373 setDoesNotCapture(F, 1);
1374 setDoesNotCapture(F, 2);
1375 setOnlyReadsMemory(F, 1);
1376 setOnlyReadsMemory(F, 2);
1378 case LibFunc::fdopen:
1379 if (FTy->getNumParams() != 2 ||
1380 !FTy->getReturnType()->isPointerTy() ||
1381 !FTy->getParamType(1)->isPointerTy())
1384 setDoesNotAlias(F, 0);
1385 setDoesNotCapture(F, 2);
1386 setOnlyReadsMemory(F, 2);
1390 case LibFunc::fseek:
1391 case LibFunc::ftell:
1392 case LibFunc::fgetc:
1393 case LibFunc::fseeko:
1394 case LibFunc::ftello:
1395 case LibFunc::fileno:
1396 case LibFunc::fflush:
1397 case LibFunc::fclose:
1398 case LibFunc::fsetpos:
1399 case LibFunc::flockfile:
1400 case LibFunc::funlockfile:
1401 case LibFunc::ftrylockfile:
1402 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1405 setDoesNotCapture(F, 1);
1407 case LibFunc::ferror:
1408 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1411 setDoesNotCapture(F, 1);
1412 setOnlyReadsMemory(F);
1414 case LibFunc::fputc:
1415 case LibFunc::fstat:
1416 case LibFunc::frexp:
1417 case LibFunc::frexpf:
1418 case LibFunc::frexpl:
1419 case LibFunc::fstatvfs:
1420 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1423 setDoesNotCapture(F, 2);
1425 case LibFunc::fgets:
1426 if (FTy->getNumParams() != 3 ||
1427 !FTy->getParamType(0)->isPointerTy() ||
1428 !FTy->getParamType(2)->isPointerTy())
1431 setDoesNotCapture(F, 3);
1433 case LibFunc::fread:
1434 if (FTy->getNumParams() != 4 ||
1435 !FTy->getParamType(0)->isPointerTy() ||
1436 !FTy->getParamType(3)->isPointerTy())
1439 setDoesNotCapture(F, 1);
1440 setDoesNotCapture(F, 4);
1442 case LibFunc::fwrite:
1443 if (FTy->getNumParams() != 4 ||
1444 !FTy->getParamType(0)->isPointerTy() ||
1445 !FTy->getParamType(3)->isPointerTy())
1448 setDoesNotCapture(F, 1);
1449 setDoesNotCapture(F, 4);
1451 case LibFunc::fputs:
1452 if (FTy->getNumParams() < 2 ||
1453 !FTy->getParamType(0)->isPointerTy() ||
1454 !FTy->getParamType(1)->isPointerTy())
1457 setDoesNotCapture(F, 1);
1458 setDoesNotCapture(F, 2);
1459 setOnlyReadsMemory(F, 1);
1461 case LibFunc::fscanf:
1462 case LibFunc::fprintf:
1463 if (FTy->getNumParams() < 2 ||
1464 !FTy->getParamType(0)->isPointerTy() ||
1465 !FTy->getParamType(1)->isPointerTy())
1468 setDoesNotCapture(F, 1);
1469 setDoesNotCapture(F, 2);
1470 setOnlyReadsMemory(F, 2);
1472 case LibFunc::fgetpos:
1473 if (FTy->getNumParams() < 2 ||
1474 !FTy->getParamType(0)->isPointerTy() ||
1475 !FTy->getParamType(1)->isPointerTy())
1478 setDoesNotCapture(F, 1);
1479 setDoesNotCapture(F, 2);
1482 case LibFunc::getlogin_r:
1483 case LibFunc::getc_unlocked:
1484 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1487 setDoesNotCapture(F, 1);
1489 case LibFunc::getenv:
1490 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1493 setOnlyReadsMemory(F);
1494 setDoesNotCapture(F, 1);
1497 case LibFunc::getchar:
1500 case LibFunc::getitimer:
1501 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1504 setDoesNotCapture(F, 2);
1506 case LibFunc::getpwnam:
1507 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1510 setDoesNotCapture(F, 1);
1511 setOnlyReadsMemory(F, 1);
1513 case LibFunc::ungetc:
1514 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1517 setDoesNotCapture(F, 2);
1519 case LibFunc::uname:
1520 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1523 setDoesNotCapture(F, 1);
1525 case LibFunc::unlink:
1526 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1529 setDoesNotCapture(F, 1);
1530 setOnlyReadsMemory(F, 1);
1532 case LibFunc::unsetenv:
1533 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1536 setDoesNotCapture(F, 1);
1537 setOnlyReadsMemory(F, 1);
1539 case LibFunc::utime:
1540 case LibFunc::utimes:
1541 if (FTy->getNumParams() != 2 ||
1542 !FTy->getParamType(0)->isPointerTy() ||
1543 !FTy->getParamType(1)->isPointerTy())
1546 setDoesNotCapture(F, 1);
1547 setDoesNotCapture(F, 2);
1548 setOnlyReadsMemory(F, 1);
1549 setOnlyReadsMemory(F, 2);
1552 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1555 setDoesNotCapture(F, 2);
1558 case LibFunc::printf:
1559 case LibFunc::perror:
1560 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1563 setDoesNotCapture(F, 1);
1564 setOnlyReadsMemory(F, 1);
1566 case LibFunc::pread:
1567 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1569 // May throw; "pread" is a valid pthread cancellation point.
1570 setDoesNotCapture(F, 2);
1572 case LibFunc::pwrite:
1573 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1575 // May throw; "pwrite" is a valid pthread cancellation point.
1576 setDoesNotCapture(F, 2);
1577 setOnlyReadsMemory(F, 2);
1579 case LibFunc::putchar:
1582 case LibFunc::popen:
1583 if (FTy->getNumParams() != 2 ||
1584 !FTy->getReturnType()->isPointerTy() ||
1585 !FTy->getParamType(0)->isPointerTy() ||
1586 !FTy->getParamType(1)->isPointerTy())
1589 setDoesNotAlias(F, 0);
1590 setDoesNotCapture(F, 1);
1591 setDoesNotCapture(F, 2);
1592 setOnlyReadsMemory(F, 1);
1593 setOnlyReadsMemory(F, 2);
1595 case LibFunc::pclose:
1596 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1599 setDoesNotCapture(F, 1);
1601 case LibFunc::vscanf:
1602 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1605 setDoesNotCapture(F, 1);
1606 setOnlyReadsMemory(F, 1);
1608 case LibFunc::vsscanf:
1609 if (FTy->getNumParams() != 3 ||
1610 !FTy->getParamType(1)->isPointerTy() ||
1611 !FTy->getParamType(2)->isPointerTy())
1614 setDoesNotCapture(F, 1);
1615 setDoesNotCapture(F, 2);
1616 setOnlyReadsMemory(F, 1);
1617 setOnlyReadsMemory(F, 2);
1619 case LibFunc::vfscanf:
1620 if (FTy->getNumParams() != 3 ||
1621 !FTy->getParamType(1)->isPointerTy() ||
1622 !FTy->getParamType(2)->isPointerTy())
1625 setDoesNotCapture(F, 1);
1626 setDoesNotCapture(F, 2);
1627 setOnlyReadsMemory(F, 2);
1629 case LibFunc::valloc:
1630 if (!FTy->getReturnType()->isPointerTy())
1633 setDoesNotAlias(F, 0);
1635 case LibFunc::vprintf:
1636 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1639 setDoesNotCapture(F, 1);
1640 setOnlyReadsMemory(F, 1);
1642 case LibFunc::vfprintf:
1643 case LibFunc::vsprintf:
1644 if (FTy->getNumParams() != 3 ||
1645 !FTy->getParamType(0)->isPointerTy() ||
1646 !FTy->getParamType(1)->isPointerTy())
1649 setDoesNotCapture(F, 1);
1650 setDoesNotCapture(F, 2);
1651 setOnlyReadsMemory(F, 2);
1653 case LibFunc::vsnprintf:
1654 if (FTy->getNumParams() != 4 ||
1655 !FTy->getParamType(0)->isPointerTy() ||
1656 !FTy->getParamType(2)->isPointerTy())
1659 setDoesNotCapture(F, 1);
1660 setDoesNotCapture(F, 3);
1661 setOnlyReadsMemory(F, 3);
1664 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1666 // May throw; "open" is a valid pthread cancellation point.
1667 setDoesNotCapture(F, 1);
1668 setOnlyReadsMemory(F, 1);
1670 case LibFunc::opendir:
1671 if (FTy->getNumParams() != 1 ||
1672 !FTy->getReturnType()->isPointerTy() ||
1673 !FTy->getParamType(0)->isPointerTy())
1676 setDoesNotAlias(F, 0);
1677 setDoesNotCapture(F, 1);
1678 setOnlyReadsMemory(F, 1);
1680 case LibFunc::tmpfile:
1681 if (!FTy->getReturnType()->isPointerTy())
1684 setDoesNotAlias(F, 0);
1686 case LibFunc::times:
1687 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1690 setDoesNotCapture(F, 1);
1692 case LibFunc::htonl:
1693 case LibFunc::htons:
1694 case LibFunc::ntohl:
1695 case LibFunc::ntohs:
1697 setDoesNotAccessMemory(F);
1699 case LibFunc::lstat:
1700 if (FTy->getNumParams() != 2 ||
1701 !FTy->getParamType(0)->isPointerTy() ||
1702 !FTy->getParamType(1)->isPointerTy())
1705 setDoesNotCapture(F, 1);
1706 setDoesNotCapture(F, 2);
1707 setOnlyReadsMemory(F, 1);
1709 case LibFunc::lchown:
1710 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1713 setDoesNotCapture(F, 1);
1714 setOnlyReadsMemory(F, 1);
1716 case LibFunc::qsort:
1717 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1719 // May throw; places call through function pointer.
1720 setDoesNotCapture(F, 4);
1722 case LibFunc::dunder_strdup:
1723 case LibFunc::dunder_strndup:
1724 if (FTy->getNumParams() < 1 ||
1725 !FTy->getReturnType()->isPointerTy() ||
1726 !FTy->getParamType(0)->isPointerTy())
1729 setDoesNotAlias(F, 0);
1730 setDoesNotCapture(F, 1);
1731 setOnlyReadsMemory(F, 1);
1733 case LibFunc::dunder_strtok_r:
1734 if (FTy->getNumParams() != 3 ||
1735 !FTy->getParamType(1)->isPointerTy())
1738 setDoesNotCapture(F, 2);
1739 setOnlyReadsMemory(F, 2);
1741 case LibFunc::under_IO_getc:
1742 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1745 setDoesNotCapture(F, 1);
1747 case LibFunc::under_IO_putc:
1748 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1751 setDoesNotCapture(F, 2);
1753 case LibFunc::dunder_isoc99_scanf:
1754 if (FTy->getNumParams() < 1 ||
1755 !FTy->getParamType(0)->isPointerTy())
1758 setDoesNotCapture(F, 1);
1759 setOnlyReadsMemory(F, 1);
1761 case LibFunc::stat64:
1762 case LibFunc::lstat64:
1763 case LibFunc::statvfs64:
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);
1773 case LibFunc::dunder_isoc99_sscanf:
1774 if (FTy->getNumParams() < 1 ||
1775 !FTy->getParamType(0)->isPointerTy() ||
1776 !FTy->getParamType(1)->isPointerTy())
1779 setDoesNotCapture(F, 1);
1780 setDoesNotCapture(F, 2);
1781 setOnlyReadsMemory(F, 1);
1782 setOnlyReadsMemory(F, 2);
1784 case LibFunc::fopen64:
1785 if (FTy->getNumParams() != 2 ||
1786 !FTy->getReturnType()->isPointerTy() ||
1787 !FTy->getParamType(0)->isPointerTy() ||
1788 !FTy->getParamType(1)->isPointerTy())
1791 setDoesNotAlias(F, 0);
1792 setDoesNotCapture(F, 1);
1793 setDoesNotCapture(F, 2);
1794 setOnlyReadsMemory(F, 1);
1795 setOnlyReadsMemory(F, 2);
1797 case LibFunc::fseeko64:
1798 case LibFunc::ftello64:
1799 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1802 setDoesNotCapture(F, 1);
1804 case LibFunc::tmpfile64:
1805 if (!FTy->getReturnType()->isPointerTy())
1808 setDoesNotAlias(F, 0);
1810 case LibFunc::fstat64:
1811 case LibFunc::fstatvfs64:
1812 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1815 setDoesNotCapture(F, 2);
1817 case LibFunc::open64:
1818 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1820 // May throw; "open" is a valid pthread cancellation point.
1821 setDoesNotCapture(F, 1);
1822 setOnlyReadsMemory(F, 1);
1824 case LibFunc::gettimeofday:
1825 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1826 !FTy->getParamType(1)->isPointerTy())
1828 // Currently some platforms have the restrict keyword on the arguments to
1829 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1832 setDoesNotCapture(F, 1);
1833 setDoesNotCapture(F, 2);
1836 // Didn't mark any attributes.
1843 /// annotateLibraryCalls - Adds attributes to well-known standard library
1844 /// call declarations.
1845 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1846 bool MadeChange = false;
1848 // Check each function in turn annotating well-known library function
1849 // declarations with attributes.
1850 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1851 Function *F = (*I)->getFunction();
1853 if (F && F->isDeclaration())
1854 MadeChange |= inferPrototypeAttributes(*F);
1860 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1861 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1863 bool Changed = annotateLibraryCalls(SCC);
1864 Changed |= AddReadAttrs(SCC);
1865 Changed |= AddArgumentAttrs(SCC);
1866 Changed |= AddNoAliasAttrs(SCC);
1867 Changed |= AddNonNullAttrs(SCC);