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/CallGraphSCCPass.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/CallGraph.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/UniqueVector.h"
33 #include "llvm/Support/InstIterator.h"
36 STATISTIC(NumReadNone, "Number of functions marked readnone");
37 STATISTIC(NumReadOnly, "Number of functions marked readonly");
38 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
39 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
42 struct FunctionAttrs : public CallGraphSCCPass {
43 static char ID; // Pass identification, replacement for typeid
44 FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {
45 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
48 // runOnSCC - Analyze the SCC, performing the transformation if possible.
49 bool runOnSCC(CallGraphSCC &SCC);
51 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
52 bool AddReadAttrs(const CallGraphSCC &SCC);
54 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
55 bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
57 // IsFunctionMallocLike - Does this function allocate new memory?
58 bool IsFunctionMallocLike(Function *F,
59 SmallPtrSet<Function*, 8> &) const;
61 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
62 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired<AliasAnalysis>();
67 CallGraphSCCPass::getAnalysisUsage(AU);
75 char FunctionAttrs::ID = 0;
76 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
77 "Deduce function attributes", false, false)
78 INITIALIZE_AG_DEPENDENCY(CallGraph)
79 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
80 "Deduce function attributes", false, false)
82 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
85 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
86 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
87 SmallPtrSet<Function*, 8> SCCNodes;
89 // Fill SCCNodes with the elements of the SCC. Used for quickly
90 // looking up whether a given CallGraphNode is in this SCC.
91 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
92 SCCNodes.insert((*I)->getFunction());
94 // Check if any of the functions in the SCC read or write memory. If they
95 // write memory then they can't be marked readnone or readonly.
96 bool ReadsMemory = false;
97 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
98 Function *F = (*I)->getFunction();
101 // External node - may write memory. Just give up.
104 if (F->doesNotAccessMemory())
108 // Definitions with weak linkage may be overridden at linktime with
109 // something that writes memory, so treat them like declarations.
110 if (F->isDeclaration() || F->mayBeOverridden()) {
111 if (!F->onlyReadsMemory())
112 // May write memory. Just give up.
119 // Scan the function body for instructions that may read or write memory.
120 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
121 Instruction *I = &*II;
123 // Some instructions can be ignored even if they read or write memory.
124 // Detect these now, skipping to the next instruction if one is found.
125 CallSite CS(cast<Value>(I));
127 // Ignore calls to functions in the same SCC.
128 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
130 switch (AA->getModRefBehavior(CS)) {
131 case AliasAnalysis::DoesNotAccessMemory:
132 // Ignore calls that don't access memory.
134 case AliasAnalysis::OnlyReadsMemory:
135 // Handle calls that only read from memory.
138 case AliasAnalysis::AccessesArguments:
139 // Check whether all pointer arguments point to local memory, and
140 // ignore calls that only access local memory.
141 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
144 if (Arg->getType()->isPointerTy()) {
145 AliasAnalysis::Location Loc(Arg,
146 AliasAnalysis::UnknownSize,
147 I->getMetadata(LLVMContext::MD_tbaa));
148 if (!AA->pointsToConstantMemory(Arg, /*OrLocal=*/true))
149 // Writes memory. Just give up.
153 // Only reads and writes local memory.
156 // Otherwise, be conservative.
159 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
160 // Ignore non-volatile loads from local memory.
161 if (!LI->isVolatile()) {
162 AliasAnalysis::Location Loc(LI->getPointerOperand(),
163 AA->getTypeStoreSize(LI->getType()),
164 LI->getMetadata(LLVMContext::MD_tbaa));
165 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
168 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
169 // Ignore non-volatile stores to local memory.
170 if (!SI->isVolatile()) {
171 const Type *StoredType = SI->getValueOperand()->getType();
172 AliasAnalysis::Location Loc(SI->getPointerOperand(),
173 AA->getTypeStoreSize(StoredType),
174 SI->getMetadata(LLVMContext::MD_tbaa));
175 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
180 // Any remaining instructions need to be taken seriously! Check if they
181 // read or write memory.
182 if (I->mayWriteToMemory())
183 // Writes memory. Just give up.
186 // If this instruction may read memory, remember that.
187 ReadsMemory |= I->mayReadFromMemory();
191 // Success! Functions in this SCC do not access memory, or only read memory.
192 // Give them the appropriate attribute.
193 bool MadeChange = false;
194 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
195 Function *F = (*I)->getFunction();
197 if (F->doesNotAccessMemory())
201 if (F->onlyReadsMemory() && ReadsMemory)
207 // Clear out any existing attributes.
208 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
210 // Add in the new attribute.
211 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
222 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
223 bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
224 bool Changed = false;
226 // Check each function in turn, determining which pointer arguments are not
228 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
229 Function *F = (*I)->getFunction();
232 // External node - skip it;
235 // Definitions with weak linkage may be overridden at linktime with
236 // something that writes memory, so treat them like declarations.
237 if (F->isDeclaration() || F->mayBeOverridden())
240 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
241 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
242 !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
243 A->addAttr(Attribute::NoCapture);
252 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
253 /// or a pointer that doesn't alias any other pointer visible to the caller.
254 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
255 SmallPtrSet<Function*, 8> &SCCNodes) const {
256 UniqueVector<Value *> FlowsToReturn;
257 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
258 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
259 FlowsToReturn.insert(Ret->getReturnValue());
261 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
262 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
264 if (Constant *C = dyn_cast<Constant>(RetVal)) {
265 if (!C->isNullValue() && !isa<UndefValue>(C))
271 if (isa<Argument>(RetVal))
274 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
275 switch (RVI->getOpcode()) {
276 // Extend the analysis by looking upwards.
277 case Instruction::BitCast:
278 case Instruction::GetElementPtr:
279 FlowsToReturn.insert(RVI->getOperand(0));
281 case Instruction::Select: {
282 SelectInst *SI = cast<SelectInst>(RVI);
283 FlowsToReturn.insert(SI->getTrueValue());
284 FlowsToReturn.insert(SI->getFalseValue());
287 case Instruction::PHI: {
288 PHINode *PN = cast<PHINode>(RVI);
289 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
290 FlowsToReturn.insert(PN->getIncomingValue(i));
294 // Check whether the pointer came from an allocation.
295 case Instruction::Alloca:
297 case Instruction::Call:
298 case Instruction::Invoke: {
300 if (CS.paramHasAttr(0, Attribute::NoAlias))
302 if (CS.getCalledFunction() &&
303 SCCNodes.count(CS.getCalledFunction()))
307 return false; // Did not come from an allocation.
310 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
317 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
318 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
319 SmallPtrSet<Function*, 8> SCCNodes;
321 // Fill SCCNodes with the elements of the SCC. Used for quickly
322 // looking up whether a given CallGraphNode is in this SCC.
323 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
324 SCCNodes.insert((*I)->getFunction());
326 // Check each function in turn, determining which functions return noalias
328 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
329 Function *F = (*I)->getFunction();
332 // External node - skip it;
336 if (F->doesNotAlias(0))
339 // Definitions with weak linkage may be overridden at linktime, so
340 // treat them like declarations.
341 if (F->isDeclaration() || F->mayBeOverridden())
344 // We annotate noalias return values, which are only applicable to
346 if (!F->getReturnType()->isPointerTy())
349 if (!IsFunctionMallocLike(F, SCCNodes))
353 bool MadeChange = false;
354 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
355 Function *F = (*I)->getFunction();
356 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
359 F->setDoesNotAlias(0);
367 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
368 AA = &getAnalysis<AliasAnalysis>();
370 bool Changed = AddReadAttrs(SCC);
371 Changed |= AddNoCaptureAttrs(SCC);
372 Changed |= AddNoAliasAttrs(SCC);