blob: 59b23699658fb88cf8c3a5a49195401e119704c2 [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
Chandler Carruth9c4ed172016-02-18 11:03:11 +000016#include "llvm/Transforms/IPO/FunctionAttrs.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000017#include "llvm/Transforms/IPO.h"
Nick Lewycky4c378a42011-12-28 23:24:21 +000018#include "llvm/ADT/SCCIterator.h"
Benjamin Kramer15591272012-10-31 13:45:49 +000019#include "llvm/ADT/SetVector.h"
Duncan Sandsb193a372009-01-02 11:54:37 +000020#include "llvm/ADT/SmallSet.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000021#include "llvm/ADT/Statistic.h"
James Molloy0ecdbe72015-11-19 08:49:57 +000022#include "llvm/ADT/StringSwitch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000024#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000025#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/CallGraph.h"
Chandler Carruth839a98e2013-01-07 15:26:48 +000027#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000029#include "llvm/Analysis/TargetLibraryInfo.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000030#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000032#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000035#include "llvm/Support/Debug.h"
Hans Wennborg043bf5b2015-08-31 21:19:18 +000036#include "llvm/Support/raw_ostream.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000037#include "llvm/Analysis/TargetLibraryInfo.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000038using namespace llvm;
39
Chandler Carruth964daaa2014-04-22 02:55:47 +000040#define DEBUG_TYPE "functionattrs"
41
Duncan Sands44c8cd92008-12-31 16:14:43 +000042STATISTIC(NumReadNone, "Number of functions marked readnone");
43STATISTIC(NumReadOnly, "Number of functions marked readonly");
44STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
David Majnemer5246e0b2016-07-19 18:50:26 +000045STATISTIC(NumReturned, "Number of arguments marked returned");
Nick Lewyckyc2ec0722013-07-06 00:29:58 +000046STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
47STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
Nick Lewyckyfbed86a2009-03-08 06:20:47 +000048STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Philip Reamesa88caea2015-08-31 19:44:38 +000049STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
James Molloy7e9bdd52015-11-12 10:55:20 +000050STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
Duncan Sands44c8cd92008-12-31 16:14:43 +000051
Sanjay Patel4f742162017-02-13 23:10:51 +000052// FIXME: This is disabled by default to avoid exposing security vulnerabilities
53// in C/C++ code compiled by clang:
54// http://lists.llvm.org/pipermail/cfe-dev/2017-January/052066.html
55static cl::opt<bool> EnableNonnullArgPropagation(
56 "enable-nonnull-arg-prop", cl::Hidden,
57 cl::desc("Try to propagate nonnull argument attributes from callsites to "
58 "caller functions."));
59
Duncan Sands44c8cd92008-12-31 16:14:43 +000060namespace {
Chandler Carruthc518ebd2015-10-29 18:29:15 +000061typedef SmallSetVector<Function *, 8> SCCNodeSet;
62}
63
64namespace {
Chandler Carruth7542d372015-09-21 17:39:41 +000065/// The three kinds of memory access relevant to 'readonly' and
66/// 'readnone' attributes.
67enum MemoryAccessKind {
68 MAK_ReadNone = 0,
69 MAK_ReadOnly = 1,
70 MAK_MayWrite = 2
71};
72}
73
Chandler Carruthc518ebd2015-10-29 18:29:15 +000074static MemoryAccessKind checkFunctionMemoryAccess(Function &F, AAResults &AAR,
75 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +000076 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
77 if (MRB == FMRB_DoesNotAccessMemory)
78 // Already perfect!
79 return MAK_ReadNone;
80
Sanjoy Das5ce32722016-04-08 00:48:30 +000081 // Non-exact function definitions may not be selected at link time, and an
82 // alternative version that writes to memory may be selected. See the comment
83 // on GlobalValue::isDefinitionExact for more details.
84 if (!F.hasExactDefinition()) {
Chandler Carruth7542d372015-09-21 17:39:41 +000085 if (AliasAnalysis::onlyReadsMemory(MRB))
86 return MAK_ReadOnly;
87
88 // Conservatively assume it writes to memory.
89 return MAK_MayWrite;
90 }
91
92 // Scan the function body for instructions that may read or write memory.
93 bool ReadsMemory = false;
94 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
95 Instruction *I = &*II;
96
97 // Some instructions can be ignored even if they read or write memory.
98 // Detect these now, skipping to the next instruction if one is found.
99 CallSite CS(cast<Value>(I));
100 if (CS) {
Sanjoy Das10c8a042016-02-09 18:40:40 +0000101 // Ignore calls to functions in the same SCC, as long as the call sites
102 // don't have operand bundles. Calls with operand bundles are allowed to
103 // have memory effects not described by the memory effects of the call
104 // target.
105 if (!CS.hasOperandBundles() && CS.getCalledFunction() &&
106 SCCNodes.count(CS.getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +0000107 continue;
108 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
Chandler Carruth7542d372015-09-21 17:39:41 +0000109
Chandler Carruth69798fb2015-10-27 01:41:43 +0000110 // If the call doesn't access memory, we're done.
111 if (!(MRB & MRI_ModRef))
112 continue;
113
114 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
115 // The call could access any memory. If that includes writes, give up.
116 if (MRB & MRI_Mod)
117 return MAK_MayWrite;
118 // If it reads, note it.
119 if (MRB & MRI_Ref)
120 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000121 continue;
122 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000123
124 // Check whether all pointer arguments point to local memory, and
125 // ignore calls that only access local memory.
126 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
127 CI != CE; ++CI) {
128 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000129 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000130 continue;
131
132 AAMDNodes AAInfo;
133 I->getAAMetadata(AAInfo);
134 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
135
136 // Skip accesses to local or constant memory as they don't impact the
137 // externally visible mod/ref behavior.
138 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
139 continue;
140
141 if (MRB & MRI_Mod)
142 // Writes non-local memory. Give up.
143 return MAK_MayWrite;
144 if (MRB & MRI_Ref)
145 // Ok, it reads non-local memory.
146 ReadsMemory = true;
147 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000148 continue;
149 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
150 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
151 if (!LI->isVolatile()) {
152 MemoryLocation Loc = MemoryLocation::get(LI);
153 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
154 continue;
155 }
156 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
157 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
158 if (!SI->isVolatile()) {
159 MemoryLocation Loc = MemoryLocation::get(SI);
160 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
161 continue;
162 }
163 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
164 // Ignore vaargs on local memory.
165 MemoryLocation Loc = MemoryLocation::get(VI);
166 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
167 continue;
168 }
169
170 // Any remaining instructions need to be taken seriously! Check if they
171 // read or write memory.
172 if (I->mayWriteToMemory())
173 // Writes memory. Just give up.
174 return MAK_MayWrite;
175
176 // If this instruction may read memory, remember that.
177 ReadsMemory |= I->mayReadFromMemory();
178 }
179
180 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
181}
182
Chandler Carrutha632fb92015-09-13 06:57:25 +0000183/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000184template <typename AARGetterT>
Peter Collingbournecea1e4e2017-02-09 23:11:52 +0000185static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000186 // Check if any of the functions in the SCC read or write memory. If they
187 // write memory then they can't be marked readnone or readonly.
188 bool ReadsMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000189 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000190 // Call the callable parameter to look up AA results for this function.
191 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000192
Chandler Carruth7542d372015-09-21 17:39:41 +0000193 switch (checkFunctionMemoryAccess(*F, AAR, SCCNodes)) {
194 case MAK_MayWrite:
195 return false;
196 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000197 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000198 break;
199 case MAK_ReadNone:
200 // Nothing to do!
201 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000202 }
203 }
204
205 // Success! Functions in this SCC do not access memory, or only read memory.
206 // Give them the appropriate attribute.
207 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000208 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000209 if (F->doesNotAccessMemory())
210 // Already perfect!
211 continue;
212
213 if (F->onlyReadsMemory() && ReadsMemory)
214 // No change.
215 continue;
216
217 MadeChange = true;
218
219 // Clear out any existing attributes.
Bill Wendling50d27842012-10-15 20:35:56 +0000220 AttrBuilder B;
Chandler Carruth63559d72015-09-13 06:47:20 +0000221 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
222 F->removeAttributes(
223 AttributeSet::FunctionIndex,
224 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
Duncan Sands44c8cd92008-12-31 16:14:43 +0000225
226 // Add in the new attribute.
Bill Wendlinge94d8432012-12-07 23:16:57 +0000227 F->addAttribute(AttributeSet::FunctionIndex,
Bill Wendlingc0e2a1f2013-01-23 00:20:53 +0000228 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000229
230 if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000231 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000232 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000233 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000234 }
235
236 return MadeChange;
237}
238
Nick Lewycky4c378a42011-12-28 23:24:21 +0000239namespace {
Chandler Carrutha632fb92015-09-13 06:57:25 +0000240/// For a given pointer Argument, this retains a list of Arguments of functions
241/// in the same SCC that the pointer data flows into. We use this to build an
242/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000243struct ArgumentGraphNode {
244 Argument *Definition;
245 SmallVector<ArgumentGraphNode *, 4> Uses;
246};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000247
Chandler Carruth63559d72015-09-13 06:47:20 +0000248class ArgumentGraph {
249 // We store pointers to ArgumentGraphNode objects, so it's important that
250 // that they not move around upon insert.
251 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000252
Chandler Carruth63559d72015-09-13 06:47:20 +0000253 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000254
Chandler Carruth63559d72015-09-13 06:47:20 +0000255 // There is no root node for the argument graph, in fact:
256 // void f(int *x, int *y) { if (...) f(x, y); }
257 // is an example where the graph is disconnected. The SCCIterator requires a
258 // single entry point, so we maintain a fake ("synthetic") root node that
259 // uses every node. Because the graph is directed and nothing points into
260 // the root, it will not participate in any SCCs (except for its own).
261 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000262
Chandler Carruth63559d72015-09-13 06:47:20 +0000263public:
264 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000265
Chandler Carruth63559d72015-09-13 06:47:20 +0000266 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000267
Chandler Carruth63559d72015-09-13 06:47:20 +0000268 iterator begin() { return SyntheticRoot.Uses.begin(); }
269 iterator end() { return SyntheticRoot.Uses.end(); }
270 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000271
Chandler Carruth63559d72015-09-13 06:47:20 +0000272 ArgumentGraphNode *operator[](Argument *A) {
273 ArgumentGraphNode &Node = ArgumentMap[A];
274 Node.Definition = A;
275 SyntheticRoot.Uses.push_back(&Node);
276 return &Node;
277 }
278};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000279
Chandler Carrutha632fb92015-09-13 06:57:25 +0000280/// This tracker checks whether callees are in the SCC, and if so it does not
281/// consider that a capture, instead adding it to the "Uses" list and
282/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000283struct ArgumentUsesTracker : public CaptureTracker {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000284 ArgumentUsesTracker(const SCCNodeSet &SCCNodes)
Nick Lewycky4c378a42011-12-28 23:24:21 +0000285 : Captured(false), SCCNodes(SCCNodes) {}
286
Chandler Carruth63559d72015-09-13 06:47:20 +0000287 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000288
Chandler Carruth63559d72015-09-13 06:47:20 +0000289 bool captured(const Use *U) override {
290 CallSite CS(U->getUser());
291 if (!CS.getInstruction()) {
292 Captured = true;
293 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000294 }
295
Chandler Carruth63559d72015-09-13 06:47:20 +0000296 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000297 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000298 Captured = true;
299 return true;
300 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000301
Sanjoy Das98bfe262015-11-05 03:04:40 +0000302 // Note: the callee and the two successor blocks *follow* the argument
303 // operands. This means there is no need to adjust UseIndex to account for
304 // these.
305
306 unsigned UseIndex =
307 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
308
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000309 assert(UseIndex < CS.data_operands_size() &&
310 "Indirect function calls should have been filtered above!");
311
312 if (UseIndex >= CS.getNumArgOperands()) {
313 // Data operand, but not a argument operand -- must be a bundle operand
314 assert(CS.hasOperandBundles() && "Must be!");
315
316 // CaptureTracking told us that we're being captured by an operand bundle
317 // use. In this case it does not matter if the callee is within our SCC
318 // or not -- we've been captured in some unknown way, and we have to be
319 // conservative.
320 Captured = true;
321 return true;
322 }
323
Sanjoy Das98bfe262015-11-05 03:04:40 +0000324 if (UseIndex >= F->arg_size()) {
325 assert(F->isVarArg() && "More params than args in non-varargs call");
326 Captured = true;
327 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000328 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000329
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000330 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000331 return false;
332 }
333
334 bool Captured; // True only if certainly captured (used outside our SCC).
335 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
336
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000337 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000338};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000339}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000340
341namespace llvm {
Chandler Carruth63559d72015-09-13 06:47:20 +0000342template <> struct GraphTraits<ArgumentGraphNode *> {
Tim Shenb44909e2016-08-01 22:32:20 +0000343 typedef ArgumentGraphNode *NodeRef;
Chandler Carruth63559d72015-09-13 06:47:20 +0000344 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000345
Tim Shen48f814e2016-08-31 16:48:13 +0000346 static NodeRef getEntryNode(NodeRef A) { return A; }
347 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
348 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000349};
350template <>
351struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
Tim Shenf2187ed2016-08-22 21:09:30 +0000352 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000353 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
354 return AG->begin();
355 }
356 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
357};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000358}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000359
Chandler Carrutha632fb92015-09-13 06:57:25 +0000360/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000361static Attribute::AttrKind
362determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000363 const SmallPtrSet<Argument *, 8> &SCCNodes) {
364
365 SmallVector<Use *, 32> Worklist;
366 SmallSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000367
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000368 // inalloca arguments are always clobbered by the call.
369 if (A->hasInAllocaAttr())
370 return Attribute::None;
371
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000372 bool IsRead = false;
373 // We don't need to track IsWritten. If A is written to, return immediately.
374
Chandler Carruthcdf47882014-03-09 03:16:01 +0000375 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000376 Visited.insert(&U);
377 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000378 }
379
380 while (!Worklist.empty()) {
381 Use *U = Worklist.pop_back_val();
382 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000383
384 switch (I->getOpcode()) {
385 case Instruction::BitCast:
386 case Instruction::GetElementPtr:
387 case Instruction::PHI:
388 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000389 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000390 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000391 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000392 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000393 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000394 break;
395
396 case Instruction::Call:
397 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000398 bool Captures = true;
399
400 if (I->getType()->isVoidTy())
401 Captures = false;
402
403 auto AddUsersToWorklistIfCapturing = [&] {
404 if (Captures)
405 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000406 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000407 Worklist.push_back(&UU);
408 };
409
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000410 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000411 if (CS.doesNotAccessMemory()) {
412 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000413 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000414 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000415
416 Function *F = CS.getCalledFunction();
417 if (!F) {
418 if (CS.onlyReadsMemory()) {
419 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000420 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000421 continue;
422 }
423 return Attribute::None;
424 }
425
Sanjoy Das436e2392015-11-07 01:55:53 +0000426 // Note: the callee and the two successor blocks *follow* the argument
427 // operands. This means there is no need to adjust UseIndex to account
428 // for these.
429
430 unsigned UseIndex = std::distance(CS.arg_begin(), U);
431
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000432 // U cannot be the callee operand use: since we're exploring the
433 // transitive uses of an Argument, having such a use be a callee would
434 // imply the CallSite is an indirect call or invoke; and we'd take the
435 // early exit above.
436 assert(UseIndex < CS.data_operands_size() &&
437 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000438
439 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
440
441 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000442 assert(F->isVarArg() && "More params than args in non-varargs call");
443 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000444 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000445
Tilmann Scheller925b1932015-11-20 19:17:10 +0000446 Captures &= !CS.doesNotCapture(UseIndex);
447
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000448 // Since the optimizer (by design) cannot see the data flow corresponding
449 // to a operand bundle use, these cannot participate in the optimistic SCC
450 // analysis. Instead, we model the operand bundle uses as arguments in
451 // call to a function external to the SCC.
Duncan P. N. Exon Smith9e3edad2016-08-17 01:23:58 +0000452 if (IsOperandBundleUse ||
453 !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000454
455 // The accessors used on CallSite here do the right thing for calls and
456 // invokes with operand bundles.
457
Sanjoy Das436e2392015-11-07 01:55:53 +0000458 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
459 return Attribute::None;
460 if (!CS.doesNotAccessMemory(UseIndex))
461 IsRead = true;
462 }
463
Nick Lewycky59633cb2014-05-30 02:31:27 +0000464 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000465 break;
466 }
467
468 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000469 // A volatile load has side effects beyond what readonly can be relied
470 // upon.
471 if (cast<LoadInst>(I)->isVolatile())
472 return Attribute::None;
473
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000474 IsRead = true;
475 break;
476
477 case Instruction::ICmp:
478 case Instruction::Ret:
479 break;
480
481 default:
482 return Attribute::None;
483 }
484 }
485
486 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
487}
488
David Majnemer5246e0b2016-07-19 18:50:26 +0000489/// Deduce returned attributes for the SCC.
490static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
491 bool Changed = false;
492
493 AttrBuilder B;
494 B.addAttribute(Attribute::Returned);
495
496 // Check each function in turn, determining if an argument is always returned.
497 for (Function *F : SCCNodes) {
498 // We can infer and propagate function attributes only when we know that the
499 // definition we'll get at link time is *exactly* the definition we see now.
500 // For more details, see GlobalValue::mayBeDerefined.
501 if (!F->hasExactDefinition())
502 continue;
503
504 if (F->getReturnType()->isVoidTy())
505 continue;
506
David Majnemerc83044d2016-09-12 16:04:59 +0000507 // There is nothing to do if an argument is already marked as 'returned'.
508 if (any_of(F->args(),
509 [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
510 continue;
511
David Majnemer5246e0b2016-07-19 18:50:26 +0000512 auto FindRetArg = [&]() -> Value * {
513 Value *RetArg = nullptr;
514 for (BasicBlock &BB : *F)
515 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
516 // Note that stripPointerCasts should look through functions with
517 // returned arguments.
518 Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
519 if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
520 return nullptr;
521
522 if (!RetArg)
523 RetArg = RetVal;
524 else if (RetArg != RetVal)
525 return nullptr;
526 }
527
528 return RetArg;
529 };
530
531 if (Value *RetArg = FindRetArg()) {
532 auto *A = cast<Argument>(RetArg);
533 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
534 ++NumReturned;
535 Changed = true;
536 }
537 }
538
539 return Changed;
540}
541
Sanjay Patel4f742162017-02-13 23:10:51 +0000542/// If a callsite has arguments that are also arguments to the parent function,
543/// try to propagate attributes from the callsite's arguments to the parent's
544/// arguments. This may be important because inlining can cause information loss
545/// when attribute knowledge disappears with the inlined call.
546static bool addArgumentAttrsFromCallsites(Function &F) {
547 if (!EnableNonnullArgPropagation)
548 return false;
549
550 bool Changed = false;
551
552 // For an argument attribute to transfer from a callsite to the parent, the
553 // call must be guaranteed to execute every time the parent is called.
554 // Conservatively, just check for calls in the entry block that are guaranteed
555 // to execute.
556 // TODO: This could be enhanced by testing if the callsite post-dominates the
557 // entry block or by doing simple forward walks or backward walks to the
558 // callsite.
559 BasicBlock &Entry = F.getEntryBlock();
560 for (Instruction &I : Entry) {
561 if (auto CS = CallSite(&I)) {
562 if (auto *CalledFunc = CS.getCalledFunction()) {
563 for (auto &CSArg : CalledFunc->args()) {
564 if (!CSArg.hasNonNullAttr())
565 continue;
566
567 // If the non-null callsite argument operand is an argument to 'F'
568 // (the caller) and the call is guaranteed to execute, then the value
569 // must be non-null throughout 'F'.
570 auto *FArg = dyn_cast<Argument>(CS.getArgOperand(CSArg.getArgNo()));
571 if (FArg && !FArg->hasNonNullAttr()) {
572 FArg->addAttr(Attribute::NonNull);
573 Changed = true;
574 }
575 }
576 }
577 }
578 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
579 break;
580 }
581
582 return Changed;
583}
584
Chandler Carrutha632fb92015-09-13 06:57:25 +0000585/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000586static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000587 bool Changed = false;
588
Nick Lewycky4c378a42011-12-28 23:24:21 +0000589 ArgumentGraph AG;
590
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000591 AttrBuilder B;
592 B.addAttribute(Attribute::NoCapture);
593
Duncan Sands44c8cd92008-12-31 16:14:43 +0000594 // Check each function in turn, determining which pointer arguments are not
595 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000596 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000597 // We can infer and propagate function attributes only when we know that the
598 // definition we'll get at link time is *exactly* the definition we see now.
599 // For more details, see GlobalValue::mayBeDerefined.
600 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000601 continue;
602
Sanjay Patel4f742162017-02-13 23:10:51 +0000603 Changed |= addArgumentAttrsFromCallsites(*F);
604
Nick Lewycky4c378a42011-12-28 23:24:21 +0000605 // Functions that are readonly (or readnone) and nounwind and don't return
606 // a value can't capture arguments. Don't analyze them.
607 if (F->onlyReadsMemory() && F->doesNotThrow() &&
608 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000609 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
610 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000611 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
612 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
613 ++NumNoCapture;
614 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000615 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000616 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000617 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000618 }
619
Chandler Carruth63559d72015-09-13 06:47:20 +0000620 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
621 ++A) {
622 if (!A->getType()->isPointerTy())
623 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000624 bool HasNonLocalUses = false;
625 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000626 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000627 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000628 if (!Tracker.Captured) {
629 if (Tracker.Uses.empty()) {
630 // If it's trivially not captured, mark it nocapture now.
Chandler Carruth63559d72015-09-13 06:47:20 +0000631 A->addAttr(
632 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000633 ++NumNoCapture;
634 Changed = true;
635 } else {
636 // If it's not trivially captured and not trivially not captured,
637 // then it must be calling into another function in our SCC. Save
638 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000639 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000640 for (Argument *Use : Tracker.Uses) {
641 Node->Uses.push_back(AG[Use]);
642 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000643 HasNonLocalUses = true;
644 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000645 }
646 }
647 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
648 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000649 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
650 // Can we determine that it's readonly/readnone without doing an SCC?
651 // Note that we don't allow any calls at all here, or else our result
652 // will be dependent on the iteration order through the functions in the
653 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000654 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000655 Self.insert(&*A);
656 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000657 if (R != Attribute::None) {
658 AttrBuilder B;
659 B.addAttribute(R);
660 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
661 Changed = true;
662 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
663 }
664 }
665 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000666 }
667
668 // The graph we've collected is partial because we stopped scanning for
669 // argument uses once we solved the argument trivially. These partial nodes
670 // show up as ArgumentGraphNode objects with an empty Uses list, and for
671 // these nodes the final decision about whether they capture has already been
672 // made. If the definition doesn't have a 'nocapture' attribute by now, it
673 // captures.
674
Chandler Carruth63559d72015-09-13 06:47:20 +0000675 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000676 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000677 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000678 if (!ArgumentSCC[0]->Definition)
679 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000680
681 // eg. "void f(int* x) { if (...) f(x); }"
682 if (ArgumentSCC[0]->Uses.size() == 1 &&
683 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000684 Argument *A = ArgumentSCC[0]->Definition;
685 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky7e820552009-01-02 03:46:56 +0000686 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000687 Changed = true;
688 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000689 continue;
690 }
691
692 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000693 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
694 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000695 ArgumentGraphNode *Node = *I;
696 if (Node->Uses.empty()) {
697 if (!Node->Definition->hasNoCaptureAttr())
698 SCCCaptured = true;
699 }
700 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000701 if (SCCCaptured)
702 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000703
Chandler Carruth63559d72015-09-13 06:47:20 +0000704 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000705 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
706 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000707 for (ArgumentGraphNode *I : ArgumentSCC) {
708 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000709 }
710
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000711 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
712 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000713 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000714 for (ArgumentGraphNode *Use : N->Uses) {
715 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000716 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
717 continue;
718 SCCCaptured = true;
719 break;
720 }
721 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000722 if (SCCCaptured)
723 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000724
Nick Lewyckyf740db32012-01-05 22:21:45 +0000725 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000726 Argument *A = ArgumentSCC[i]->Definition;
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000727 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky4c378a42011-12-28 23:24:21 +0000728 ++NumNoCapture;
729 Changed = true;
730 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000731
732 // We also want to compute readonly/readnone. With a small number of false
733 // negatives, we can assume that any pointer which is captured isn't going
734 // to be provably readonly or readnone, since by definition we can't
735 // analyze all uses of a captured pointer.
736 //
737 // The false negatives happen when the pointer is captured by a function
738 // that promises readonly/readnone behaviour on the pointer, then the
739 // pointer's lifetime ends before anything that writes to arbitrary memory.
740 // Also, a readonly/readnone pointer may be returned, but returning a
741 // pointer is capturing it.
742
743 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
744 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
745 Argument *A = ArgumentSCC[i]->Definition;
746 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
747 if (K == Attribute::ReadNone)
748 continue;
749 if (K == Attribute::ReadOnly) {
750 ReadAttr = Attribute::ReadOnly;
751 continue;
752 }
753 ReadAttr = K;
754 break;
755 }
756
757 if (ReadAttr != Attribute::None) {
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000758 AttrBuilder B, R;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000759 B.addAttribute(ReadAttr);
Chandler Carruth63559d72015-09-13 06:47:20 +0000760 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000761 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
762 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000763 // Clear out existing readonly/readnone attributes
764 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000765 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
766 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
767 Changed = true;
768 }
769 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000770 }
771
772 return Changed;
773}
774
Chandler Carrutha632fb92015-09-13 06:57:25 +0000775/// Tests whether a function is "malloc-like".
776///
777/// A function is "malloc-like" if it returns either null or a pointer that
778/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000779static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000780 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000781 for (BasicBlock &BB : *F)
782 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000783 FlowsToReturn.insert(Ret->getReturnValue());
784
785 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000786 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000787
788 if (Constant *C = dyn_cast<Constant>(RetVal)) {
789 if (!C->isNullValue() && !isa<UndefValue>(C))
790 return false;
791
792 continue;
793 }
794
795 if (isa<Argument>(RetVal))
796 return false;
797
798 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
799 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000800 // Extend the analysis by looking upwards.
801 case Instruction::BitCast:
802 case Instruction::GetElementPtr:
803 case Instruction::AddrSpaceCast:
804 FlowsToReturn.insert(RVI->getOperand(0));
805 continue;
806 case Instruction::Select: {
807 SelectInst *SI = cast<SelectInst>(RVI);
808 FlowsToReturn.insert(SI->getTrueValue());
809 FlowsToReturn.insert(SI->getFalseValue());
810 continue;
811 }
812 case Instruction::PHI: {
813 PHINode *PN = cast<PHINode>(RVI);
814 for (Value *IncValue : PN->incoming_values())
815 FlowsToReturn.insert(IncValue);
816 continue;
817 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000818
Chandler Carruth63559d72015-09-13 06:47:20 +0000819 // Check whether the pointer came from an allocation.
820 case Instruction::Alloca:
821 break;
822 case Instruction::Call:
823 case Instruction::Invoke: {
824 CallSite CS(RVI);
825 if (CS.paramHasAttr(0, Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000826 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000827 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
828 break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000829 LLVM_FALLTHROUGH;
830 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000831 default:
832 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000833 }
834
Dan Gohman94e61762009-11-19 21:57:48 +0000835 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000836 return false;
837 }
838
839 return true;
840}
841
Chandler Carrutha632fb92015-09-13 06:57:25 +0000842/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000843static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000844 // Check each function in turn, determining which functions return noalias
845 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000846 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000847 // Already noalias.
848 if (F->doesNotAlias(0))
849 continue;
850
Sanjoy Das5ce32722016-04-08 00:48:30 +0000851 // We can infer and propagate function attributes only when we know that the
852 // definition we'll get at link time is *exactly* the definition we see now.
853 // For more details, see GlobalValue::mayBeDerefined.
854 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000855 return false;
856
Chandler Carruth63559d72015-09-13 06:47:20 +0000857 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000858 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000859 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000860 continue;
861
Chandler Carruth3824f852015-09-13 08:23:27 +0000862 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000863 return false;
864 }
865
866 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000867 for (Function *F : SCCNodes) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000868 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000869 continue;
870
871 F->setDoesNotAlias(0);
872 ++NumNoAlias;
873 MadeChange = true;
874 }
875
876 return MadeChange;
877}
878
Chandler Carrutha632fb92015-09-13 06:57:25 +0000879/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000880///
881/// Requires that the function returns a pointer.
882///
883/// Returns true if it believes the function will not return a null, and sets
884/// \p Speculative based on whether the returned conclusion is a speculative
885/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000886static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000887 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000888 assert(F->getReturnType()->isPointerTy() &&
889 "nonnull only meaningful on pointer types");
890 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000891
Philip Reamesa88caea2015-08-31 19:44:38 +0000892 SmallSetVector<Value *, 8> FlowsToReturn;
893 for (BasicBlock &BB : *F)
894 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
895 FlowsToReturn.insert(Ret->getReturnValue());
896
897 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
898 Value *RetVal = FlowsToReturn[i];
899
900 // If this value is locally known to be non-null, we're good
Sean Silva45835e72016-07-02 23:47:27 +0000901 if (isKnownNonNull(RetVal))
Philip Reamesa88caea2015-08-31 19:44:38 +0000902 continue;
903
904 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000905 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000906 Instruction *RVI = dyn_cast<Instruction>(RetVal);
907 if (!RVI)
908 return false;
909 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000910 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000911 case Instruction::BitCast:
912 case Instruction::GetElementPtr:
913 case Instruction::AddrSpaceCast:
914 FlowsToReturn.insert(RVI->getOperand(0));
915 continue;
916 case Instruction::Select: {
917 SelectInst *SI = cast<SelectInst>(RVI);
918 FlowsToReturn.insert(SI->getTrueValue());
919 FlowsToReturn.insert(SI->getFalseValue());
920 continue;
921 }
922 case Instruction::PHI: {
923 PHINode *PN = cast<PHINode>(RVI);
924 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
925 FlowsToReturn.insert(PN->getIncomingValue(i));
926 continue;
927 }
928 case Instruction::Call:
929 case Instruction::Invoke: {
930 CallSite CS(RVI);
931 Function *Callee = CS.getCalledFunction();
932 // A call to a node within the SCC is assumed to return null until
933 // proven otherwise
934 if (Callee && SCCNodes.count(Callee)) {
935 Speculative = true;
936 continue;
937 }
938 return false;
939 }
940 default:
Chandler Carruth63559d72015-09-13 06:47:20 +0000941 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +0000942 };
943 llvm_unreachable("should have either continued or returned");
944 }
945
946 return true;
947}
948
Chandler Carrutha632fb92015-09-13 06:57:25 +0000949/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +0000950static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000951 // Speculative that all functions in the SCC return only nonnull
952 // pointers. We may refute this as we analyze functions.
953 bool SCCReturnsNonNull = true;
954
955 bool MadeChange = false;
956
957 // Check each function in turn, determining which functions return nonnull
958 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000959 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000960 // Already nonnull.
961 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
962 Attribute::NonNull))
963 continue;
964
Sanjoy Das5ce32722016-04-08 00:48:30 +0000965 // We can infer and propagate function attributes only when we know that the
966 // definition we'll get at link time is *exactly* the definition we see now.
967 // For more details, see GlobalValue::mayBeDerefined.
968 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +0000969 return false;
970
Chandler Carruth63559d72015-09-13 06:47:20 +0000971 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +0000972 // pointer types.
973 if (!F->getReturnType()->isPointerTy())
974 continue;
975
976 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +0000977 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000978 if (!Speculative) {
979 // Mark the function eagerly since we may discover a function
980 // which prevents us from speculating about the entire SCC
981 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
982 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
983 ++NumNonNullReturn;
984 MadeChange = true;
985 }
986 continue;
987 }
988 // At least one function returns something which could be null, can't
989 // speculate any more.
990 SCCReturnsNonNull = false;
991 }
992
993 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000994 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000995 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
996 Attribute::NonNull) ||
997 !F->getReturnType()->isPointerTy())
998 continue;
999
1000 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
1001 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
1002 ++NumNonNullReturn;
1003 MadeChange = true;
1004 }
1005 }
1006
1007 return MadeChange;
1008}
1009
Justin Lebar9d943972016-03-14 20:18:54 +00001010/// Remove the convergent attribute from all functions in the SCC if every
1011/// callsite within the SCC is not convergent (except for calls to functions
1012/// within the SCC). Returns true if changes were made.
Chandler Carruth3937bc72016-02-12 09:47:49 +00001013static bool removeConvergentAttrs(const SCCNodeSet &SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001014 // For every function in SCC, ensure that either
1015 // * it is not convergent, or
1016 // * we can remove its convergent attribute.
1017 bool HasConvergentFn = false;
Chandler Carruth3937bc72016-02-12 09:47:49 +00001018 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001019 if (!F->isConvergent()) continue;
1020 HasConvergentFn = true;
1021
1022 // Can't remove convergent from function declarations.
1023 if (F->isDeclaration()) return false;
1024
1025 // Can't remove convergent if any of our functions has a convergent call to a
1026 // function not in the SCC.
1027 for (Instruction &I : instructions(*F)) {
1028 CallSite CS(&I);
1029 // Bail if CS is a convergent call to a function not in the SCC.
1030 if (CS && CS.isConvergent() &&
1031 SCCNodes.count(CS.getCalledFunction()) == 0)
1032 return false;
1033 }
1034 }
1035
1036 // If the SCC doesn't have any convergent functions, we have nothing to do.
1037 if (!HasConvergentFn) return false;
1038
1039 // If we got here, all of the calls the SCC makes to functions not in the SCC
1040 // are non-convergent. Therefore all of the SCC's functions can also be made
1041 // non-convergent. We'll remove the attr from the callsites in
1042 // InstCombineCalls.
1043 for (Function *F : SCCNodes) {
1044 if (!F->isConvergent()) continue;
1045
1046 DEBUG(dbgs() << "Removing convergent attr from fn " << F->getName()
1047 << "\n");
Chandler Carruth3937bc72016-02-12 09:47:49 +00001048 F->setNotConvergent();
1049 }
Justin Lebar260854b2016-02-09 23:03:22 +00001050 return true;
1051}
1052
James Molloy7e9bdd52015-11-12 10:55:20 +00001053static bool setDoesNotRecurse(Function &F) {
1054 if (F.doesNotRecurse())
1055 return false;
1056 F.setDoesNotRecurse();
1057 ++NumNoRecurse;
1058 return true;
1059}
1060
Chandler Carruth632d2082016-02-13 08:47:51 +00001061static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +00001062 // Try and identify functions that do not recurse.
1063
1064 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +00001065 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +00001066 return false;
1067
Chandler Carruth632d2082016-02-13 08:47:51 +00001068 Function *F = *SCCNodes.begin();
James Molloy7e9bdd52015-11-12 10:55:20 +00001069 if (!F || F->isDeclaration() || F->doesNotRecurse())
1070 return false;
1071
1072 // If all of the calls in F are identifiable and are to norecurse functions, F
1073 // is norecurse. This check also detects self-recursion as F is not currently
1074 // marked norecurse, so any called from F to F will not be marked norecurse.
Chandler Carruth632d2082016-02-13 08:47:51 +00001075 for (Instruction &I : instructions(*F))
1076 if (auto CS = CallSite(&I)) {
1077 Function *Callee = CS.getCalledFunction();
1078 if (!Callee || Callee == F || !Callee->doesNotRecurse())
1079 // Function calls a potentially recursive function.
1080 return false;
1081 }
James Molloy7e9bdd52015-11-12 10:55:20 +00001082
Chandler Carruth632d2082016-02-13 08:47:51 +00001083 // Every call was to a non-recursive function other than this function, and
1084 // we have no indirect recursion as the SCC size is one. This function cannot
1085 // recurse.
1086 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +00001087}
1088
Chandler Carruthb47f8012016-03-11 11:05:24 +00001089PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
Chandler Carruth88823462016-08-24 09:37:14 +00001090 CGSCCAnalysisManager &AM,
1091 LazyCallGraph &CG,
1092 CGSCCUpdateResult &) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001093 FunctionAnalysisManager &FAM =
Chandler Carruth88823462016-08-24 09:37:14 +00001094 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001095
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001096 // We pass a lambda into functions to wire them up to the analysis manager
1097 // for getting function analyses.
1098 auto AARGetter = [&](Function &F) -> AAResults & {
1099 return FAM.getResult<AAManager>(F);
1100 };
1101
1102 // Fill SCCNodes with the elements of the SCC. Also track whether there are
1103 // any external or opt-none nodes that will prevent us from optimizing any
1104 // part of the SCC.
1105 SCCNodeSet SCCNodes;
1106 bool HasUnknownCall = false;
1107 for (LazyCallGraph::Node &N : C) {
1108 Function &F = N.getFunction();
1109 if (F.hasFnAttribute(Attribute::OptimizeNone)) {
1110 // Treat any function we're trying not to optimize as if it were an
1111 // indirect call and omit it from the node set used below.
1112 HasUnknownCall = true;
1113 continue;
1114 }
1115 // Track whether any functions in this SCC have an unknown call edge.
1116 // Note: if this is ever a performance hit, we can common it with
1117 // subsequent routines which also do scans over the instructions of the
1118 // function.
1119 if (!HasUnknownCall)
1120 for (Instruction &I : instructions(F))
1121 if (auto CS = CallSite(&I))
1122 if (!CS.getCalledFunction()) {
1123 HasUnknownCall = true;
1124 break;
1125 }
1126
1127 SCCNodes.insert(&F);
1128 }
1129
1130 bool Changed = false;
David Majnemer5246e0b2016-07-19 18:50:26 +00001131 Changed |= addArgumentReturnedAttrs(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001132 Changed |= addReadAttrs(SCCNodes, AARGetter);
1133 Changed |= addArgumentAttrs(SCCNodes);
1134
1135 // If we have no external nodes participating in the SCC, we can deduce some
1136 // more precise attributes as well.
1137 if (!HasUnknownCall) {
1138 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001139 Changed |= addNonNullAttrs(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001140 Changed |= removeConvergentAttrs(SCCNodes);
1141 Changed |= addNoRecurseAttrs(SCCNodes);
1142 }
1143
1144 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1145}
1146
1147namespace {
1148struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
1149 static char ID; // Pass identification, replacement for typeid
1150 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001151 initializePostOrderFunctionAttrsLegacyPassPass(
1152 *PassRegistry::getPassRegistry());
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001153 }
1154
1155 bool runOnSCC(CallGraphSCC &SCC) override;
1156
1157 void getAnalysisUsage(AnalysisUsage &AU) const override {
1158 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001159 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001160 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001161 CallGraphSCCPass::getAnalysisUsage(AU);
1162 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001163};
1164}
1165
1166char PostOrderFunctionAttrsLegacyPass::ID = 0;
1167INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1168 "Deduce function attributes", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001169INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001170INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001171INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1172 "Deduce function attributes", false, false)
1173
Chad Rosier611b73b2016-11-07 16:28:04 +00001174Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1175 return new PostOrderFunctionAttrsLegacyPass();
1176}
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001177
Sean Silva997cbea2016-07-03 03:35:03 +00001178template <typename AARGetterT>
1179static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
Chandler Carruthcada2d82015-10-31 00:28:37 +00001180 bool Changed = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001181
1182 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1183 // whether a given CallGraphNode is in this SCC. Also track whether there are
1184 // any external or opt-none nodes that will prevent us from optimizing any
1185 // part of the SCC.
1186 SCCNodeSet SCCNodes;
1187 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001188 for (CallGraphNode *I : SCC) {
1189 Function *F = I->getFunction();
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001190 if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
1191 // External node or function we're trying not to optimize - we both avoid
1192 // transform them and avoid leveraging information they provide.
1193 ExternalNode = true;
1194 continue;
1195 }
1196
1197 SCCNodes.insert(F);
1198 }
1199
David Majnemer5246e0b2016-07-19 18:50:26 +00001200 Changed |= addArgumentReturnedAttrs(SCCNodes);
Chandler Carrutha8125352015-10-30 16:48:08 +00001201 Changed |= addReadAttrs(SCCNodes, AARGetter);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001202 Changed |= addArgumentAttrs(SCCNodes);
1203
Chandler Carruth3a040e62015-12-27 08:41:34 +00001204 // If we have no external nodes participating in the SCC, we can deduce some
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001205 // more precise attributes as well.
1206 if (!ExternalNode) {
1207 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001208 Changed |= addNonNullAttrs(SCCNodes);
Chandler Carruth3937bc72016-02-12 09:47:49 +00001209 Changed |= removeConvergentAttrs(SCCNodes);
Chandler Carruth632d2082016-02-13 08:47:51 +00001210 Changed |= addNoRecurseAttrs(SCCNodes);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001211 }
Chandler Carruth1926b702016-01-08 10:55:52 +00001212
James Molloy7e9bdd52015-11-12 10:55:20 +00001213 return Changed;
1214}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001215
Sean Silva997cbea2016-07-03 03:35:03 +00001216bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1217 if (skipSCC(SCC))
1218 return false;
Peter Collingbournecea1e4e2017-02-09 23:11:52 +00001219 return runImpl(SCC, LegacyAARGetter(*this));
Sean Silva997cbea2016-07-03 03:35:03 +00001220}
1221
Chandler Carruth1926b702016-01-08 10:55:52 +00001222namespace {
Sean Silvaf5080192016-06-12 07:48:51 +00001223struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Chandler Carruth1926b702016-01-08 10:55:52 +00001224 static char ID; // Pass identification, replacement for typeid
Sean Silvaf5080192016-06-12 07:48:51 +00001225 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001226 initializeReversePostOrderFunctionAttrsLegacyPassPass(
1227 *PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001228 }
1229
1230 bool runOnModule(Module &M) override;
1231
1232 void getAnalysisUsage(AnalysisUsage &AU) const override {
1233 AU.setPreservesCFG();
1234 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001235 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001236 }
1237};
1238}
1239
Sean Silvaf5080192016-06-12 07:48:51 +00001240char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
1241INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001242 "Deduce function attributes in RPO", false, false)
1243INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001244INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001245 "Deduce function attributes in RPO", false, false)
1246
1247Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001248 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001249}
1250
1251static bool addNoRecurseAttrsTopDown(Function &F) {
1252 // We check the preconditions for the function prior to calling this to avoid
1253 // the cost of building up a reversible post-order list. We assert them here
1254 // to make sure none of the invariants this relies on were violated.
1255 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1256 assert(!F.doesNotRecurse() &&
1257 "This function has already been deduced as norecurs!");
1258 assert(F.hasInternalLinkage() &&
1259 "Can only do top-down deduction for internal linkage functions!");
1260
1261 // If F is internal and all of its uses are calls from a non-recursive
1262 // functions, then none of its calls could in fact recurse without going
1263 // through a function marked norecurse, and so we can mark this function too
1264 // as norecurse. Note that the uses must actually be calls -- otherwise
1265 // a pointer to this function could be returned from a norecurse function but
1266 // this function could be recursively (indirectly) called. Note that this
1267 // also detects if F is directly recursive as F is not yet marked as
1268 // a norecurse function.
1269 for (auto *U : F.users()) {
1270 auto *I = dyn_cast<Instruction>(U);
1271 if (!I)
1272 return false;
1273 CallSite CS(I);
1274 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1275 return false;
1276 }
1277 return setDoesNotRecurse(F);
1278}
1279
Sean Silvaadc79392016-06-12 05:44:51 +00001280static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001281 // We only have a post-order SCC traversal (because SCCs are inherently
1282 // discovered in post-order), so we accumulate them in a vector and then walk
1283 // it in reverse. This is simpler than using the RPO iterator infrastructure
1284 // because we need to combine SCC detection and the PO walk of the call
1285 // graph. We can also cheat egregiously because we're primarily interested in
1286 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1287 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001288 SmallVector<Function *, 16> Worklist;
1289 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1290 if (I->size() != 1)
1291 continue;
1292
1293 Function *F = I->front()->getFunction();
1294 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1295 F->hasInternalLinkage())
1296 Worklist.push_back(F);
1297 }
1298
James Molloy7e9bdd52015-11-12 10:55:20 +00001299 bool Changed = false;
Chandler Carruth1926b702016-01-08 10:55:52 +00001300 for (auto *F : reverse(Worklist))
1301 Changed |= addNoRecurseAttrsTopDown(*F);
1302
Duncan Sands44c8cd92008-12-31 16:14:43 +00001303 return Changed;
1304}
Sean Silvaadc79392016-06-12 05:44:51 +00001305
Sean Silvaf5080192016-06-12 07:48:51 +00001306bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001307 if (skipModule(M))
1308 return false;
1309
1310 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1311
1312 return deduceFunctionAttributeInRPO(M, CG);
1313}
Sean Silvaf5080192016-06-12 07:48:51 +00001314
1315PreservedAnalyses
Sean Silvafd03ac62016-08-09 00:28:38 +00001316ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
Sean Silvaf5080192016-06-12 07:48:51 +00001317 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1318
Chandler Carruth6acdca72017-01-24 12:55:57 +00001319 if (!deduceFunctionAttributeInRPO(M, CG))
Sean Silvaf5080192016-06-12 07:48:51 +00001320 return PreservedAnalyses::all();
Chandler Carruth6acdca72017-01-24 12:55:57 +00001321
Sean Silvaf5080192016-06-12 07:48:51 +00001322 PreservedAnalyses PA;
1323 PA.preserve<CallGraphAnalysis>();
1324 return PA;
1325}