blob: d79a1b3f6b6447d7f0db02eafe43fd0c023da187 [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
Peter Collingbournec45f7f32017-02-14 00:28:13 +000064/// Returns the memory access attribute for function F using AAR for AA results,
65/// where SCCNodes is the current SCC.
66///
67/// If ThisBody is true, this function may examine the function body and will
68/// return a result pertaining to this copy of the function. If it is false, the
69/// result will be based only on AA results for the function declaration; it
70/// will be assumed that some other (perhaps less optimized) version of the
71/// function may be selected at link time.
72static MemoryAccessKind checkFunctionMemoryAccess(Function &F, bool ThisBody,
73 AAResults &AAR,
Chandler Carruthc518ebd2015-10-29 18:29:15 +000074 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +000075 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
76 if (MRB == FMRB_DoesNotAccessMemory)
77 // Already perfect!
78 return MAK_ReadNone;
79
Peter Collingbournec45f7f32017-02-14 00:28:13 +000080 if (!ThisBody) {
Chandler Carruth7542d372015-09-21 17:39:41 +000081 if (AliasAnalysis::onlyReadsMemory(MRB))
82 return MAK_ReadOnly;
83
84 // Conservatively assume it writes to memory.
85 return MAK_MayWrite;
86 }
87
88 // Scan the function body for instructions that may read or write memory.
89 bool ReadsMemory = false;
90 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
91 Instruction *I = &*II;
92
93 // Some instructions can be ignored even if they read or write memory.
94 // Detect these now, skipping to the next instruction if one is found.
95 CallSite CS(cast<Value>(I));
96 if (CS) {
Sanjoy Das10c8a042016-02-09 18:40:40 +000097 // Ignore calls to functions in the same SCC, as long as the call sites
98 // don't have operand bundles. Calls with operand bundles are allowed to
99 // have memory effects not described by the memory effects of the call
100 // target.
101 if (!CS.hasOperandBundles() && CS.getCalledFunction() &&
102 SCCNodes.count(CS.getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +0000103 continue;
104 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
Chandler Carruth7542d372015-09-21 17:39:41 +0000105
Chandler Carruth69798fb2015-10-27 01:41:43 +0000106 // If the call doesn't access memory, we're done.
107 if (!(MRB & MRI_ModRef))
108 continue;
109
110 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
111 // The call could access any memory. If that includes writes, give up.
112 if (MRB & MRI_Mod)
113 return MAK_MayWrite;
114 // If it reads, note it.
115 if (MRB & MRI_Ref)
116 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000117 continue;
118 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000119
120 // Check whether all pointer arguments point to local memory, and
121 // ignore calls that only access local memory.
122 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
123 CI != CE; ++CI) {
124 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000125 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000126 continue;
127
128 AAMDNodes AAInfo;
129 I->getAAMetadata(AAInfo);
130 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
131
132 // Skip accesses to local or constant memory as they don't impact the
133 // externally visible mod/ref behavior.
134 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
135 continue;
136
137 if (MRB & MRI_Mod)
138 // Writes non-local memory. Give up.
139 return MAK_MayWrite;
140 if (MRB & MRI_Ref)
141 // Ok, it reads non-local memory.
142 ReadsMemory = true;
143 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000144 continue;
145 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
146 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
147 if (!LI->isVolatile()) {
148 MemoryLocation Loc = MemoryLocation::get(LI);
149 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
150 continue;
151 }
152 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
153 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
154 if (!SI->isVolatile()) {
155 MemoryLocation Loc = MemoryLocation::get(SI);
156 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
157 continue;
158 }
159 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
160 // Ignore vaargs on local memory.
161 MemoryLocation Loc = MemoryLocation::get(VI);
162 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
163 continue;
164 }
165
166 // Any remaining instructions need to be taken seriously! Check if they
167 // read or write memory.
168 if (I->mayWriteToMemory())
169 // Writes memory. Just give up.
170 return MAK_MayWrite;
171
172 // If this instruction may read memory, remember that.
173 ReadsMemory |= I->mayReadFromMemory();
174 }
175
176 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
177}
178
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000179MemoryAccessKind llvm::computeFunctionBodyMemoryAccess(Function &F,
180 AAResults &AAR) {
181 return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {});
182}
183
Chandler Carrutha632fb92015-09-13 06:57:25 +0000184/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000185template <typename AARGetterT>
Peter Collingbournecea1e4e2017-02-09 23:11:52 +0000186static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000187 // Check if any of the functions in the SCC read or write memory. If they
188 // write memory then they can't be marked readnone or readonly.
189 bool ReadsMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000190 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000191 // Call the callable parameter to look up AA results for this function.
192 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000193
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000194 // Non-exact function definitions may not be selected at link time, and an
195 // alternative version that writes to memory may be selected. See the
196 // comment on GlobalValue::isDefinitionExact for more details.
197 switch (checkFunctionMemoryAccess(*F, F->hasExactDefinition(),
198 AAR, SCCNodes)) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000199 case MAK_MayWrite:
200 return false;
201 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000202 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000203 break;
204 case MAK_ReadNone:
205 // Nothing to do!
206 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000207 }
208 }
209
210 // Success! Functions in this SCC do not access memory, or only read memory.
211 // Give them the appropriate attribute.
212 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000213 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000214 if (F->doesNotAccessMemory())
215 // Already perfect!
216 continue;
217
218 if (F->onlyReadsMemory() && ReadsMemory)
219 // No change.
220 continue;
221
222 MadeChange = true;
223
224 // Clear out any existing attributes.
Bill Wendling50d27842012-10-15 20:35:56 +0000225 AttrBuilder B;
Chandler Carruth63559d72015-09-13 06:47:20 +0000226 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
227 F->removeAttributes(
228 AttributeSet::FunctionIndex,
229 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
Duncan Sands44c8cd92008-12-31 16:14:43 +0000230
231 // Add in the new attribute.
Bill Wendlinge94d8432012-12-07 23:16:57 +0000232 F->addAttribute(AttributeSet::FunctionIndex,
Bill Wendlingc0e2a1f2013-01-23 00:20:53 +0000233 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000234
235 if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000236 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000237 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000238 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000239 }
240
241 return MadeChange;
242}
243
Nick Lewycky4c378a42011-12-28 23:24:21 +0000244namespace {
Chandler Carrutha632fb92015-09-13 06:57:25 +0000245/// For a given pointer Argument, this retains a list of Arguments of functions
246/// in the same SCC that the pointer data flows into. We use this to build an
247/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000248struct ArgumentGraphNode {
249 Argument *Definition;
250 SmallVector<ArgumentGraphNode *, 4> Uses;
251};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000252
Chandler Carruth63559d72015-09-13 06:47:20 +0000253class ArgumentGraph {
254 // We store pointers to ArgumentGraphNode objects, so it's important that
255 // that they not move around upon insert.
256 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000257
Chandler Carruth63559d72015-09-13 06:47:20 +0000258 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000259
Chandler Carruth63559d72015-09-13 06:47:20 +0000260 // There is no root node for the argument graph, in fact:
261 // void f(int *x, int *y) { if (...) f(x, y); }
262 // is an example where the graph is disconnected. The SCCIterator requires a
263 // single entry point, so we maintain a fake ("synthetic") root node that
264 // uses every node. Because the graph is directed and nothing points into
265 // the root, it will not participate in any SCCs (except for its own).
266 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000267
Chandler Carruth63559d72015-09-13 06:47:20 +0000268public:
269 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000270
Chandler Carruth63559d72015-09-13 06:47:20 +0000271 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000272
Chandler Carruth63559d72015-09-13 06:47:20 +0000273 iterator begin() { return SyntheticRoot.Uses.begin(); }
274 iterator end() { return SyntheticRoot.Uses.end(); }
275 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000276
Chandler Carruth63559d72015-09-13 06:47:20 +0000277 ArgumentGraphNode *operator[](Argument *A) {
278 ArgumentGraphNode &Node = ArgumentMap[A];
279 Node.Definition = A;
280 SyntheticRoot.Uses.push_back(&Node);
281 return &Node;
282 }
283};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000284
Chandler Carrutha632fb92015-09-13 06:57:25 +0000285/// This tracker checks whether callees are in the SCC, and if so it does not
286/// consider that a capture, instead adding it to the "Uses" list and
287/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000288struct ArgumentUsesTracker : public CaptureTracker {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000289 ArgumentUsesTracker(const SCCNodeSet &SCCNodes)
Nick Lewycky4c378a42011-12-28 23:24:21 +0000290 : Captured(false), SCCNodes(SCCNodes) {}
291
Chandler Carruth63559d72015-09-13 06:47:20 +0000292 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000293
Chandler Carruth63559d72015-09-13 06:47:20 +0000294 bool captured(const Use *U) override {
295 CallSite CS(U->getUser());
296 if (!CS.getInstruction()) {
297 Captured = true;
298 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000299 }
300
Chandler Carruth63559d72015-09-13 06:47:20 +0000301 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000302 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000303 Captured = true;
304 return true;
305 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000306
Sanjoy Das98bfe262015-11-05 03:04:40 +0000307 // Note: the callee and the two successor blocks *follow* the argument
308 // operands. This means there is no need to adjust UseIndex to account for
309 // these.
310
311 unsigned UseIndex =
312 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
313
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000314 assert(UseIndex < CS.data_operands_size() &&
315 "Indirect function calls should have been filtered above!");
316
317 if (UseIndex >= CS.getNumArgOperands()) {
318 // Data operand, but not a argument operand -- must be a bundle operand
319 assert(CS.hasOperandBundles() && "Must be!");
320
321 // CaptureTracking told us that we're being captured by an operand bundle
322 // use. In this case it does not matter if the callee is within our SCC
323 // or not -- we've been captured in some unknown way, and we have to be
324 // conservative.
325 Captured = true;
326 return true;
327 }
328
Sanjoy Das98bfe262015-11-05 03:04:40 +0000329 if (UseIndex >= F->arg_size()) {
330 assert(F->isVarArg() && "More params than args in non-varargs call");
331 Captured = true;
332 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000333 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000334
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000335 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000336 return false;
337 }
338
339 bool Captured; // True only if certainly captured (used outside our SCC).
340 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
341
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000342 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000343};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000344}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000345
346namespace llvm {
Chandler Carruth63559d72015-09-13 06:47:20 +0000347template <> struct GraphTraits<ArgumentGraphNode *> {
Tim Shenb44909e2016-08-01 22:32:20 +0000348 typedef ArgumentGraphNode *NodeRef;
Chandler Carruth63559d72015-09-13 06:47:20 +0000349 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000350
Tim Shen48f814e2016-08-31 16:48:13 +0000351 static NodeRef getEntryNode(NodeRef A) { return A; }
352 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
353 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000354};
355template <>
356struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
Tim Shenf2187ed2016-08-22 21:09:30 +0000357 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000358 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
359 return AG->begin();
360 }
361 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
362};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000363}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000364
Chandler Carrutha632fb92015-09-13 06:57:25 +0000365/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000366static Attribute::AttrKind
367determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000368 const SmallPtrSet<Argument *, 8> &SCCNodes) {
369
370 SmallVector<Use *, 32> Worklist;
371 SmallSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000372
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000373 // inalloca arguments are always clobbered by the call.
374 if (A->hasInAllocaAttr())
375 return Attribute::None;
376
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000377 bool IsRead = false;
378 // We don't need to track IsWritten. If A is written to, return immediately.
379
Chandler Carruthcdf47882014-03-09 03:16:01 +0000380 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000381 Visited.insert(&U);
382 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000383 }
384
385 while (!Worklist.empty()) {
386 Use *U = Worklist.pop_back_val();
387 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000388
389 switch (I->getOpcode()) {
390 case Instruction::BitCast:
391 case Instruction::GetElementPtr:
392 case Instruction::PHI:
393 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000394 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000395 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000396 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000397 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000398 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000399 break;
400
401 case Instruction::Call:
402 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000403 bool Captures = true;
404
405 if (I->getType()->isVoidTy())
406 Captures = false;
407
408 auto AddUsersToWorklistIfCapturing = [&] {
409 if (Captures)
410 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000411 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000412 Worklist.push_back(&UU);
413 };
414
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000415 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000416 if (CS.doesNotAccessMemory()) {
417 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000418 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000419 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000420
421 Function *F = CS.getCalledFunction();
422 if (!F) {
423 if (CS.onlyReadsMemory()) {
424 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000425 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000426 continue;
427 }
428 return Attribute::None;
429 }
430
Sanjoy Das436e2392015-11-07 01:55:53 +0000431 // Note: the callee and the two successor blocks *follow* the argument
432 // operands. This means there is no need to adjust UseIndex to account
433 // for these.
434
435 unsigned UseIndex = std::distance(CS.arg_begin(), U);
436
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000437 // U cannot be the callee operand use: since we're exploring the
438 // transitive uses of an Argument, having such a use be a callee would
439 // imply the CallSite is an indirect call or invoke; and we'd take the
440 // early exit above.
441 assert(UseIndex < CS.data_operands_size() &&
442 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000443
444 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
445
446 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000447 assert(F->isVarArg() && "More params than args in non-varargs call");
448 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000449 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000450
Tilmann Scheller925b1932015-11-20 19:17:10 +0000451 Captures &= !CS.doesNotCapture(UseIndex);
452
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000453 // Since the optimizer (by design) cannot see the data flow corresponding
454 // to a operand bundle use, these cannot participate in the optimistic SCC
455 // analysis. Instead, we model the operand bundle uses as arguments in
456 // call to a function external to the SCC.
Duncan P. N. Exon Smith9e3edad2016-08-17 01:23:58 +0000457 if (IsOperandBundleUse ||
458 !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000459
460 // The accessors used on CallSite here do the right thing for calls and
461 // invokes with operand bundles.
462
Sanjoy Das436e2392015-11-07 01:55:53 +0000463 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
464 return Attribute::None;
465 if (!CS.doesNotAccessMemory(UseIndex))
466 IsRead = true;
467 }
468
Nick Lewycky59633cb2014-05-30 02:31:27 +0000469 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000470 break;
471 }
472
473 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000474 // A volatile load has side effects beyond what readonly can be relied
475 // upon.
476 if (cast<LoadInst>(I)->isVolatile())
477 return Attribute::None;
478
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000479 IsRead = true;
480 break;
481
482 case Instruction::ICmp:
483 case Instruction::Ret:
484 break;
485
486 default:
487 return Attribute::None;
488 }
489 }
490
491 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
492}
493
David Majnemer5246e0b2016-07-19 18:50:26 +0000494/// Deduce returned attributes for the SCC.
495static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
496 bool Changed = false;
497
498 AttrBuilder B;
499 B.addAttribute(Attribute::Returned);
500
501 // Check each function in turn, determining if an argument is always returned.
502 for (Function *F : SCCNodes) {
503 // We can infer and propagate function attributes only when we know that the
504 // definition we'll get at link time is *exactly* the definition we see now.
505 // For more details, see GlobalValue::mayBeDerefined.
506 if (!F->hasExactDefinition())
507 continue;
508
509 if (F->getReturnType()->isVoidTy())
510 continue;
511
David Majnemerc83044d2016-09-12 16:04:59 +0000512 // There is nothing to do if an argument is already marked as 'returned'.
513 if (any_of(F->args(),
514 [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
515 continue;
516
David Majnemer5246e0b2016-07-19 18:50:26 +0000517 auto FindRetArg = [&]() -> Value * {
518 Value *RetArg = nullptr;
519 for (BasicBlock &BB : *F)
520 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
521 // Note that stripPointerCasts should look through functions with
522 // returned arguments.
523 Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
524 if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
525 return nullptr;
526
527 if (!RetArg)
528 RetArg = RetVal;
529 else if (RetArg != RetVal)
530 return nullptr;
531 }
532
533 return RetArg;
534 };
535
536 if (Value *RetArg = FindRetArg()) {
537 auto *A = cast<Argument>(RetArg);
538 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
539 ++NumReturned;
540 Changed = true;
541 }
542 }
543
544 return Changed;
545}
546
Sanjay Patel4f742162017-02-13 23:10:51 +0000547/// If a callsite has arguments that are also arguments to the parent function,
548/// try to propagate attributes from the callsite's arguments to the parent's
549/// arguments. This may be important because inlining can cause information loss
550/// when attribute knowledge disappears with the inlined call.
551static bool addArgumentAttrsFromCallsites(Function &F) {
552 if (!EnableNonnullArgPropagation)
553 return false;
554
555 bool Changed = false;
556
557 // For an argument attribute to transfer from a callsite to the parent, the
558 // call must be guaranteed to execute every time the parent is called.
559 // Conservatively, just check for calls in the entry block that are guaranteed
560 // to execute.
561 // TODO: This could be enhanced by testing if the callsite post-dominates the
562 // entry block or by doing simple forward walks or backward walks to the
563 // callsite.
564 BasicBlock &Entry = F.getEntryBlock();
565 for (Instruction &I : Entry) {
566 if (auto CS = CallSite(&I)) {
567 if (auto *CalledFunc = CS.getCalledFunction()) {
568 for (auto &CSArg : CalledFunc->args()) {
569 if (!CSArg.hasNonNullAttr())
570 continue;
571
572 // If the non-null callsite argument operand is an argument to 'F'
573 // (the caller) and the call is guaranteed to execute, then the value
574 // must be non-null throughout 'F'.
575 auto *FArg = dyn_cast<Argument>(CS.getArgOperand(CSArg.getArgNo()));
576 if (FArg && !FArg->hasNonNullAttr()) {
577 FArg->addAttr(Attribute::NonNull);
578 Changed = true;
579 }
580 }
581 }
582 }
583 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
584 break;
585 }
586
587 return Changed;
588}
589
Chandler Carrutha632fb92015-09-13 06:57:25 +0000590/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000591static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000592 bool Changed = false;
593
Nick Lewycky4c378a42011-12-28 23:24:21 +0000594 ArgumentGraph AG;
595
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000596 AttrBuilder B;
597 B.addAttribute(Attribute::NoCapture);
598
Duncan Sands44c8cd92008-12-31 16:14:43 +0000599 // Check each function in turn, determining which pointer arguments are not
600 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000601 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000602 // We can infer and propagate function attributes only when we know that the
603 // definition we'll get at link time is *exactly* the definition we see now.
604 // For more details, see GlobalValue::mayBeDerefined.
605 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000606 continue;
607
Sanjay Patel4f742162017-02-13 23:10:51 +0000608 Changed |= addArgumentAttrsFromCallsites(*F);
609
Nick Lewycky4c378a42011-12-28 23:24:21 +0000610 // Functions that are readonly (or readnone) and nounwind and don't return
611 // a value can't capture arguments. Don't analyze them.
612 if (F->onlyReadsMemory() && F->doesNotThrow() &&
613 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000614 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
615 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000616 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
617 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
618 ++NumNoCapture;
619 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000620 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000621 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000622 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000623 }
624
Chandler Carruth63559d72015-09-13 06:47:20 +0000625 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
626 ++A) {
627 if (!A->getType()->isPointerTy())
628 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000629 bool HasNonLocalUses = false;
630 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000631 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000632 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000633 if (!Tracker.Captured) {
634 if (Tracker.Uses.empty()) {
635 // If it's trivially not captured, mark it nocapture now.
Chandler Carruth63559d72015-09-13 06:47:20 +0000636 A->addAttr(
637 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000638 ++NumNoCapture;
639 Changed = true;
640 } else {
641 // If it's not trivially captured and not trivially not captured,
642 // then it must be calling into another function in our SCC. Save
643 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000644 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000645 for (Argument *Use : Tracker.Uses) {
646 Node->Uses.push_back(AG[Use]);
647 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000648 HasNonLocalUses = true;
649 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000650 }
651 }
652 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
653 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000654 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
655 // Can we determine that it's readonly/readnone without doing an SCC?
656 // Note that we don't allow any calls at all here, or else our result
657 // will be dependent on the iteration order through the functions in the
658 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000659 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000660 Self.insert(&*A);
661 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000662 if (R != Attribute::None) {
663 AttrBuilder B;
664 B.addAttribute(R);
665 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
666 Changed = true;
667 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
668 }
669 }
670 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000671 }
672
673 // The graph we've collected is partial because we stopped scanning for
674 // argument uses once we solved the argument trivially. These partial nodes
675 // show up as ArgumentGraphNode objects with an empty Uses list, and for
676 // these nodes the final decision about whether they capture has already been
677 // made. If the definition doesn't have a 'nocapture' attribute by now, it
678 // captures.
679
Chandler Carruth63559d72015-09-13 06:47:20 +0000680 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000681 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000682 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000683 if (!ArgumentSCC[0]->Definition)
684 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000685
686 // eg. "void f(int* x) { if (...) f(x); }"
687 if (ArgumentSCC[0]->Uses.size() == 1 &&
688 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000689 Argument *A = ArgumentSCC[0]->Definition;
690 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky7e820552009-01-02 03:46:56 +0000691 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000692 Changed = true;
693 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000694 continue;
695 }
696
697 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000698 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
699 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000700 ArgumentGraphNode *Node = *I;
701 if (Node->Uses.empty()) {
702 if (!Node->Definition->hasNoCaptureAttr())
703 SCCCaptured = true;
704 }
705 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000706 if (SCCCaptured)
707 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000708
Chandler Carruth63559d72015-09-13 06:47:20 +0000709 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000710 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
711 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000712 for (ArgumentGraphNode *I : ArgumentSCC) {
713 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000714 }
715
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000716 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
717 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000718 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000719 for (ArgumentGraphNode *Use : N->Uses) {
720 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000721 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
722 continue;
723 SCCCaptured = true;
724 break;
725 }
726 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000727 if (SCCCaptured)
728 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000729
Nick Lewyckyf740db32012-01-05 22:21:45 +0000730 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000731 Argument *A = ArgumentSCC[i]->Definition;
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000732 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky4c378a42011-12-28 23:24:21 +0000733 ++NumNoCapture;
734 Changed = true;
735 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000736
737 // We also want to compute readonly/readnone. With a small number of false
738 // negatives, we can assume that any pointer which is captured isn't going
739 // to be provably readonly or readnone, since by definition we can't
740 // analyze all uses of a captured pointer.
741 //
742 // The false negatives happen when the pointer is captured by a function
743 // that promises readonly/readnone behaviour on the pointer, then the
744 // pointer's lifetime ends before anything that writes to arbitrary memory.
745 // Also, a readonly/readnone pointer may be returned, but returning a
746 // pointer is capturing it.
747
748 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
749 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
750 Argument *A = ArgumentSCC[i]->Definition;
751 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
752 if (K == Attribute::ReadNone)
753 continue;
754 if (K == Attribute::ReadOnly) {
755 ReadAttr = Attribute::ReadOnly;
756 continue;
757 }
758 ReadAttr = K;
759 break;
760 }
761
762 if (ReadAttr != Attribute::None) {
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000763 AttrBuilder B, R;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000764 B.addAttribute(ReadAttr);
Chandler Carruth63559d72015-09-13 06:47:20 +0000765 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000766 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
767 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000768 // Clear out existing readonly/readnone attributes
769 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000770 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
771 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
772 Changed = true;
773 }
774 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000775 }
776
777 return Changed;
778}
779
Chandler Carrutha632fb92015-09-13 06:57:25 +0000780/// Tests whether a function is "malloc-like".
781///
782/// A function is "malloc-like" if it returns either null or a pointer that
783/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000784static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000785 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000786 for (BasicBlock &BB : *F)
787 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000788 FlowsToReturn.insert(Ret->getReturnValue());
789
790 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000791 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000792
793 if (Constant *C = dyn_cast<Constant>(RetVal)) {
794 if (!C->isNullValue() && !isa<UndefValue>(C))
795 return false;
796
797 continue;
798 }
799
800 if (isa<Argument>(RetVal))
801 return false;
802
803 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
804 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000805 // Extend the analysis by looking upwards.
806 case Instruction::BitCast:
807 case Instruction::GetElementPtr:
808 case Instruction::AddrSpaceCast:
809 FlowsToReturn.insert(RVI->getOperand(0));
810 continue;
811 case Instruction::Select: {
812 SelectInst *SI = cast<SelectInst>(RVI);
813 FlowsToReturn.insert(SI->getTrueValue());
814 FlowsToReturn.insert(SI->getFalseValue());
815 continue;
816 }
817 case Instruction::PHI: {
818 PHINode *PN = cast<PHINode>(RVI);
819 for (Value *IncValue : PN->incoming_values())
820 FlowsToReturn.insert(IncValue);
821 continue;
822 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000823
Chandler Carruth63559d72015-09-13 06:47:20 +0000824 // Check whether the pointer came from an allocation.
825 case Instruction::Alloca:
826 break;
827 case Instruction::Call:
828 case Instruction::Invoke: {
829 CallSite CS(RVI);
830 if (CS.paramHasAttr(0, Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000831 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000832 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
833 break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000834 LLVM_FALLTHROUGH;
835 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000836 default:
837 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000838 }
839
Dan Gohman94e61762009-11-19 21:57:48 +0000840 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000841 return false;
842 }
843
844 return true;
845}
846
Chandler Carrutha632fb92015-09-13 06:57:25 +0000847/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000848static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000849 // Check each function in turn, determining which functions return noalias
850 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000851 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000852 // Already noalias.
853 if (F->doesNotAlias(0))
854 continue;
855
Sanjoy Das5ce32722016-04-08 00:48:30 +0000856 // We can infer and propagate function attributes only when we know that the
857 // definition we'll get at link time is *exactly* the definition we see now.
858 // For more details, see GlobalValue::mayBeDerefined.
859 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000860 return false;
861
Chandler Carruth63559d72015-09-13 06:47:20 +0000862 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000863 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000864 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000865 continue;
866
Chandler Carruth3824f852015-09-13 08:23:27 +0000867 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000868 return false;
869 }
870
871 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000872 for (Function *F : SCCNodes) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000873 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000874 continue;
875
876 F->setDoesNotAlias(0);
877 ++NumNoAlias;
878 MadeChange = true;
879 }
880
881 return MadeChange;
882}
883
Chandler Carrutha632fb92015-09-13 06:57:25 +0000884/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000885///
886/// Requires that the function returns a pointer.
887///
888/// Returns true if it believes the function will not return a null, and sets
889/// \p Speculative based on whether the returned conclusion is a speculative
890/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000891static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000892 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000893 assert(F->getReturnType()->isPointerTy() &&
894 "nonnull only meaningful on pointer types");
895 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000896
Philip Reamesa88caea2015-08-31 19:44:38 +0000897 SmallSetVector<Value *, 8> FlowsToReturn;
898 for (BasicBlock &BB : *F)
899 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
900 FlowsToReturn.insert(Ret->getReturnValue());
901
902 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
903 Value *RetVal = FlowsToReturn[i];
904
905 // If this value is locally known to be non-null, we're good
Sean Silva45835e72016-07-02 23:47:27 +0000906 if (isKnownNonNull(RetVal))
Philip Reamesa88caea2015-08-31 19:44:38 +0000907 continue;
908
909 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000910 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000911 Instruction *RVI = dyn_cast<Instruction>(RetVal);
912 if (!RVI)
913 return false;
914 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000915 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000916 case Instruction::BitCast:
917 case Instruction::GetElementPtr:
918 case Instruction::AddrSpaceCast:
919 FlowsToReturn.insert(RVI->getOperand(0));
920 continue;
921 case Instruction::Select: {
922 SelectInst *SI = cast<SelectInst>(RVI);
923 FlowsToReturn.insert(SI->getTrueValue());
924 FlowsToReturn.insert(SI->getFalseValue());
925 continue;
926 }
927 case Instruction::PHI: {
928 PHINode *PN = cast<PHINode>(RVI);
929 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
930 FlowsToReturn.insert(PN->getIncomingValue(i));
931 continue;
932 }
933 case Instruction::Call:
934 case Instruction::Invoke: {
935 CallSite CS(RVI);
936 Function *Callee = CS.getCalledFunction();
937 // A call to a node within the SCC is assumed to return null until
938 // proven otherwise
939 if (Callee && SCCNodes.count(Callee)) {
940 Speculative = true;
941 continue;
942 }
943 return false;
944 }
945 default:
Chandler Carruth63559d72015-09-13 06:47:20 +0000946 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +0000947 };
948 llvm_unreachable("should have either continued or returned");
949 }
950
951 return true;
952}
953
Chandler Carrutha632fb92015-09-13 06:57:25 +0000954/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +0000955static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000956 // Speculative that all functions in the SCC return only nonnull
957 // pointers. We may refute this as we analyze functions.
958 bool SCCReturnsNonNull = true;
959
960 bool MadeChange = false;
961
962 // Check each function in turn, determining which functions return nonnull
963 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000964 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000965 // Already nonnull.
966 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
967 Attribute::NonNull))
968 continue;
969
Sanjoy Das5ce32722016-04-08 00:48:30 +0000970 // We can infer and propagate function attributes only when we know that the
971 // definition we'll get at link time is *exactly* the definition we see now.
972 // For more details, see GlobalValue::mayBeDerefined.
973 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +0000974 return false;
975
Chandler Carruth63559d72015-09-13 06:47:20 +0000976 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +0000977 // pointer types.
978 if (!F->getReturnType()->isPointerTy())
979 continue;
980
981 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +0000982 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000983 if (!Speculative) {
984 // Mark the function eagerly since we may discover a function
985 // which prevents us from speculating about the entire SCC
986 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
987 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
988 ++NumNonNullReturn;
989 MadeChange = true;
990 }
991 continue;
992 }
993 // At least one function returns something which could be null, can't
994 // speculate any more.
995 SCCReturnsNonNull = false;
996 }
997
998 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000999 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001000 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1001 Attribute::NonNull) ||
1002 !F->getReturnType()->isPointerTy())
1003 continue;
1004
1005 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
1006 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
1007 ++NumNonNullReturn;
1008 MadeChange = true;
1009 }
1010 }
1011
1012 return MadeChange;
1013}
1014
Justin Lebar9d943972016-03-14 20:18:54 +00001015/// Remove the convergent attribute from all functions in the SCC if every
1016/// callsite within the SCC is not convergent (except for calls to functions
1017/// within the SCC). Returns true if changes were made.
Chandler Carruth3937bc72016-02-12 09:47:49 +00001018static bool removeConvergentAttrs(const SCCNodeSet &SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001019 // For every function in SCC, ensure that either
1020 // * it is not convergent, or
1021 // * we can remove its convergent attribute.
1022 bool HasConvergentFn = false;
Chandler Carruth3937bc72016-02-12 09:47:49 +00001023 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001024 if (!F->isConvergent()) continue;
1025 HasConvergentFn = true;
1026
1027 // Can't remove convergent from function declarations.
1028 if (F->isDeclaration()) return false;
1029
1030 // Can't remove convergent if any of our functions has a convergent call to a
1031 // function not in the SCC.
1032 for (Instruction &I : instructions(*F)) {
1033 CallSite CS(&I);
1034 // Bail if CS is a convergent call to a function not in the SCC.
1035 if (CS && CS.isConvergent() &&
1036 SCCNodes.count(CS.getCalledFunction()) == 0)
1037 return false;
1038 }
1039 }
1040
1041 // If the SCC doesn't have any convergent functions, we have nothing to do.
1042 if (!HasConvergentFn) return false;
1043
1044 // If we got here, all of the calls the SCC makes to functions not in the SCC
1045 // are non-convergent. Therefore all of the SCC's functions can also be made
1046 // non-convergent. We'll remove the attr from the callsites in
1047 // InstCombineCalls.
1048 for (Function *F : SCCNodes) {
1049 if (!F->isConvergent()) continue;
1050
1051 DEBUG(dbgs() << "Removing convergent attr from fn " << F->getName()
1052 << "\n");
Chandler Carruth3937bc72016-02-12 09:47:49 +00001053 F->setNotConvergent();
1054 }
Justin Lebar260854b2016-02-09 23:03:22 +00001055 return true;
1056}
1057
James Molloy7e9bdd52015-11-12 10:55:20 +00001058static bool setDoesNotRecurse(Function &F) {
1059 if (F.doesNotRecurse())
1060 return false;
1061 F.setDoesNotRecurse();
1062 ++NumNoRecurse;
1063 return true;
1064}
1065
Chandler Carruth632d2082016-02-13 08:47:51 +00001066static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +00001067 // Try and identify functions that do not recurse.
1068
1069 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +00001070 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +00001071 return false;
1072
Chandler Carruth632d2082016-02-13 08:47:51 +00001073 Function *F = *SCCNodes.begin();
James Molloy7e9bdd52015-11-12 10:55:20 +00001074 if (!F || F->isDeclaration() || F->doesNotRecurse())
1075 return false;
1076
1077 // If all of the calls in F are identifiable and are to norecurse functions, F
1078 // is norecurse. This check also detects self-recursion as F is not currently
1079 // marked norecurse, so any called from F to F will not be marked norecurse.
Chandler Carruth632d2082016-02-13 08:47:51 +00001080 for (Instruction &I : instructions(*F))
1081 if (auto CS = CallSite(&I)) {
1082 Function *Callee = CS.getCalledFunction();
1083 if (!Callee || Callee == F || !Callee->doesNotRecurse())
1084 // Function calls a potentially recursive function.
1085 return false;
1086 }
James Molloy7e9bdd52015-11-12 10:55:20 +00001087
Chandler Carruth632d2082016-02-13 08:47:51 +00001088 // Every call was to a non-recursive function other than this function, and
1089 // we have no indirect recursion as the SCC size is one. This function cannot
1090 // recurse.
1091 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +00001092}
1093
Chandler Carruthb47f8012016-03-11 11:05:24 +00001094PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
Chandler Carruth88823462016-08-24 09:37:14 +00001095 CGSCCAnalysisManager &AM,
1096 LazyCallGraph &CG,
1097 CGSCCUpdateResult &) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001098 FunctionAnalysisManager &FAM =
Chandler Carruth88823462016-08-24 09:37:14 +00001099 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001100
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001101 // We pass a lambda into functions to wire them up to the analysis manager
1102 // for getting function analyses.
1103 auto AARGetter = [&](Function &F) -> AAResults & {
1104 return FAM.getResult<AAManager>(F);
1105 };
1106
1107 // Fill SCCNodes with the elements of the SCC. Also track whether there are
1108 // any external or opt-none nodes that will prevent us from optimizing any
1109 // part of the SCC.
1110 SCCNodeSet SCCNodes;
1111 bool HasUnknownCall = false;
1112 for (LazyCallGraph::Node &N : C) {
1113 Function &F = N.getFunction();
1114 if (F.hasFnAttribute(Attribute::OptimizeNone)) {
1115 // Treat any function we're trying not to optimize as if it were an
1116 // indirect call and omit it from the node set used below.
1117 HasUnknownCall = true;
1118 continue;
1119 }
1120 // Track whether any functions in this SCC have an unknown call edge.
1121 // Note: if this is ever a performance hit, we can common it with
1122 // subsequent routines which also do scans over the instructions of the
1123 // function.
1124 if (!HasUnknownCall)
1125 for (Instruction &I : instructions(F))
1126 if (auto CS = CallSite(&I))
1127 if (!CS.getCalledFunction()) {
1128 HasUnknownCall = true;
1129 break;
1130 }
1131
1132 SCCNodes.insert(&F);
1133 }
1134
1135 bool Changed = false;
David Majnemer5246e0b2016-07-19 18:50:26 +00001136 Changed |= addArgumentReturnedAttrs(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001137 Changed |= addReadAttrs(SCCNodes, AARGetter);
1138 Changed |= addArgumentAttrs(SCCNodes);
1139
1140 // If we have no external nodes participating in the SCC, we can deduce some
1141 // more precise attributes as well.
1142 if (!HasUnknownCall) {
1143 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001144 Changed |= addNonNullAttrs(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001145 Changed |= removeConvergentAttrs(SCCNodes);
1146 Changed |= addNoRecurseAttrs(SCCNodes);
1147 }
1148
1149 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1150}
1151
1152namespace {
1153struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
1154 static char ID; // Pass identification, replacement for typeid
1155 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001156 initializePostOrderFunctionAttrsLegacyPassPass(
1157 *PassRegistry::getPassRegistry());
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001158 }
1159
1160 bool runOnSCC(CallGraphSCC &SCC) override;
1161
1162 void getAnalysisUsage(AnalysisUsage &AU) const override {
1163 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001164 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001165 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001166 CallGraphSCCPass::getAnalysisUsage(AU);
1167 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001168};
1169}
1170
1171char PostOrderFunctionAttrsLegacyPass::ID = 0;
1172INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1173 "Deduce function attributes", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001174INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001175INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001176INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1177 "Deduce function attributes", false, false)
1178
Chad Rosier611b73b2016-11-07 16:28:04 +00001179Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1180 return new PostOrderFunctionAttrsLegacyPass();
1181}
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001182
Sean Silva997cbea2016-07-03 03:35:03 +00001183template <typename AARGetterT>
1184static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
Chandler Carruthcada2d82015-10-31 00:28:37 +00001185 bool Changed = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001186
1187 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1188 // whether a given CallGraphNode is in this SCC. Also track whether there are
1189 // any external or opt-none nodes that will prevent us from optimizing any
1190 // part of the SCC.
1191 SCCNodeSet SCCNodes;
1192 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001193 for (CallGraphNode *I : SCC) {
1194 Function *F = I->getFunction();
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001195 if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
1196 // External node or function we're trying not to optimize - we both avoid
1197 // transform them and avoid leveraging information they provide.
1198 ExternalNode = true;
1199 continue;
1200 }
1201
1202 SCCNodes.insert(F);
1203 }
1204
David Majnemer5246e0b2016-07-19 18:50:26 +00001205 Changed |= addArgumentReturnedAttrs(SCCNodes);
Chandler Carrutha8125352015-10-30 16:48:08 +00001206 Changed |= addReadAttrs(SCCNodes, AARGetter);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001207 Changed |= addArgumentAttrs(SCCNodes);
1208
Chandler Carruth3a040e62015-12-27 08:41:34 +00001209 // If we have no external nodes participating in the SCC, we can deduce some
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001210 // more precise attributes as well.
1211 if (!ExternalNode) {
1212 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001213 Changed |= addNonNullAttrs(SCCNodes);
Chandler Carruth3937bc72016-02-12 09:47:49 +00001214 Changed |= removeConvergentAttrs(SCCNodes);
Chandler Carruth632d2082016-02-13 08:47:51 +00001215 Changed |= addNoRecurseAttrs(SCCNodes);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001216 }
Chandler Carruth1926b702016-01-08 10:55:52 +00001217
James Molloy7e9bdd52015-11-12 10:55:20 +00001218 return Changed;
1219}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001220
Sean Silva997cbea2016-07-03 03:35:03 +00001221bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1222 if (skipSCC(SCC))
1223 return false;
Peter Collingbournecea1e4e2017-02-09 23:11:52 +00001224 return runImpl(SCC, LegacyAARGetter(*this));
Sean Silva997cbea2016-07-03 03:35:03 +00001225}
1226
Chandler Carruth1926b702016-01-08 10:55:52 +00001227namespace {
Sean Silvaf5080192016-06-12 07:48:51 +00001228struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Chandler Carruth1926b702016-01-08 10:55:52 +00001229 static char ID; // Pass identification, replacement for typeid
Sean Silvaf5080192016-06-12 07:48:51 +00001230 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001231 initializeReversePostOrderFunctionAttrsLegacyPassPass(
1232 *PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001233 }
1234
1235 bool runOnModule(Module &M) override;
1236
1237 void getAnalysisUsage(AnalysisUsage &AU) const override {
1238 AU.setPreservesCFG();
1239 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001240 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001241 }
1242};
1243}
1244
Sean Silvaf5080192016-06-12 07:48:51 +00001245char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
1246INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001247 "Deduce function attributes in RPO", false, false)
1248INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001249INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001250 "Deduce function attributes in RPO", false, false)
1251
1252Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001253 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001254}
1255
1256static bool addNoRecurseAttrsTopDown(Function &F) {
1257 // We check the preconditions for the function prior to calling this to avoid
1258 // the cost of building up a reversible post-order list. We assert them here
1259 // to make sure none of the invariants this relies on were violated.
1260 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1261 assert(!F.doesNotRecurse() &&
1262 "This function has already been deduced as norecurs!");
1263 assert(F.hasInternalLinkage() &&
1264 "Can only do top-down deduction for internal linkage functions!");
1265
1266 // If F is internal and all of its uses are calls from a non-recursive
1267 // functions, then none of its calls could in fact recurse without going
1268 // through a function marked norecurse, and so we can mark this function too
1269 // as norecurse. Note that the uses must actually be calls -- otherwise
1270 // a pointer to this function could be returned from a norecurse function but
1271 // this function could be recursively (indirectly) called. Note that this
1272 // also detects if F is directly recursive as F is not yet marked as
1273 // a norecurse function.
1274 for (auto *U : F.users()) {
1275 auto *I = dyn_cast<Instruction>(U);
1276 if (!I)
1277 return false;
1278 CallSite CS(I);
1279 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1280 return false;
1281 }
1282 return setDoesNotRecurse(F);
1283}
1284
Sean Silvaadc79392016-06-12 05:44:51 +00001285static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001286 // We only have a post-order SCC traversal (because SCCs are inherently
1287 // discovered in post-order), so we accumulate them in a vector and then walk
1288 // it in reverse. This is simpler than using the RPO iterator infrastructure
1289 // because we need to combine SCC detection and the PO walk of the call
1290 // graph. We can also cheat egregiously because we're primarily interested in
1291 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1292 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001293 SmallVector<Function *, 16> Worklist;
1294 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1295 if (I->size() != 1)
1296 continue;
1297
1298 Function *F = I->front()->getFunction();
1299 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1300 F->hasInternalLinkage())
1301 Worklist.push_back(F);
1302 }
1303
James Molloy7e9bdd52015-11-12 10:55:20 +00001304 bool Changed = false;
Chandler Carruth1926b702016-01-08 10:55:52 +00001305 for (auto *F : reverse(Worklist))
1306 Changed |= addNoRecurseAttrsTopDown(*F);
1307
Duncan Sands44c8cd92008-12-31 16:14:43 +00001308 return Changed;
1309}
Sean Silvaadc79392016-06-12 05:44:51 +00001310
Sean Silvaf5080192016-06-12 07:48:51 +00001311bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001312 if (skipModule(M))
1313 return false;
1314
1315 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1316
1317 return deduceFunctionAttributeInRPO(M, CG);
1318}
Sean Silvaf5080192016-06-12 07:48:51 +00001319
1320PreservedAnalyses
Sean Silvafd03ac62016-08-09 00:28:38 +00001321ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
Sean Silvaf5080192016-06-12 07:48:51 +00001322 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1323
Chandler Carruth6acdca72017-01-24 12:55:57 +00001324 if (!deduceFunctionAttributeInRPO(M, CG))
Sean Silvaf5080192016-06-12 07:48:51 +00001325 return PreservedAnalyses::all();
Chandler Carruth6acdca72017-01-24 12:55:57 +00001326
Sean Silvaf5080192016-06-12 07:48:51 +00001327 PreservedAnalyses PA;
1328 PA.preserve<CallGraphAnalysis>();
1329 return PA;
1330}