1 //===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===//
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. In addition,
13 // it marks function arguments (of pointer type) 'nocapture' if a call
14 // to the function does not create any copies of the pointer value that
15 // outlive the call. This more or less means that the pointer is only
16 // dereferenced, and not returned from the function or stored in a global.
17 // This pass is implemented as a bottom-up traversal of the call-graph.
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "functionattrs"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/ADT/SCCIterator.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/CallGraph.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/CallGraphSCCPass.h"
31 #include "llvm/GlobalVariable.h"
32 #include "llvm/IntrinsicInst.h"
33 #include "llvm/LLVMContext.h"
34 #include "llvm/Support/InstIterator.h"
37 STATISTIC(NumReadNone, "Number of functions marked readnone");
38 STATISTIC(NumReadOnly, "Number of functions marked readonly");
39 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
40 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
43 struct FunctionAttrs : public CallGraphSCCPass {
44 static char ID; // Pass identification, replacement for typeid
45 FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {
46 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
49 // runOnSCC - Analyze the SCC, performing the transformation if possible.
50 bool runOnSCC(CallGraphSCC &SCC);
52 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
53 bool AddReadAttrs(const CallGraphSCC &SCC);
55 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
56 bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
58 // IsFunctionMallocLike - Does this function allocate new memory?
59 bool IsFunctionMallocLike(Function *F,
60 SmallPtrSet<Function*, 8> &) const;
62 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
63 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequired<AliasAnalysis>();
68 CallGraphSCCPass::getAnalysisUsage(AU);
76 char FunctionAttrs::ID = 0;
77 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
78 "Deduce function attributes", false, false)
79 INITIALIZE_AG_DEPENDENCY(CallGraph)
80 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
81 "Deduce function attributes", false, false)
83 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
86 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
87 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
88 SmallPtrSet<Function*, 8> SCCNodes;
90 // Fill SCCNodes with the elements of the SCC. Used for quickly
91 // looking up whether a given CallGraphNode is in this SCC.
92 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
93 SCCNodes.insert((*I)->getFunction());
95 // Check if any of the functions in the SCC read or write memory. If they
96 // write memory then they can't be marked readnone or readonly.
97 bool ReadsMemory = false;
98 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
99 Function *F = (*I)->getFunction();
102 // External node - may write memory. Just give up.
105 AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(F);
106 if (MRB == AliasAnalysis::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))
114 // May write memory. Just give up.
121 // Scan the function body for instructions that may read or write memory.
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 AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(CS);
133 // If the call doesn't access arbitrary memory, we may be able to
134 // figure out something.
135 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
136 // If the call does access argument pointees, check each argument.
137 if (AliasAnalysis::doesAccessArgPointees(MRB))
138 // Check whether all pointer arguments point to local memory, and
139 // ignore calls that only access local memory.
140 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
143 if (Arg->getType()->isPointerTy()) {
144 AliasAnalysis::Location Loc(Arg,
145 AliasAnalysis::UnknownSize,
146 I->getMetadata(LLVMContext::MD_tbaa));
147 if (!AA->pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
148 if (MRB & AliasAnalysis::Mod)
149 // Writes non-local memory. Give up.
151 if (MRB & AliasAnalysis::Ref)
152 // Ok, it reads non-local memory.
159 // The call could access any memory. If that includes writes, give up.
160 if (MRB & AliasAnalysis::Mod)
162 // If it reads, note it.
163 if (MRB & AliasAnalysis::Ref)
166 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
167 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
168 if (!LI->isVolatile()) {
169 AliasAnalysis::Location Loc = AA->getLocation(LI);
170 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
173 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
174 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
175 if (!SI->isVolatile()) {
176 AliasAnalysis::Location Loc = AA->getLocation(SI);
177 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
180 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
181 // Ignore vaargs on local memory.
182 AliasAnalysis::Location Loc = AA->getLocation(VI);
183 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
187 // Any remaining instructions need to be taken seriously! Check if they
188 // read or write memory.
189 if (I->mayWriteToMemory())
190 // Writes memory. Just give up.
193 // If this instruction may read memory, remember that.
194 ReadsMemory |= I->mayReadFromMemory();
198 // Success! Functions in this SCC do not access memory, or only read memory.
199 // Give them the appropriate attribute.
200 bool MadeChange = false;
201 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
202 Function *F = (*I)->getFunction();
204 if (F->doesNotAccessMemory())
208 if (F->onlyReadsMemory() && ReadsMemory)
214 // Clear out any existing attributes.
216 B.addAttribute(Attribute::ReadOnly)
217 .addAttribute(Attribute::ReadNone);
218 F->removeAttribute(AttributeSet::FunctionIndex,
219 Attribute::get(F->getContext(), B));
221 // Add in the new attribute.
223 B.addAttribute(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
224 F->addAttribute(AttributeSet::FunctionIndex,
225 Attribute::get(F->getContext(), B));
237 // For a given pointer Argument, this retains a list of Arguments of functions
238 // in the same SCC that the pointer data flows into. We use this to build an
239 // SCC of the arguments.
240 struct ArgumentGraphNode {
241 Argument *Definition;
242 SmallVector<ArgumentGraphNode*, 4> Uses;
245 class ArgumentGraph {
246 // We store pointers to ArgumentGraphNode objects, so it's important that
247 // that they not move around upon insert.
248 typedef std::map<Argument*, ArgumentGraphNode> ArgumentMapTy;
250 ArgumentMapTy ArgumentMap;
252 // There is no root node for the argument graph, in fact:
253 // void f(int *x, int *y) { if (...) f(x, y); }
254 // is an example where the graph is disconnected. The SCCIterator requires a
255 // single entry point, so we maintain a fake ("synthetic") root node that
256 // uses every node. Because the graph is directed and nothing points into
257 // the root, it will not participate in any SCCs (except for its own).
258 ArgumentGraphNode SyntheticRoot;
261 ArgumentGraph() { SyntheticRoot.Definition = 0; }
263 typedef SmallVectorImpl<ArgumentGraphNode*>::iterator iterator;
265 iterator begin() { return SyntheticRoot.Uses.begin(); }
266 iterator end() { return SyntheticRoot.Uses.end(); }
267 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
269 ArgumentGraphNode *operator[](Argument *A) {
270 ArgumentGraphNode &Node = ArgumentMap[A];
272 SyntheticRoot.Uses.push_back(&Node);
277 // This tracker checks whether callees are in the SCC, and if so it does not
278 // consider that a capture, instead adding it to the "Uses" list and
279 // continuing with the analysis.
280 struct ArgumentUsesTracker : public CaptureTracker {
281 ArgumentUsesTracker(const SmallPtrSet<Function*, 8> &SCCNodes)
282 : Captured(false), SCCNodes(SCCNodes) {}
284 void tooManyUses() { Captured = true; }
286 bool captured(Use *U) {
287 CallSite CS(U->getUser());
288 if (!CS.getInstruction()) { Captured = true; return true; }
290 Function *F = CS.getCalledFunction();
291 if (!F || !SCCNodes.count(F)) { Captured = true; return true; }
293 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
294 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
295 PI != PE; ++PI, ++AI) {
297 assert(F->isVarArg() && "More params than args in non-varargs call");
306 assert(!Uses.empty() && "Capturing call-site captured nothing?");
310 bool Captured; // True only if certainly captured (used outside our SCC).
311 SmallVector<Argument*, 4> Uses; // Uses within our SCC.
313 const SmallPtrSet<Function*, 8> &SCCNodes;
318 template<> struct GraphTraits<ArgumentGraphNode*> {
319 typedef ArgumentGraphNode NodeType;
320 typedef SmallVectorImpl<ArgumentGraphNode*>::iterator ChildIteratorType;
322 static inline NodeType *getEntryNode(NodeType *A) { return A; }
323 static inline ChildIteratorType child_begin(NodeType *N) {
324 return N->Uses.begin();
326 static inline ChildIteratorType child_end(NodeType *N) {
327 return N->Uses.end();
330 template<> struct GraphTraits<ArgumentGraph*>
331 : public GraphTraits<ArgumentGraphNode*> {
332 static NodeType *getEntryNode(ArgumentGraph *AG) {
333 return AG->getEntryNode();
335 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
338 static ChildIteratorType nodes_end(ArgumentGraph *AG) {
344 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
345 bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
346 bool Changed = false;
348 SmallPtrSet<Function*, 8> SCCNodes;
350 // Fill SCCNodes with the elements of the SCC. Used for quickly
351 // looking up whether a given CallGraphNode is in this SCC.
352 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
353 Function *F = (*I)->getFunction();
354 if (F && !F->isDeclaration() && !F->mayBeOverridden())
361 B.addAttribute(Attribute::NoCapture);
363 // Check each function in turn, determining which pointer arguments are not
365 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
366 Function *F = (*I)->getFunction();
369 // External node - only a problem for arguments that we pass to it.
372 // Definitions with weak linkage may be overridden at linktime with
373 // something that captures pointers, so treat them like declarations.
374 if (F->isDeclaration() || F->mayBeOverridden())
377 // Functions that are readonly (or readnone) and nounwind and don't return
378 // a value can't capture arguments. Don't analyze them.
379 if (F->onlyReadsMemory() && F->doesNotThrow() &&
380 F->getReturnType()->isVoidTy()) {
381 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end();
383 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
384 A->addAttr(Attribute::get(F->getContext(), B));
392 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
393 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
394 ArgumentUsesTracker Tracker(SCCNodes);
395 PointerMayBeCaptured(A, &Tracker);
396 if (!Tracker.Captured) {
397 if (Tracker.Uses.empty()) {
398 // If it's trivially not captured, mark it nocapture now.
399 A->addAttr(Attribute::get(F->getContext(), B));
403 // If it's not trivially captured and not trivially not captured,
404 // then it must be calling into another function in our SCC. Save
405 // its particulars for Argument-SCC analysis later.
406 ArgumentGraphNode *Node = AG[A];
407 for (SmallVectorImpl<Argument*>::iterator UI = Tracker.Uses.begin(),
408 UE = Tracker.Uses.end(); UI != UE; ++UI)
409 Node->Uses.push_back(AG[*UI]);
412 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
416 // The graph we've collected is partial because we stopped scanning for
417 // argument uses once we solved the argument trivially. These partial nodes
418 // show up as ArgumentGraphNode objects with an empty Uses list, and for
419 // these nodes the final decision about whether they capture has already been
420 // made. If the definition doesn't have a 'nocapture' attribute by now, it
423 for (scc_iterator<ArgumentGraph*> I = scc_begin(&AG), E = scc_end(&AG);
425 std::vector<ArgumentGraphNode*> &ArgumentSCC = *I;
426 if (ArgumentSCC.size() == 1) {
427 if (!ArgumentSCC[0]->Definition) continue; // synthetic root node
429 // eg. "void f(int* x) { if (...) f(x); }"
430 if (ArgumentSCC[0]->Uses.size() == 1 &&
431 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
434 addAttr(Attribute::get(ArgumentSCC[0]->Definition->getContext(), B));
441 bool SCCCaptured = false;
442 for (std::vector<ArgumentGraphNode*>::iterator I = ArgumentSCC.begin(),
443 E = ArgumentSCC.end(); I != E && !SCCCaptured; ++I) {
444 ArgumentGraphNode *Node = *I;
445 if (Node->Uses.empty()) {
446 if (!Node->Definition->hasNoCaptureAttr())
450 if (SCCCaptured) continue;
452 SmallPtrSet<Argument*, 8> ArgumentSCCNodes;
453 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
454 // quickly looking up whether a given Argument is in this ArgumentSCC.
455 for (std::vector<ArgumentGraphNode*>::iterator I = ArgumentSCC.begin(),
456 E = ArgumentSCC.end(); I != E; ++I) {
457 ArgumentSCCNodes.insert((*I)->Definition);
460 for (std::vector<ArgumentGraphNode*>::iterator I = ArgumentSCC.begin(),
461 E = ArgumentSCC.end(); I != E && !SCCCaptured; ++I) {
462 ArgumentGraphNode *N = *I;
463 for (SmallVectorImpl<ArgumentGraphNode*>::iterator UI = N->Uses.begin(),
464 UE = N->Uses.end(); UI != UE; ++UI) {
465 Argument *A = (*UI)->Definition;
466 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
472 if (SCCCaptured) continue;
474 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
475 Argument *A = ArgumentSCC[i]->Definition;
476 A->addAttr(Attribute::get(A->getContext(), B));
485 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
486 /// or a pointer that doesn't alias any other pointer visible to the caller.
487 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
488 SmallPtrSet<Function*, 8> &SCCNodes) const {
489 SmallSetVector<Value *, 8> FlowsToReturn;
490 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
491 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
492 FlowsToReturn.insert(Ret->getReturnValue());
494 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
495 Value *RetVal = FlowsToReturn[i];
497 if (Constant *C = dyn_cast<Constant>(RetVal)) {
498 if (!C->isNullValue() && !isa<UndefValue>(C))
504 if (isa<Argument>(RetVal))
507 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
508 switch (RVI->getOpcode()) {
509 // Extend the analysis by looking upwards.
510 case Instruction::BitCast:
511 case Instruction::GetElementPtr:
512 FlowsToReturn.insert(RVI->getOperand(0));
514 case Instruction::Select: {
515 SelectInst *SI = cast<SelectInst>(RVI);
516 FlowsToReturn.insert(SI->getTrueValue());
517 FlowsToReturn.insert(SI->getFalseValue());
520 case Instruction::PHI: {
521 PHINode *PN = cast<PHINode>(RVI);
522 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
523 FlowsToReturn.insert(PN->getIncomingValue(i));
527 // Check whether the pointer came from an allocation.
528 case Instruction::Alloca:
530 case Instruction::Call:
531 case Instruction::Invoke: {
533 if (CS.paramHasAttr(0, Attribute::NoAlias))
535 if (CS.getCalledFunction() &&
536 SCCNodes.count(CS.getCalledFunction()))
540 return false; // Did not come from an allocation.
543 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
550 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
551 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
552 SmallPtrSet<Function*, 8> SCCNodes;
554 // Fill SCCNodes with the elements of the SCC. Used for quickly
555 // looking up whether a given CallGraphNode is in this SCC.
556 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
557 SCCNodes.insert((*I)->getFunction());
559 // Check each function in turn, determining which functions return noalias
561 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
562 Function *F = (*I)->getFunction();
565 // External node - skip it;
569 if (F->doesNotAlias(0))
572 // Definitions with weak linkage may be overridden at linktime, so
573 // treat them like declarations.
574 if (F->isDeclaration() || F->mayBeOverridden())
577 // We annotate noalias return values, which are only applicable to
579 if (!F->getReturnType()->isPointerTy())
582 if (!IsFunctionMallocLike(F, SCCNodes))
586 bool MadeChange = false;
587 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
588 Function *F = (*I)->getFunction();
589 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
592 F->setDoesNotAlias(0);
600 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
601 AA = &getAnalysis<AliasAnalysis>();
603 bool Changed = AddReadAttrs(SCC);
604 Changed |= AddNoCaptureAttrs(SCC);
605 Changed |= AddNoAliasAttrs(SCC);