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/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/CallGraph.h"
28 #include "llvm/Analysis/CaptureTracking.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/UniqueVector.h"
32 #include "llvm/Support/InstIterator.h"
35 STATISTIC(NumReadNone, "Number of functions marked readnone");
36 STATISTIC(NumReadOnly, "Number of functions marked readonly");
37 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
38 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
41 struct FunctionAttrs : public CallGraphSCCPass {
42 static char ID; // Pass identification, replacement for typeid
43 FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {
44 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
47 // runOnSCC - Analyze the SCC, performing the transformation if possible.
48 bool runOnSCC(CallGraphSCC &SCC);
50 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
51 bool AddReadAttrs(const CallGraphSCC &SCC);
53 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
54 bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
56 // IsFunctionMallocLike - Does this function allocate new memory?
57 bool IsFunctionMallocLike(Function *F,
58 SmallPtrSet<Function*, 8> &) const;
60 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
61 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired<AliasAnalysis>();
66 CallGraphSCCPass::getAnalysisUsage(AU);
69 bool PointsToLocalOrConstantMemory(Value *V);
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 /// PointsToLocalOrConstantMemory - Returns whether the given pointer value
87 /// points to memory that is local to the function, with global constants being
88 /// considered local to all functions.
89 bool FunctionAttrs::PointsToLocalOrConstantMemory(Value *V) {
90 SmallVector<Value*, 16> Worklist;
91 unsigned MaxLookup = 8;
93 Worklist.push_back(V);
96 V = Worklist.pop_back_val()->getUnderlyingObject();
98 // An alloca instruction defines local memory.
99 if (isa<AllocaInst>(V))
102 // A global constant counts as local memory for our purposes.
103 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
104 if (!GV->isConstant())
109 // If both select values point to local memory, then so does the select.
110 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
111 Worklist.push_back(SI->getTrueValue());
112 Worklist.push_back(SI->getFalseValue());
116 // If all values incoming to a phi node point to local memory, then so does
118 if (PHINode *PN = dyn_cast<PHINode>(V)) {
119 // Don't bother inspecting phi nodes with many operands.
120 if (PN->getNumIncomingValues() > MaxLookup)
122 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
123 Worklist.push_back(PN->getIncomingValue(i));
128 } while (!Worklist.empty() && --MaxLookup);
130 return Worklist.empty();
133 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
134 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
135 SmallPtrSet<Function*, 8> SCCNodes;
137 // Fill SCCNodes with the elements of the SCC. Used for quickly
138 // looking up whether a given CallGraphNode is in this SCC.
139 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
140 SCCNodes.insert((*I)->getFunction());
142 // Check if any of the functions in the SCC read or write memory. If they
143 // write memory then they can't be marked readnone or readonly.
144 bool ReadsMemory = false;
145 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
146 Function *F = (*I)->getFunction();
149 // External node - may write memory. Just give up.
152 if (F->doesNotAccessMemory())
156 // Definitions with weak linkage may be overridden at linktime with
157 // something that writes memory, so treat them like declarations.
158 if (F->isDeclaration() || F->mayBeOverridden()) {
159 if (!F->onlyReadsMemory())
160 // May write memory. Just give up.
167 // Scan the function body for instructions that may read or write memory.
168 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
169 Instruction *I = &*II;
171 // Some instructions can be ignored even if they read or write memory.
172 // Detect these now, skipping to the next instruction if one is found.
173 CallSite CS(cast<Value>(I));
175 // Ignore calls to functions in the same SCC.
176 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
178 switch (AA->getModRefBehavior(CS)) {
179 case AliasAnalysis::DoesNotAccessMemory:
180 // Ignore calls that don't access memory.
182 case AliasAnalysis::OnlyReadsMemory:
183 // Handle calls that only read from memory.
186 case AliasAnalysis::AccessesArguments:
187 // Check whether all pointer arguments point to local memory, and
188 // ignore calls that only access local memory.
189 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
192 if (Arg->getType()->isPointerTy() &&
193 !PointsToLocalOrConstantMemory(Arg))
194 // Writes memory. Just give up.
197 // Only reads and writes local memory.
200 // Otherwise, be conservative.
203 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
204 // Ignore non-volatile loads from local memory.
205 if (!LI->isVolatile() &&
206 PointsToLocalOrConstantMemory(LI->getPointerOperand()))
208 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
209 // Ignore non-volatile stores to local memory.
210 if (!SI->isVolatile() &&
211 PointsToLocalOrConstantMemory(SI->getPointerOperand()))
215 // Any remaining instructions need to be taken seriously! Check if they
216 // read or write memory.
217 if (I->mayWriteToMemory())
218 // Writes memory. Just give up.
221 // If this instruction may read memory, remember that.
222 ReadsMemory |= I->mayReadFromMemory();
226 // Success! Functions in this SCC do not access memory, or only read memory.
227 // Give them the appropriate attribute.
228 bool MadeChange = false;
229 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
230 Function *F = (*I)->getFunction();
232 if (F->doesNotAccessMemory())
236 if (F->onlyReadsMemory() && ReadsMemory)
242 // Clear out any existing attributes.
243 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
245 // Add in the new attribute.
246 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
257 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
258 bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
259 bool Changed = false;
261 // Check each function in turn, determining which pointer arguments are not
263 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
264 Function *F = (*I)->getFunction();
267 // External node - skip it;
270 // Definitions with weak linkage may be overridden at linktime with
271 // something that writes memory, so treat them like declarations.
272 if (F->isDeclaration() || F->mayBeOverridden())
275 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
276 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
277 !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
278 A->addAttr(Attribute::NoCapture);
287 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
288 /// or a pointer that doesn't alias any other pointer visible to the caller.
289 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
290 SmallPtrSet<Function*, 8> &SCCNodes) const {
291 UniqueVector<Value *> FlowsToReturn;
292 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
293 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
294 FlowsToReturn.insert(Ret->getReturnValue());
296 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
297 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
299 if (Constant *C = dyn_cast<Constant>(RetVal)) {
300 if (!C->isNullValue() && !isa<UndefValue>(C))
306 if (isa<Argument>(RetVal))
309 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
310 switch (RVI->getOpcode()) {
311 // Extend the analysis by looking upwards.
312 case Instruction::BitCast:
313 case Instruction::GetElementPtr:
314 FlowsToReturn.insert(RVI->getOperand(0));
316 case Instruction::Select: {
317 SelectInst *SI = cast<SelectInst>(RVI);
318 FlowsToReturn.insert(SI->getTrueValue());
319 FlowsToReturn.insert(SI->getFalseValue());
322 case Instruction::PHI: {
323 PHINode *PN = cast<PHINode>(RVI);
324 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
325 FlowsToReturn.insert(PN->getIncomingValue(i));
329 // Check whether the pointer came from an allocation.
330 case Instruction::Alloca:
332 case Instruction::Call:
333 case Instruction::Invoke: {
335 if (CS.paramHasAttr(0, Attribute::NoAlias))
337 if (CS.getCalledFunction() &&
338 SCCNodes.count(CS.getCalledFunction()))
342 return false; // Did not come from an allocation.
345 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
352 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
353 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
354 SmallPtrSet<Function*, 8> SCCNodes;
356 // Fill SCCNodes with the elements of the SCC. Used for quickly
357 // looking up whether a given CallGraphNode is in this SCC.
358 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
359 SCCNodes.insert((*I)->getFunction());
361 // Check each function in turn, determining which functions return noalias
363 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
364 Function *F = (*I)->getFunction();
367 // External node - skip it;
371 if (F->doesNotAlias(0))
374 // Definitions with weak linkage may be overridden at linktime, so
375 // treat them like declarations.
376 if (F->isDeclaration() || F->mayBeOverridden())
379 // We annotate noalias return values, which are only applicable to
381 if (!F->getReturnType()->isPointerTy())
384 if (!IsFunctionMallocLike(F, SCCNodes))
388 bool MadeChange = false;
389 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
390 Function *F = (*I)->getFunction();
391 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
394 F->setDoesNotAlias(0);
402 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
403 AA = &getAnalysis<AliasAnalysis>();
405 bool Changed = AddReadAttrs(SCC);
406 Changed |= AddNoCaptureAttrs(SCC);
407 Changed |= AddNoAliasAttrs(SCC);