blob: 3c0e7ae799f68e7154092a21cbd7cf05cab765ef [file] [log] [blame]
Meador Inge6b6a1612013-03-21 00:55:59 +00001//===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
Duncan Sands44c8cd92008-12-31 16:14:43 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chandler Carruth1926b702016-01-08 10:55:52 +00009///
10/// \file
11/// This file implements interprocedural passes which walk the
12/// call-graph deducing and/or propagating function attributes.
13///
Duncan Sands44c8cd92008-12-31 16:14:43 +000014//===----------------------------------------------------------------------===//
15
Duncan Sands44c8cd92008-12-31 16:14:43 +000016#include "llvm/Transforms/IPO.h"
Nick Lewycky4c378a42011-12-28 23:24:21 +000017#include "llvm/ADT/SCCIterator.h"
Benjamin Kramer15591272012-10-31 13:45:49 +000018#include "llvm/ADT/SetVector.h"
Duncan Sandsb193a372009-01-02 11:54:37 +000019#include "llvm/ADT/SmallSet.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000020#include "llvm/ADT/Statistic.h"
James Molloy0ecdbe72015-11-19 08:49:57 +000021#include "llvm/ADT/StringSwitch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000023#include "llvm/Analysis/AssumptionCache.h"
24#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/CallGraph.h"
Chandler Carruth839a98e2013-01-07 15:26:48 +000026#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000028#include "llvm/Analysis/TargetLibraryInfo.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000029#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000031#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/LLVMContext.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000034#include "llvm/Support/Debug.h"
Hans Wennborg043bf5b2015-08-31 21:19:18 +000035#include "llvm/Support/raw_ostream.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000036#include "llvm/Analysis/TargetLibraryInfo.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000037using namespace llvm;
38
Chandler Carruth964daaa2014-04-22 02:55:47 +000039#define DEBUG_TYPE "functionattrs"
40
Duncan Sands44c8cd92008-12-31 16:14:43 +000041STATISTIC(NumReadNone, "Number of functions marked readnone");
42STATISTIC(NumReadOnly, "Number of functions marked readonly");
43STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
Nick Lewyckyc2ec0722013-07-06 00:29:58 +000044STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
45STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
Nick Lewyckyfbed86a2009-03-08 06:20:47 +000046STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Philip Reamesa88caea2015-08-31 19:44:38 +000047STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
James Molloy7e9bdd52015-11-12 10:55:20 +000048STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
Duncan Sands44c8cd92008-12-31 16:14:43 +000049
50namespace {
Chandler Carruthc518ebd2015-10-29 18:29:15 +000051typedef SmallSetVector<Function *, 8> SCCNodeSet;
52}
53
54namespace {
Chandler Carruth1926b702016-01-08 10:55:52 +000055struct PostOrderFunctionAttrs : public CallGraphSCCPass {
Chandler Carruth63559d72015-09-13 06:47:20 +000056 static char ID; // Pass identification, replacement for typeid
Chandler Carruth1926b702016-01-08 10:55:52 +000057 PostOrderFunctionAttrs() : CallGraphSCCPass(ID) {
58 initializePostOrderFunctionAttrsPass(*PassRegistry::getPassRegistry());
Chandler Carruth63559d72015-09-13 06:47:20 +000059 }
60
Chandler Carruth63559d72015-09-13 06:47:20 +000061 bool runOnSCC(CallGraphSCC &SCC) override;
Chandler Carruth1926b702016-01-08 10:55:52 +000062
Chandler Carruth63559d72015-09-13 06:47:20 +000063 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 AU.setPreservesCFG();
65 AU.addRequired<AssumptionCacheTracker>();
66 AU.addRequired<TargetLibraryInfoWrapperPass>();
Sanjoy Das1c481f52016-02-09 01:21:57 +000067 addUsedAAAnalyses(AU);
Chandler Carruth63559d72015-09-13 06:47:20 +000068 CallGraphSCCPass::getAnalysisUsage(AU);
69 }
Meador Inge6b6a1612013-03-21 00:55:59 +000070
Chandler Carruth63559d72015-09-13 06:47:20 +000071private:
72 TargetLibraryInfo *TLI;
73};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000074}
Duncan Sands44c8cd92008-12-31 16:14:43 +000075
Chandler Carruth1926b702016-01-08 10:55:52 +000076char PostOrderFunctionAttrs::ID = 0;
77INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrs, "functionattrs",
Chandler Carruth63559d72015-09-13 06:47:20 +000078 "Deduce function attributes", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +000079INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth6378cf52013-11-26 04:19:30 +000080INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000081INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth1926b702016-01-08 10:55:52 +000082INITIALIZE_PASS_END(PostOrderFunctionAttrs, "functionattrs",
Chandler Carruth63559d72015-09-13 06:47:20 +000083 "Deduce function attributes", false, false)
Duncan Sands44c8cd92008-12-31 16:14:43 +000084
Chandler Carruth1926b702016-01-08 10:55:52 +000085Pass *llvm::createPostOrderFunctionAttrsPass() { return new PostOrderFunctionAttrs(); }
Duncan Sands44c8cd92008-12-31 16:14:43 +000086
Chandler Carruth7542d372015-09-21 17:39:41 +000087namespace {
88/// The three kinds of memory access relevant to 'readonly' and
89/// 'readnone' attributes.
90enum MemoryAccessKind {
91 MAK_ReadNone = 0,
92 MAK_ReadOnly = 1,
93 MAK_MayWrite = 2
94};
95}
96
Chandler Carruthc518ebd2015-10-29 18:29:15 +000097static MemoryAccessKind checkFunctionMemoryAccess(Function &F, AAResults &AAR,
98 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +000099 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
100 if (MRB == FMRB_DoesNotAccessMemory)
101 // Already perfect!
102 return MAK_ReadNone;
103
104 // Definitions with weak linkage may be overridden at linktime with
105 // something that writes memory, so treat them like declarations.
106 if (F.isDeclaration() || F.mayBeOverridden()) {
107 if (AliasAnalysis::onlyReadsMemory(MRB))
108 return MAK_ReadOnly;
109
110 // Conservatively assume it writes to memory.
111 return MAK_MayWrite;
112 }
113
114 // Scan the function body for instructions that may read or write memory.
115 bool ReadsMemory = false;
116 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
117 Instruction *I = &*II;
118
119 // Some instructions can be ignored even if they read or write memory.
120 // Detect these now, skipping to the next instruction if one is found.
121 CallSite CS(cast<Value>(I));
122 if (CS) {
Sanjoy Das10c8a042016-02-09 18:40:40 +0000123 // Ignore calls to functions in the same SCC, as long as the call sites
124 // don't have operand bundles. Calls with operand bundles are allowed to
125 // have memory effects not described by the memory effects of the call
126 // target.
127 if (!CS.hasOperandBundles() && CS.getCalledFunction() &&
128 SCCNodes.count(CS.getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +0000129 continue;
130 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
Chandler Carruth7542d372015-09-21 17:39:41 +0000131
Chandler Carruth69798fb2015-10-27 01:41:43 +0000132 // If the call doesn't access memory, we're done.
133 if (!(MRB & MRI_ModRef))
134 continue;
135
136 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
137 // The call could access any memory. If that includes writes, give up.
138 if (MRB & MRI_Mod)
139 return MAK_MayWrite;
140 // If it reads, note it.
141 if (MRB & MRI_Ref)
142 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000143 continue;
144 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000145
146 // Check whether all pointer arguments point to local memory, and
147 // ignore calls that only access local memory.
148 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
149 CI != CE; ++CI) {
150 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000151 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000152 continue;
153
154 AAMDNodes AAInfo;
155 I->getAAMetadata(AAInfo);
156 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
157
158 // Skip accesses to local or constant memory as they don't impact the
159 // externally visible mod/ref behavior.
160 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
161 continue;
162
163 if (MRB & MRI_Mod)
164 // Writes non-local memory. Give up.
165 return MAK_MayWrite;
166 if (MRB & MRI_Ref)
167 // Ok, it reads non-local memory.
168 ReadsMemory = true;
169 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000170 continue;
171 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
172 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
173 if (!LI->isVolatile()) {
174 MemoryLocation Loc = MemoryLocation::get(LI);
175 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
176 continue;
177 }
178 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
179 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
180 if (!SI->isVolatile()) {
181 MemoryLocation Loc = MemoryLocation::get(SI);
182 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
183 continue;
184 }
185 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
186 // Ignore vaargs on local memory.
187 MemoryLocation Loc = MemoryLocation::get(VI);
188 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
189 continue;
190 }
191
192 // Any remaining instructions need to be taken seriously! Check if they
193 // read or write memory.
194 if (I->mayWriteToMemory())
195 // Writes memory. Just give up.
196 return MAK_MayWrite;
197
198 // If this instruction may read memory, remember that.
199 ReadsMemory |= I->mayReadFromMemory();
200 }
201
202 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
203}
204
Chandler Carrutha632fb92015-09-13 06:57:25 +0000205/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000206template <typename AARGetterT>
207static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000208 // Check if any of the functions in the SCC read or write memory. If they
209 // write memory then they can't be marked readnone or readonly.
210 bool ReadsMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000211 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000212 // Call the callable parameter to look up AA results for this function.
213 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000214
Chandler Carruth7542d372015-09-21 17:39:41 +0000215 switch (checkFunctionMemoryAccess(*F, AAR, SCCNodes)) {
216 case MAK_MayWrite:
217 return false;
218 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000219 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000220 break;
221 case MAK_ReadNone:
222 // Nothing to do!
223 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000224 }
225 }
226
227 // Success! Functions in this SCC do not access memory, or only read memory.
228 // Give them the appropriate attribute.
229 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000230 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000231 if (F->doesNotAccessMemory())
232 // Already perfect!
233 continue;
234
235 if (F->onlyReadsMemory() && ReadsMemory)
236 // No change.
237 continue;
238
239 MadeChange = true;
240
241 // Clear out any existing attributes.
Bill Wendling50d27842012-10-15 20:35:56 +0000242 AttrBuilder B;
Chandler Carruth63559d72015-09-13 06:47:20 +0000243 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
244 F->removeAttributes(
245 AttributeSet::FunctionIndex,
246 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
Duncan Sands44c8cd92008-12-31 16:14:43 +0000247
248 // Add in the new attribute.
Bill Wendlinge94d8432012-12-07 23:16:57 +0000249 F->addAttribute(AttributeSet::FunctionIndex,
Bill Wendlingc0e2a1f2013-01-23 00:20:53 +0000250 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000251
252 if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000253 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000254 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000255 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000256 }
257
258 return MadeChange;
259}
260
Nick Lewycky4c378a42011-12-28 23:24:21 +0000261namespace {
Chandler Carrutha632fb92015-09-13 06:57:25 +0000262/// For a given pointer Argument, this retains a list of Arguments of functions
263/// in the same SCC that the pointer data flows into. We use this to build an
264/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000265struct ArgumentGraphNode {
266 Argument *Definition;
267 SmallVector<ArgumentGraphNode *, 4> Uses;
268};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000269
Chandler Carruth63559d72015-09-13 06:47:20 +0000270class ArgumentGraph {
271 // We store pointers to ArgumentGraphNode objects, so it's important that
272 // that they not move around upon insert.
273 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000274
Chandler Carruth63559d72015-09-13 06:47:20 +0000275 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000276
Chandler Carruth63559d72015-09-13 06:47:20 +0000277 // There is no root node for the argument graph, in fact:
278 // void f(int *x, int *y) { if (...) f(x, y); }
279 // is an example where the graph is disconnected. The SCCIterator requires a
280 // single entry point, so we maintain a fake ("synthetic") root node that
281 // uses every node. Because the graph is directed and nothing points into
282 // the root, it will not participate in any SCCs (except for its own).
283 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000284
Chandler Carruth63559d72015-09-13 06:47:20 +0000285public:
286 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000287
Chandler Carruth63559d72015-09-13 06:47:20 +0000288 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000289
Chandler Carruth63559d72015-09-13 06:47:20 +0000290 iterator begin() { return SyntheticRoot.Uses.begin(); }
291 iterator end() { return SyntheticRoot.Uses.end(); }
292 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000293
Chandler Carruth63559d72015-09-13 06:47:20 +0000294 ArgumentGraphNode *operator[](Argument *A) {
295 ArgumentGraphNode &Node = ArgumentMap[A];
296 Node.Definition = A;
297 SyntheticRoot.Uses.push_back(&Node);
298 return &Node;
299 }
300};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000301
Chandler Carrutha632fb92015-09-13 06:57:25 +0000302/// This tracker checks whether callees are in the SCC, and if so it does not
303/// consider that a capture, instead adding it to the "Uses" list and
304/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000305struct ArgumentUsesTracker : public CaptureTracker {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000306 ArgumentUsesTracker(const SCCNodeSet &SCCNodes)
Nick Lewycky4c378a42011-12-28 23:24:21 +0000307 : Captured(false), SCCNodes(SCCNodes) {}
308
Chandler Carruth63559d72015-09-13 06:47:20 +0000309 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000310
Chandler Carruth63559d72015-09-13 06:47:20 +0000311 bool captured(const Use *U) override {
312 CallSite CS(U->getUser());
313 if (!CS.getInstruction()) {
314 Captured = true;
315 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000316 }
317
Chandler Carruth63559d72015-09-13 06:47:20 +0000318 Function *F = CS.getCalledFunction();
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000319 if (!F || F->isDeclaration() || F->mayBeOverridden() ||
320 !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000321 Captured = true;
322 return true;
323 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000324
Sanjoy Das98bfe262015-11-05 03:04:40 +0000325 // Note: the callee and the two successor blocks *follow* the argument
326 // operands. This means there is no need to adjust UseIndex to account for
327 // these.
328
329 unsigned UseIndex =
330 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
331
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000332 assert(UseIndex < CS.data_operands_size() &&
333 "Indirect function calls should have been filtered above!");
334
335 if (UseIndex >= CS.getNumArgOperands()) {
336 // Data operand, but not a argument operand -- must be a bundle operand
337 assert(CS.hasOperandBundles() && "Must be!");
338
339 // CaptureTracking told us that we're being captured by an operand bundle
340 // use. In this case it does not matter if the callee is within our SCC
341 // or not -- we've been captured in some unknown way, and we have to be
342 // conservative.
343 Captured = true;
344 return true;
345 }
346
Sanjoy Das98bfe262015-11-05 03:04:40 +0000347 if (UseIndex >= F->arg_size()) {
348 assert(F->isVarArg() && "More params than args in non-varargs call");
349 Captured = true;
350 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000351 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000352
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000353 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000354 return false;
355 }
356
357 bool Captured; // True only if certainly captured (used outside our SCC).
358 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
359
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000360 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000361};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000362}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000363
364namespace llvm {
Chandler Carruth63559d72015-09-13 06:47:20 +0000365template <> struct GraphTraits<ArgumentGraphNode *> {
366 typedef ArgumentGraphNode NodeType;
367 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000368
Chandler Carruth63559d72015-09-13 06:47:20 +0000369 static inline NodeType *getEntryNode(NodeType *A) { return A; }
370 static inline ChildIteratorType child_begin(NodeType *N) {
371 return N->Uses.begin();
372 }
373 static inline ChildIteratorType child_end(NodeType *N) {
374 return N->Uses.end();
375 }
376};
377template <>
378struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
379 static NodeType *getEntryNode(ArgumentGraph *AG) {
380 return AG->getEntryNode();
381 }
382 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
383 return AG->begin();
384 }
385 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
386};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000387}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000388
Chandler Carrutha632fb92015-09-13 06:57:25 +0000389/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000390static Attribute::AttrKind
391determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000392 const SmallPtrSet<Argument *, 8> &SCCNodes) {
393
394 SmallVector<Use *, 32> Worklist;
395 SmallSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000396
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000397 // inalloca arguments are always clobbered by the call.
398 if (A->hasInAllocaAttr())
399 return Attribute::None;
400
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000401 bool IsRead = false;
402 // We don't need to track IsWritten. If A is written to, return immediately.
403
Chandler Carruthcdf47882014-03-09 03:16:01 +0000404 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000405 Visited.insert(&U);
406 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000407 }
408
409 while (!Worklist.empty()) {
410 Use *U = Worklist.pop_back_val();
411 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000412
413 switch (I->getOpcode()) {
414 case Instruction::BitCast:
415 case Instruction::GetElementPtr:
416 case Instruction::PHI:
417 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000418 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000419 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000420 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000421 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000422 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000423 break;
424
425 case Instruction::Call:
426 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000427 bool Captures = true;
428
429 if (I->getType()->isVoidTy())
430 Captures = false;
431
432 auto AddUsersToWorklistIfCapturing = [&] {
433 if (Captures)
434 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000435 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000436 Worklist.push_back(&UU);
437 };
438
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000439 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000440 if (CS.doesNotAccessMemory()) {
441 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000442 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000443 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000444
445 Function *F = CS.getCalledFunction();
446 if (!F) {
447 if (CS.onlyReadsMemory()) {
448 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000449 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000450 continue;
451 }
452 return Attribute::None;
453 }
454
Sanjoy Das436e2392015-11-07 01:55:53 +0000455 // Note: the callee and the two successor blocks *follow* the argument
456 // operands. This means there is no need to adjust UseIndex to account
457 // for these.
458
459 unsigned UseIndex = std::distance(CS.arg_begin(), U);
460
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000461 // U cannot be the callee operand use: since we're exploring the
462 // transitive uses of an Argument, having such a use be a callee would
463 // imply the CallSite is an indirect call or invoke; and we'd take the
464 // early exit above.
465 assert(UseIndex < CS.data_operands_size() &&
466 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000467
468 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
469
470 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000471 assert(F->isVarArg() && "More params than args in non-varargs call");
472 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000473 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000474
Tilmann Scheller925b1932015-11-20 19:17:10 +0000475 Captures &= !CS.doesNotCapture(UseIndex);
476
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000477 // Since the optimizer (by design) cannot see the data flow corresponding
478 // to a operand bundle use, these cannot participate in the optimistic SCC
479 // analysis. Instead, we model the operand bundle uses as arguments in
480 // call to a function external to the SCC.
Sanjoy Das76dd2432015-11-07 02:26:53 +0000481 if (!SCCNodes.count(&*std::next(F->arg_begin(), UseIndex)) ||
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000482 IsOperandBundleUse) {
483
484 // The accessors used on CallSite here do the right thing for calls and
485 // invokes with operand bundles.
486
Sanjoy Das436e2392015-11-07 01:55:53 +0000487 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
488 return Attribute::None;
489 if (!CS.doesNotAccessMemory(UseIndex))
490 IsRead = true;
491 }
492
Nick Lewycky59633cb2014-05-30 02:31:27 +0000493 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000494 break;
495 }
496
497 case Instruction::Load:
498 IsRead = true;
499 break;
500
501 case Instruction::ICmp:
502 case Instruction::Ret:
503 break;
504
505 default:
506 return Attribute::None;
507 }
508 }
509
510 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
511}
512
Chandler Carrutha632fb92015-09-13 06:57:25 +0000513/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000514static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000515 bool Changed = false;
516
Nick Lewycky4c378a42011-12-28 23:24:21 +0000517 ArgumentGraph AG;
518
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000519 AttrBuilder B;
520 B.addAttribute(Attribute::NoCapture);
521
Duncan Sands44c8cd92008-12-31 16:14:43 +0000522 // Check each function in turn, determining which pointer arguments are not
523 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000524 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000525 // Definitions with weak linkage may be overridden at linktime with
Nick Lewycky4c378a42011-12-28 23:24:21 +0000526 // something that captures pointers, so treat them like declarations.
Duncan Sands44c8cd92008-12-31 16:14:43 +0000527 if (F->isDeclaration() || F->mayBeOverridden())
528 continue;
529
Nick Lewycky4c378a42011-12-28 23:24:21 +0000530 // Functions that are readonly (or readnone) and nounwind and don't return
531 // a value can't capture arguments. Don't analyze them.
532 if (F->onlyReadsMemory() && F->doesNotThrow() &&
533 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000534 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
535 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000536 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
537 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
538 ++NumNoCapture;
539 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000540 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000541 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000542 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000543 }
544
Chandler Carruth63559d72015-09-13 06:47:20 +0000545 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
546 ++A) {
547 if (!A->getType()->isPointerTy())
548 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000549 bool HasNonLocalUses = false;
550 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000551 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000552 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000553 if (!Tracker.Captured) {
554 if (Tracker.Uses.empty()) {
555 // If it's trivially not captured, mark it nocapture now.
Chandler Carruth63559d72015-09-13 06:47:20 +0000556 A->addAttr(
557 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000558 ++NumNoCapture;
559 Changed = true;
560 } else {
561 // If it's not trivially captured and not trivially not captured,
562 // then it must be calling into another function in our SCC. Save
563 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000564 ArgumentGraphNode *Node = AG[&*A];
Chandler Carruth63559d72015-09-13 06:47:20 +0000565 for (SmallVectorImpl<Argument *>::iterator
566 UI = Tracker.Uses.begin(),
567 UE = Tracker.Uses.end();
568 UI != UE; ++UI) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000569 Node->Uses.push_back(AG[*UI]);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000570 if (*UI != A)
571 HasNonLocalUses = true;
572 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000573 }
574 }
575 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
576 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000577 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
578 // Can we determine that it's readonly/readnone without doing an SCC?
579 // Note that we don't allow any calls at all here, or else our result
580 // will be dependent on the iteration order through the functions in the
581 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000582 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000583 Self.insert(&*A);
584 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000585 if (R != Attribute::None) {
586 AttrBuilder B;
587 B.addAttribute(R);
588 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
589 Changed = true;
590 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
591 }
592 }
593 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000594 }
595
596 // The graph we've collected is partial because we stopped scanning for
597 // argument uses once we solved the argument trivially. These partial nodes
598 // show up as ArgumentGraphNode objects with an empty Uses list, and for
599 // these nodes the final decision about whether they capture has already been
600 // made. If the definition doesn't have a 'nocapture' attribute by now, it
601 // captures.
602
Chandler Carruth63559d72015-09-13 06:47:20 +0000603 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000604 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000605 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000606 if (!ArgumentSCC[0]->Definition)
607 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000608
609 // eg. "void f(int* x) { if (...) f(x); }"
610 if (ArgumentSCC[0]->Uses.size() == 1 &&
611 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000612 Argument *A = ArgumentSCC[0]->Definition;
613 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky7e820552009-01-02 03:46:56 +0000614 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000615 Changed = true;
616 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000617 continue;
618 }
619
620 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000621 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
622 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000623 ArgumentGraphNode *Node = *I;
624 if (Node->Uses.empty()) {
625 if (!Node->Definition->hasNoCaptureAttr())
626 SCCCaptured = true;
627 }
628 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000629 if (SCCCaptured)
630 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000631
Chandler Carruth63559d72015-09-13 06:47:20 +0000632 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000633 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
634 // quickly looking up whether a given Argument is in this ArgumentSCC.
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000635 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000636 ArgumentSCCNodes.insert((*I)->Definition);
637 }
638
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000639 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
640 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000641 ArgumentGraphNode *N = *I;
Chandler Carruth63559d72015-09-13 06:47:20 +0000642 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
643 UE = N->Uses.end();
644 UI != UE; ++UI) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000645 Argument *A = (*UI)->Definition;
646 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
647 continue;
648 SCCCaptured = true;
649 break;
650 }
651 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000652 if (SCCCaptured)
653 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000654
Nick Lewyckyf740db32012-01-05 22:21:45 +0000655 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000656 Argument *A = ArgumentSCC[i]->Definition;
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000657 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky4c378a42011-12-28 23:24:21 +0000658 ++NumNoCapture;
659 Changed = true;
660 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000661
662 // We also want to compute readonly/readnone. With a small number of false
663 // negatives, we can assume that any pointer which is captured isn't going
664 // to be provably readonly or readnone, since by definition we can't
665 // analyze all uses of a captured pointer.
666 //
667 // The false negatives happen when the pointer is captured by a function
668 // that promises readonly/readnone behaviour on the pointer, then the
669 // pointer's lifetime ends before anything that writes to arbitrary memory.
670 // Also, a readonly/readnone pointer may be returned, but returning a
671 // pointer is capturing it.
672
673 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
674 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
675 Argument *A = ArgumentSCC[i]->Definition;
676 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
677 if (K == Attribute::ReadNone)
678 continue;
679 if (K == Attribute::ReadOnly) {
680 ReadAttr = Attribute::ReadOnly;
681 continue;
682 }
683 ReadAttr = K;
684 break;
685 }
686
687 if (ReadAttr != Attribute::None) {
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000688 AttrBuilder B, R;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000689 B.addAttribute(ReadAttr);
Chandler Carruth63559d72015-09-13 06:47:20 +0000690 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000691 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
692 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000693 // Clear out existing readonly/readnone attributes
694 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000695 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
696 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
697 Changed = true;
698 }
699 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000700 }
701
702 return Changed;
703}
704
Chandler Carrutha632fb92015-09-13 06:57:25 +0000705/// Tests whether a function is "malloc-like".
706///
707/// A function is "malloc-like" if it returns either null or a pointer that
708/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000709static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000710 SmallSetVector<Value *, 8> FlowsToReturn;
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000711 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
712 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
713 FlowsToReturn.insert(Ret->getReturnValue());
714
715 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000716 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000717
718 if (Constant *C = dyn_cast<Constant>(RetVal)) {
719 if (!C->isNullValue() && !isa<UndefValue>(C))
720 return false;
721
722 continue;
723 }
724
725 if (isa<Argument>(RetVal))
726 return false;
727
728 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
729 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000730 // Extend the analysis by looking upwards.
731 case Instruction::BitCast:
732 case Instruction::GetElementPtr:
733 case Instruction::AddrSpaceCast:
734 FlowsToReturn.insert(RVI->getOperand(0));
735 continue;
736 case Instruction::Select: {
737 SelectInst *SI = cast<SelectInst>(RVI);
738 FlowsToReturn.insert(SI->getTrueValue());
739 FlowsToReturn.insert(SI->getFalseValue());
740 continue;
741 }
742 case Instruction::PHI: {
743 PHINode *PN = cast<PHINode>(RVI);
744 for (Value *IncValue : PN->incoming_values())
745 FlowsToReturn.insert(IncValue);
746 continue;
747 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000748
Chandler Carruth63559d72015-09-13 06:47:20 +0000749 // Check whether the pointer came from an allocation.
750 case Instruction::Alloca:
751 break;
752 case Instruction::Call:
753 case Instruction::Invoke: {
754 CallSite CS(RVI);
755 if (CS.paramHasAttr(0, Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000756 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000757 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
758 break;
759 } // fall-through
760 default:
761 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000762 }
763
Dan Gohman94e61762009-11-19 21:57:48 +0000764 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000765 return false;
766 }
767
768 return true;
769}
770
Chandler Carrutha632fb92015-09-13 06:57:25 +0000771/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000772static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000773 // Check each function in turn, determining which functions return noalias
774 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000775 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000776 // Already noalias.
777 if (F->doesNotAlias(0))
778 continue;
779
780 // Definitions with weak linkage may be overridden at linktime, so
781 // treat them like declarations.
782 if (F->isDeclaration() || F->mayBeOverridden())
783 return false;
784
Chandler Carruth63559d72015-09-13 06:47:20 +0000785 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000786 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000787 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000788 continue;
789
Chandler Carruth3824f852015-09-13 08:23:27 +0000790 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000791 return false;
792 }
793
794 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000795 for (Function *F : SCCNodes) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000796 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000797 continue;
798
799 F->setDoesNotAlias(0);
800 ++NumNoAlias;
801 MadeChange = true;
802 }
803
804 return MadeChange;
805}
806
Chandler Carrutha632fb92015-09-13 06:57:25 +0000807/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000808///
809/// Requires that the function returns a pointer.
810///
811/// Returns true if it believes the function will not return a null, and sets
812/// \p Speculative based on whether the returned conclusion is a speculative
813/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000814static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Chandler Carruth8874b782015-09-13 08:17:14 +0000815 const TargetLibraryInfo &TLI, bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000816 assert(F->getReturnType()->isPointerTy() &&
817 "nonnull only meaningful on pointer types");
818 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000819
Philip Reamesa88caea2015-08-31 19:44:38 +0000820 SmallSetVector<Value *, 8> FlowsToReturn;
821 for (BasicBlock &BB : *F)
822 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
823 FlowsToReturn.insert(Ret->getReturnValue());
824
825 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
826 Value *RetVal = FlowsToReturn[i];
827
828 // If this value is locally known to be non-null, we're good
Chandler Carruth8874b782015-09-13 08:17:14 +0000829 if (isKnownNonNull(RetVal, &TLI))
Philip Reamesa88caea2015-08-31 19:44:38 +0000830 continue;
831
832 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000833 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000834 Instruction *RVI = dyn_cast<Instruction>(RetVal);
835 if (!RVI)
836 return false;
837 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000838 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000839 case Instruction::BitCast:
840 case Instruction::GetElementPtr:
841 case Instruction::AddrSpaceCast:
842 FlowsToReturn.insert(RVI->getOperand(0));
843 continue;
844 case Instruction::Select: {
845 SelectInst *SI = cast<SelectInst>(RVI);
846 FlowsToReturn.insert(SI->getTrueValue());
847 FlowsToReturn.insert(SI->getFalseValue());
848 continue;
849 }
850 case Instruction::PHI: {
851 PHINode *PN = cast<PHINode>(RVI);
852 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
853 FlowsToReturn.insert(PN->getIncomingValue(i));
854 continue;
855 }
856 case Instruction::Call:
857 case Instruction::Invoke: {
858 CallSite CS(RVI);
859 Function *Callee = CS.getCalledFunction();
860 // A call to a node within the SCC is assumed to return null until
861 // proven otherwise
862 if (Callee && SCCNodes.count(Callee)) {
863 Speculative = true;
864 continue;
865 }
866 return false;
867 }
868 default:
Chandler Carruth63559d72015-09-13 06:47:20 +0000869 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +0000870 };
871 llvm_unreachable("should have either continued or returned");
872 }
873
874 return true;
875}
876
Chandler Carrutha632fb92015-09-13 06:57:25 +0000877/// Deduce nonnull attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000878static bool addNonNullAttrs(const SCCNodeSet &SCCNodes,
879 const TargetLibraryInfo &TLI) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000880 // Speculative that all functions in the SCC return only nonnull
881 // pointers. We may refute this as we analyze functions.
882 bool SCCReturnsNonNull = true;
883
884 bool MadeChange = false;
885
886 // Check each function in turn, determining which functions return nonnull
887 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000888 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000889 // Already nonnull.
890 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
891 Attribute::NonNull))
892 continue;
893
894 // Definitions with weak linkage may be overridden at linktime, so
895 // treat them like declarations.
896 if (F->isDeclaration() || F->mayBeOverridden())
897 return false;
898
Chandler Carruth63559d72015-09-13 06:47:20 +0000899 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +0000900 // pointer types.
901 if (!F->getReturnType()->isPointerTy())
902 continue;
903
904 bool Speculative = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000905 if (isReturnNonNull(F, SCCNodes, TLI, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000906 if (!Speculative) {
907 // Mark the function eagerly since we may discover a function
908 // which prevents us from speculating about the entire SCC
909 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
910 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
911 ++NumNonNullReturn;
912 MadeChange = true;
913 }
914 continue;
915 }
916 // At least one function returns something which could be null, can't
917 // speculate any more.
918 SCCReturnsNonNull = false;
919 }
920
921 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000922 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000923 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
924 Attribute::NonNull) ||
925 !F->getReturnType()->isPointerTy())
926 continue;
927
928 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
929 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
930 ++NumNonNullReturn;
931 MadeChange = true;
932 }
933 }
934
935 return MadeChange;
936}
937
Justin Lebar260854b2016-02-09 23:03:22 +0000938/// Removes convergent attributes where we can prove that none of the SCC's
939/// callees are themselves convergent. Returns true if successful at removing
940/// the attribute.
Chandler Carruth3937bc72016-02-12 09:47:49 +0000941static bool removeConvergentAttrs(const SCCNodeSet &SCCNodes) {
Justin Lebar260854b2016-02-09 23:03:22 +0000942 // Determines whether a function can be made non-convergent, ignoring all
943 // other functions in SCC. (A function can *actually* be made non-convergent
944 // only if all functions in its SCC can be made convergent.)
Chandler Carruth3937bc72016-02-12 09:47:49 +0000945 auto CanRemoveConvergent = [&](Function *F) {
Chandler Carruthbbbbec02016-02-12 03:07:50 +0000946 if (!F->isConvergent())
947 return true;
Justin Lebar260854b2016-02-09 23:03:22 +0000948
949 // Can't remove convergent from declarations.
Chandler Carruthbbbbec02016-02-12 03:07:50 +0000950 if (F->isDeclaration())
951 return false;
Justin Lebar260854b2016-02-09 23:03:22 +0000952
Chandler Carruth057df3d2016-02-12 09:23:53 +0000953 for (Instruction &I : instructions(*F))
954 if (auto CS = CallSite(&I)) {
955 // Can't remove convergent if any of F's callees -- ignoring functions
956 // in the SCC itself -- are convergent. This needs to consider both
957 // function calls and intrinsic calls. We also assume indirect calls
958 // might call a convergent function.
959 // FIXME: We should revisit this when we put convergent onto calls
960 // instead of functions so that indirect calls which should be
961 // convergent are required to be marked as such.
962 Function *Callee = CS.getCalledFunction();
963 if (!Callee || (SCCNodes.count(Callee) == 0 && Callee->isConvergent()))
964 return false;
965 }
Justin Lebar260854b2016-02-09 23:03:22 +0000966
Chandler Carruth057df3d2016-02-12 09:23:53 +0000967 return true;
Justin Lebar260854b2016-02-09 23:03:22 +0000968 };
969
Chandler Carruthbbbbec02016-02-12 03:07:50 +0000970 // We can remove the convergent attr from functions in the SCC if they all
971 // can be made non-convergent (because they call only non-convergent
972 // functions, other than each other).
Chandler Carruth3937bc72016-02-12 09:47:49 +0000973 if (!llvm::all_of(SCCNodes, CanRemoveConvergent))
Chandler Carruthbbbbec02016-02-12 03:07:50 +0000974 return false;
Justin Lebar260854b2016-02-09 23:03:22 +0000975
Chandler Carruth3937bc72016-02-12 09:47:49 +0000976 // If we got here, all of the SCC's callees are non-convergent. Therefore all
Justin Lebar260854b2016-02-09 23:03:22 +0000977 // of the SCC's functions can be marked as non-convergent.
Chandler Carruth3937bc72016-02-12 09:47:49 +0000978 for (Function *F : SCCNodes) {
979 if (F->isConvergent())
980 DEBUG(dbgs() << "Removing convergent attr from " << F->getName() << "\n");
981 F->setNotConvergent();
982 }
Justin Lebar260854b2016-02-09 23:03:22 +0000983 return true;
984}
985
James Molloy7e9bdd52015-11-12 10:55:20 +0000986static bool setDoesNotRecurse(Function &F) {
987 if (F.doesNotRecurse())
988 return false;
989 F.setDoesNotRecurse();
990 ++NumNoRecurse;
991 return true;
992}
993
Chandler Carruth1926b702016-01-08 10:55:52 +0000994static bool addNoRecurseAttrs(const CallGraphSCC &SCC) {
James Molloy7e9bdd52015-11-12 10:55:20 +0000995 // Try and identify functions that do not recurse.
996
997 // If the SCC contains multiple nodes we know for sure there is recursion.
998 if (!SCC.isSingular())
999 return false;
1000
1001 const CallGraphNode *CGN = *SCC.begin();
1002 Function *F = CGN->getFunction();
1003 if (!F || F->isDeclaration() || F->doesNotRecurse())
1004 return false;
1005
1006 // If all of the calls in F are identifiable and are to norecurse functions, F
1007 // is norecurse. This check also detects self-recursion as F is not currently
1008 // marked norecurse, so any called from F to F will not be marked norecurse.
1009 if (std::all_of(CGN->begin(), CGN->end(),
1010 [](const CallGraphNode::CallRecord &CR) {
1011 Function *F = CR.second->getFunction();
1012 return F && F->doesNotRecurse();
1013 }))
1014 // Function calls a potentially recursive function.
1015 return setDoesNotRecurse(*F);
1016
Chandler Carruth1926b702016-01-08 10:55:52 +00001017 // Nothing else we can deduce usefully during the postorder traversal.
James Molloy7e9bdd52015-11-12 10:55:20 +00001018 return false;
1019}
1020
Chandler Carruth1926b702016-01-08 10:55:52 +00001021bool PostOrderFunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001022 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthcada2d82015-10-31 00:28:37 +00001023 bool Changed = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001024
Chandler Carrutha8125352015-10-30 16:48:08 +00001025 // We compute dedicated AA results for each function in the SCC as needed. We
1026 // use a lambda referencing external objects so that they live long enough to
1027 // be queried, but we re-use them each time.
1028 Optional<BasicAAResult> BAR;
1029 Optional<AAResults> AAR;
1030 auto AARGetter = [&](Function &F) -> AAResults & {
1031 BAR.emplace(createLegacyPMBasicAAResult(*this, F));
1032 AAR.emplace(createLegacyPMAAResults(*this, F, *BAR));
1033 return *AAR;
1034 };
1035
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001036 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1037 // whether a given CallGraphNode is in this SCC. Also track whether there are
1038 // any external or opt-none nodes that will prevent us from optimizing any
1039 // part of the SCC.
1040 SCCNodeSet SCCNodes;
1041 bool ExternalNode = false;
1042 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1043 Function *F = (*I)->getFunction();
1044 if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
1045 // External node or function we're trying not to optimize - we both avoid
1046 // transform them and avoid leveraging information they provide.
1047 ExternalNode = true;
1048 continue;
1049 }
1050
1051 SCCNodes.insert(F);
1052 }
1053
Chandler Carrutha8125352015-10-30 16:48:08 +00001054 Changed |= addReadAttrs(SCCNodes, AARGetter);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001055 Changed |= addArgumentAttrs(SCCNodes);
1056
Chandler Carruth3a040e62015-12-27 08:41:34 +00001057 // If we have no external nodes participating in the SCC, we can deduce some
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001058 // more precise attributes as well.
1059 if (!ExternalNode) {
1060 Changed |= addNoAliasAttrs(SCCNodes);
1061 Changed |= addNonNullAttrs(SCCNodes, *TLI);
Chandler Carruth3937bc72016-02-12 09:47:49 +00001062 Changed |= removeConvergentAttrs(SCCNodes);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001063 }
Chandler Carruth1926b702016-01-08 10:55:52 +00001064
1065 Changed |= addNoRecurseAttrs(SCC);
James Molloy7e9bdd52015-11-12 10:55:20 +00001066 return Changed;
1067}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001068
Chandler Carruth1926b702016-01-08 10:55:52 +00001069namespace {
1070/// A pass to do RPO deduction and propagation of function attributes.
1071///
1072/// This pass provides a general RPO or "top down" propagation of
1073/// function attributes. For a few (rare) cases, we can deduce significantly
1074/// more about function attributes by working in RPO, so this pass
1075/// provides the compliment to the post-order pass above where the majority of
1076/// deduction is performed.
1077// FIXME: Currently there is no RPO CGSCC pass structure to slide into and so
1078// this is a boring module pass, but eventually it should be an RPO CGSCC pass
1079// when such infrastructure is available.
1080struct ReversePostOrderFunctionAttrs : public ModulePass {
1081 static char ID; // Pass identification, replacement for typeid
1082 ReversePostOrderFunctionAttrs() : ModulePass(ID) {
1083 initializeReversePostOrderFunctionAttrsPass(*PassRegistry::getPassRegistry());
1084 }
1085
1086 bool runOnModule(Module &M) override;
1087
1088 void getAnalysisUsage(AnalysisUsage &AU) const override {
1089 AU.setPreservesCFG();
1090 AU.addRequired<CallGraphWrapperPass>();
1091 }
1092};
1093}
1094
1095char ReversePostOrderFunctionAttrs::ID = 0;
1096INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrs, "rpo-functionattrs",
1097 "Deduce function attributes in RPO", false, false)
1098INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1099INITIALIZE_PASS_END(ReversePostOrderFunctionAttrs, "rpo-functionattrs",
1100 "Deduce function attributes in RPO", false, false)
1101
1102Pass *llvm::createReversePostOrderFunctionAttrsPass() {
1103 return new ReversePostOrderFunctionAttrs();
1104}
1105
1106static bool addNoRecurseAttrsTopDown(Function &F) {
1107 // We check the preconditions for the function prior to calling this to avoid
1108 // the cost of building up a reversible post-order list. We assert them here
1109 // to make sure none of the invariants this relies on were violated.
1110 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1111 assert(!F.doesNotRecurse() &&
1112 "This function has already been deduced as norecurs!");
1113 assert(F.hasInternalLinkage() &&
1114 "Can only do top-down deduction for internal linkage functions!");
1115
1116 // If F is internal and all of its uses are calls from a non-recursive
1117 // functions, then none of its calls could in fact recurse without going
1118 // through a function marked norecurse, and so we can mark this function too
1119 // as norecurse. Note that the uses must actually be calls -- otherwise
1120 // a pointer to this function could be returned from a norecurse function but
1121 // this function could be recursively (indirectly) called. Note that this
1122 // also detects if F is directly recursive as F is not yet marked as
1123 // a norecurse function.
1124 for (auto *U : F.users()) {
1125 auto *I = dyn_cast<Instruction>(U);
1126 if (!I)
1127 return false;
1128 CallSite CS(I);
1129 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1130 return false;
1131 }
1132 return setDoesNotRecurse(F);
1133}
1134
1135bool ReversePostOrderFunctionAttrs::runOnModule(Module &M) {
1136 // We only have a post-order SCC traversal (because SCCs are inherently
1137 // discovered in post-order), so we accumulate them in a vector and then walk
1138 // it in reverse. This is simpler than using the RPO iterator infrastructure
1139 // because we need to combine SCC detection and the PO walk of the call
1140 // graph. We can also cheat egregiously because we're primarily interested in
1141 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1142 // with multiple functions in them will clearly be recursive.
1143 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1144 SmallVector<Function *, 16> Worklist;
1145 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1146 if (I->size() != 1)
1147 continue;
1148
1149 Function *F = I->front()->getFunction();
1150 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1151 F->hasInternalLinkage())
1152 Worklist.push_back(F);
1153 }
1154
James Molloy7e9bdd52015-11-12 10:55:20 +00001155 bool Changed = false;
Chandler Carruth1926b702016-01-08 10:55:52 +00001156 for (auto *F : reverse(Worklist))
1157 Changed |= addNoRecurseAttrsTopDown(*F);
1158
Duncan Sands44c8cd92008-12-31 16:14:43 +00001159 return Changed;
1160}