blob: 5352e32479bb902d6eb5a5bb9f81591240414618 [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//===----------------------------------------------------------------------===//
Eugene Zelenkof27d1612017-10-19 21:21:30 +00009//
Chandler Carruth1926b702016-01-08 10:55:52 +000010/// \file
11/// This file implements interprocedural passes which walk the
12/// call-graph deducing and/or propagating function attributes.
Eugene Zelenkof27d1612017-10-19 21:21:30 +000013//
Duncan Sands44c8cd92008-12-31 16:14:43 +000014//===----------------------------------------------------------------------===//
15
Chandler Carruth9c4ed172016-02-18 11:03:11 +000016#include "llvm/Transforms/IPO/FunctionAttrs.h"
Nick Lewycky4c378a42011-12-28 23:24:21 +000017#include "llvm/ADT/SCCIterator.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000018#include "llvm/ADT/STLExtras.h"
Benjamin Kramer15591272012-10-31 13:45:49 +000019#include "llvm/ADT/SetVector.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000020#include "llvm/ADT/SmallPtrSet.h"
Duncan Sandsb193a372009-01-02 11:54:37 +000021#include "llvm/ADT/SmallSet.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000022#include "llvm/ADT/SmallVector.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000023#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000025#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000026#include "llvm/Analysis/BasicAliasAnalysis.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000027#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/CallGraph.h"
Chandler Carruth839a98e2013-01-07 15:26:48 +000029#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Analysis/CaptureTracking.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000031#include "llvm/Analysis/LazyCallGraph.h"
32#include "llvm/Analysis/MemoryLocation.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000033#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000034#include "llvm/IR/Argument.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/BasicBlock.h"
37#include "llvm/IR/CallSite.h"
38#include "llvm/IR/Constant.h"
39#include "llvm/IR/Constants.h"
40#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000041#include "llvm/IR/InstIterator.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000042#include "llvm/IR/InstrTypes.h"
43#include "llvm/IR/Instruction.h"
44#include "llvm/IR/Instructions.h"
45#include "llvm/IR/Metadata.h"
46#include "llvm/IR/PassManager.h"
47#include "llvm/IR/Type.h"
48#include "llvm/IR/Use.h"
49#include "llvm/IR/User.h"
50#include "llvm/IR/Value.h"
51#include "llvm/Pass.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000055#include "llvm/Support/Debug.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000056#include "llvm/Support/ErrorHandling.h"
Hans Wennborg043bf5b2015-08-31 21:19:18 +000057#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000058#include "llvm/Transforms/IPO.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000059#include <cassert>
60#include <iterator>
61#include <map>
62#include <vector>
63
Duncan Sands44c8cd92008-12-31 16:14:43 +000064using namespace llvm;
65
Chandler Carruth964daaa2014-04-22 02:55:47 +000066#define DEBUG_TYPE "functionattrs"
67
Duncan Sands44c8cd92008-12-31 16:14:43 +000068STATISTIC(NumReadNone, "Number of functions marked readnone");
69STATISTIC(NumReadOnly, "Number of functions marked readonly");
70STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
David Majnemer5246e0b2016-07-19 18:50:26 +000071STATISTIC(NumReturned, "Number of arguments marked returned");
Nick Lewyckyc2ec0722013-07-06 00:29:58 +000072STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
73STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
Nick Lewyckyfbed86a2009-03-08 06:20:47 +000074STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Philip Reamesa88caea2015-08-31 19:44:38 +000075STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
James Molloy7e9bdd52015-11-12 10:55:20 +000076STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
Duncan Sands44c8cd92008-12-31 16:14:43 +000077
Sanjay Patel4f742162017-02-13 23:10:51 +000078// FIXME: This is disabled by default to avoid exposing security vulnerabilities
79// in C/C++ code compiled by clang:
80// http://lists.llvm.org/pipermail/cfe-dev/2017-January/052066.html
81static cl::opt<bool> EnableNonnullArgPropagation(
82 "enable-nonnull-arg-prop", cl::Hidden,
83 cl::desc("Try to propagate nonnull argument attributes from callsites to "
84 "caller functions."));
85
Duncan Sands44c8cd92008-12-31 16:14:43 +000086namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +000087
88using SCCNodeSet = SmallSetVector<Function *, 8>;
89
90} // end anonymous namespace
Chandler Carruthc518ebd2015-10-29 18:29:15 +000091
Peter Collingbournec45f7f32017-02-14 00:28:13 +000092/// Returns the memory access attribute for function F using AAR for AA results,
93/// where SCCNodes is the current SCC.
94///
95/// If ThisBody is true, this function may examine the function body and will
96/// return a result pertaining to this copy of the function. If it is false, the
97/// result will be based only on AA results for the function declaration; it
98/// will be assumed that some other (perhaps less optimized) version of the
99/// function may be selected at link time.
100static MemoryAccessKind checkFunctionMemoryAccess(Function &F, bool ThisBody,
101 AAResults &AAR,
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000102 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000103 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
104 if (MRB == FMRB_DoesNotAccessMemory)
105 // Already perfect!
106 return MAK_ReadNone;
107
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000108 if (!ThisBody) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000109 if (AliasAnalysis::onlyReadsMemory(MRB))
110 return MAK_ReadOnly;
111
112 // Conservatively assume it writes to memory.
113 return MAK_MayWrite;
114 }
115
116 // Scan the function body for instructions that may read or write memory.
117 bool ReadsMemory = false;
118 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
119 Instruction *I = &*II;
120
121 // Some instructions can be ignored even if they read or write memory.
122 // Detect these now, skipping to the next instruction if one is found.
123 CallSite CS(cast<Value>(I));
124 if (CS) {
Sanjoy Das10c8a042016-02-09 18:40:40 +0000125 // Ignore calls to functions in the same SCC, as long as the call sites
126 // don't have operand bundles. Calls with operand bundles are allowed to
127 // have memory effects not described by the memory effects of the call
128 // target.
129 if (!CS.hasOperandBundles() && CS.getCalledFunction() &&
130 SCCNodes.count(CS.getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +0000131 continue;
132 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
Alina Sbirlea63d22502017-12-05 20:12:23 +0000133 ModRefInfo MRI = createModRefInfo(MRB);
Chandler Carruth7542d372015-09-21 17:39:41 +0000134
Chandler Carruth69798fb2015-10-27 01:41:43 +0000135 // If the call doesn't access memory, we're done.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000136 if (isNoModRef(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000137 continue;
138
139 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
140 // The call could access any memory. If that includes writes, give up.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000141 if (isModSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000142 return MAK_MayWrite;
143 // If it reads, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000144 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000145 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000146 continue;
147 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000148
149 // Check whether all pointer arguments point to local memory, and
150 // ignore calls that only access local memory.
151 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
152 CI != CE; ++CI) {
153 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000154 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000155 continue;
156
157 AAMDNodes AAInfo;
158 I->getAAMetadata(AAInfo);
159 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
160
161 // Skip accesses to local or constant memory as they don't impact the
162 // externally visible mod/ref behavior.
163 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
164 continue;
165
Alina Sbirlea63d22502017-12-05 20:12:23 +0000166 if (isModSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000167 // Writes non-local memory. Give up.
168 return MAK_MayWrite;
Alina Sbirlea63d22502017-12-05 20:12:23 +0000169 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000170 // Ok, it reads non-local memory.
171 ReadsMemory = true;
172 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000173 continue;
174 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
175 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
176 if (!LI->isVolatile()) {
177 MemoryLocation Loc = MemoryLocation::get(LI);
178 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
179 continue;
180 }
181 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
182 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
183 if (!SI->isVolatile()) {
184 MemoryLocation Loc = MemoryLocation::get(SI);
185 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
186 continue;
187 }
188 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
189 // Ignore vaargs on local memory.
190 MemoryLocation Loc = MemoryLocation::get(VI);
191 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
192 continue;
193 }
194
195 // Any remaining instructions need to be taken seriously! Check if they
196 // read or write memory.
197 if (I->mayWriteToMemory())
198 // Writes memory. Just give up.
199 return MAK_MayWrite;
200
201 // If this instruction may read memory, remember that.
202 ReadsMemory |= I->mayReadFromMemory();
203 }
204
205 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
206}
207
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000208MemoryAccessKind llvm::computeFunctionBodyMemoryAccess(Function &F,
209 AAResults &AAR) {
210 return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {});
211}
212
Chandler Carrutha632fb92015-09-13 06:57:25 +0000213/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000214template <typename AARGetterT>
Peter Collingbournecea1e4e2017-02-09 23:11:52 +0000215static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000216 // Check if any of the functions in the SCC read or write memory. If they
217 // write memory then they can't be marked readnone or readonly.
218 bool ReadsMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000219 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000220 // Call the callable parameter to look up AA results for this function.
221 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000222
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000223 // Non-exact function definitions may not be selected at link time, and an
224 // alternative version that writes to memory may be selected. See the
225 // comment on GlobalValue::isDefinitionExact for more details.
226 switch (checkFunctionMemoryAccess(*F, F->hasExactDefinition(),
227 AAR, SCCNodes)) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000228 case MAK_MayWrite:
229 return false;
230 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000231 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000232 break;
233 case MAK_ReadNone:
234 // Nothing to do!
235 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000236 }
237 }
238
239 // Success! Functions in this SCC do not access memory, or only read memory.
240 // Give them the appropriate attribute.
241 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000242 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000243 if (F->doesNotAccessMemory())
244 // Already perfect!
245 continue;
246
247 if (F->onlyReadsMemory() && ReadsMemory)
248 // No change.
249 continue;
250
251 MadeChange = true;
252
253 // Clear out any existing attributes.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000254 F->removeFnAttr(Attribute::ReadOnly);
255 F->removeFnAttr(Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000256
257 // Add in the new attribute.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000258 F->addFnAttr(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000259
260 if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000261 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000262 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000263 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000264 }
265
266 return MadeChange;
267}
268
Nick Lewycky4c378a42011-12-28 23:24:21 +0000269namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000270
Chandler Carrutha632fb92015-09-13 06:57:25 +0000271/// For a given pointer Argument, this retains a list of Arguments of functions
272/// in the same SCC that the pointer data flows into. We use this to build an
273/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000274struct ArgumentGraphNode {
275 Argument *Definition;
276 SmallVector<ArgumentGraphNode *, 4> Uses;
277};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000278
Chandler Carruth63559d72015-09-13 06:47:20 +0000279class ArgumentGraph {
280 // We store pointers to ArgumentGraphNode objects, so it's important that
281 // that they not move around upon insert.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000282 using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000283
Chandler Carruth63559d72015-09-13 06:47:20 +0000284 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000285
Chandler Carruth63559d72015-09-13 06:47:20 +0000286 // There is no root node for the argument graph, in fact:
287 // void f(int *x, int *y) { if (...) f(x, y); }
288 // is an example where the graph is disconnected. The SCCIterator requires a
289 // single entry point, so we maintain a fake ("synthetic") root node that
290 // uses every node. Because the graph is directed and nothing points into
291 // the root, it will not participate in any SCCs (except for its own).
292 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000293
Chandler Carruth63559d72015-09-13 06:47:20 +0000294public:
295 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000296
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000297 using iterator = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000298
Chandler Carruth63559d72015-09-13 06:47:20 +0000299 iterator begin() { return SyntheticRoot.Uses.begin(); }
300 iterator end() { return SyntheticRoot.Uses.end(); }
301 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000302
Chandler Carruth63559d72015-09-13 06:47:20 +0000303 ArgumentGraphNode *operator[](Argument *A) {
304 ArgumentGraphNode &Node = ArgumentMap[A];
305 Node.Definition = A;
306 SyntheticRoot.Uses.push_back(&Node);
307 return &Node;
308 }
309};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000310
Chandler Carrutha632fb92015-09-13 06:57:25 +0000311/// This tracker checks whether callees are in the SCC, and if so it does not
312/// consider that a capture, instead adding it to the "Uses" list and
313/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000314struct ArgumentUsesTracker : public CaptureTracker {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000315 ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000316
Chandler Carruth63559d72015-09-13 06:47:20 +0000317 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000318
Chandler Carruth63559d72015-09-13 06:47:20 +0000319 bool captured(const Use *U) override {
320 CallSite CS(U->getUser());
321 if (!CS.getInstruction()) {
322 Captured = true;
323 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000324 }
325
Chandler Carruth63559d72015-09-13 06:47:20 +0000326 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000327 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000328 Captured = true;
329 return true;
330 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000331
Sanjoy Das98bfe262015-11-05 03:04:40 +0000332 // Note: the callee and the two successor blocks *follow* the argument
333 // operands. This means there is no need to adjust UseIndex to account for
334 // these.
335
336 unsigned UseIndex =
337 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
338
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000339 assert(UseIndex < CS.data_operands_size() &&
340 "Indirect function calls should have been filtered above!");
341
342 if (UseIndex >= CS.getNumArgOperands()) {
343 // Data operand, but not a argument operand -- must be a bundle operand
344 assert(CS.hasOperandBundles() && "Must be!");
345
346 // CaptureTracking told us that we're being captured by an operand bundle
347 // use. In this case it does not matter if the callee is within our SCC
348 // or not -- we've been captured in some unknown way, and we have to be
349 // conservative.
350 Captured = true;
351 return true;
352 }
353
Sanjoy Das98bfe262015-11-05 03:04:40 +0000354 if (UseIndex >= F->arg_size()) {
355 assert(F->isVarArg() && "More params than args in non-varargs call");
356 Captured = true;
357 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000358 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000359
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000360 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000361 return false;
362 }
363
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000364 // True only if certainly captured (used outside our SCC).
365 bool Captured = false;
366
367 // Uses within our SCC.
368 SmallVector<Argument *, 4> Uses;
Chandler Carruth63559d72015-09-13 06:47:20 +0000369
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000370 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000371};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000372
373} // end anonymous namespace
Nick Lewycky4c378a42011-12-28 23:24:21 +0000374
375namespace llvm {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000376
Chandler Carruth63559d72015-09-13 06:47:20 +0000377template <> struct GraphTraits<ArgumentGraphNode *> {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000378 using NodeRef = ArgumentGraphNode *;
379 using ChildIteratorType = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000380
Tim Shen48f814e2016-08-31 16:48:13 +0000381 static NodeRef getEntryNode(NodeRef A) { return A; }
382 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
383 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000384};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000385
Chandler Carruth63559d72015-09-13 06:47:20 +0000386template <>
387struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
Tim Shenf2187ed2016-08-22 21:09:30 +0000388 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000389
Chandler Carruth63559d72015-09-13 06:47:20 +0000390 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
391 return AG->begin();
392 }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000393
Chandler Carruth63559d72015-09-13 06:47:20 +0000394 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
395};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000396
397} // end namespace llvm
Nick Lewycky4c378a42011-12-28 23:24:21 +0000398
Chandler Carrutha632fb92015-09-13 06:57:25 +0000399/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000400static Attribute::AttrKind
401determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000402 const SmallPtrSet<Argument *, 8> &SCCNodes) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000403 SmallVector<Use *, 32> Worklist;
404 SmallSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000405
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000406 // inalloca arguments are always clobbered by the call.
407 if (A->hasInAllocaAttr())
408 return Attribute::None;
409
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000410 bool IsRead = false;
411 // We don't need to track IsWritten. If A is written to, return immediately.
412
Chandler Carruthcdf47882014-03-09 03:16:01 +0000413 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000414 Visited.insert(&U);
415 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000416 }
417
418 while (!Worklist.empty()) {
419 Use *U = Worklist.pop_back_val();
420 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000421
422 switch (I->getOpcode()) {
423 case Instruction::BitCast:
424 case Instruction::GetElementPtr:
425 case Instruction::PHI:
426 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000427 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000428 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000429 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000430 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000431 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000432 break;
433
434 case Instruction::Call:
435 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000436 bool Captures = true;
437
438 if (I->getType()->isVoidTy())
439 Captures = false;
440
441 auto AddUsersToWorklistIfCapturing = [&] {
442 if (Captures)
443 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000444 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000445 Worklist.push_back(&UU);
446 };
447
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000448 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000449 if (CS.doesNotAccessMemory()) {
450 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000451 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000452 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000453
454 Function *F = CS.getCalledFunction();
455 if (!F) {
456 if (CS.onlyReadsMemory()) {
457 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000458 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000459 continue;
460 }
461 return Attribute::None;
462 }
463
Sanjoy Das436e2392015-11-07 01:55:53 +0000464 // Note: the callee and the two successor blocks *follow* the argument
465 // operands. This means there is no need to adjust UseIndex to account
466 // for these.
467
468 unsigned UseIndex = std::distance(CS.arg_begin(), U);
469
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000470 // U cannot be the callee operand use: since we're exploring the
471 // transitive uses of an Argument, having such a use be a callee would
472 // imply the CallSite is an indirect call or invoke; and we'd take the
473 // early exit above.
474 assert(UseIndex < CS.data_operands_size() &&
475 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000476
477 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
478
479 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000480 assert(F->isVarArg() && "More params than args in non-varargs call");
481 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000482 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000483
Tilmann Scheller925b1932015-11-20 19:17:10 +0000484 Captures &= !CS.doesNotCapture(UseIndex);
485
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000486 // Since the optimizer (by design) cannot see the data flow corresponding
487 // to a operand bundle use, these cannot participate in the optimistic SCC
488 // analysis. Instead, we model the operand bundle uses as arguments in
489 // call to a function external to the SCC.
Duncan P. N. Exon Smith9e3edad2016-08-17 01:23:58 +0000490 if (IsOperandBundleUse ||
491 !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000492
493 // The accessors used on CallSite here do the right thing for calls and
494 // invokes with operand bundles.
495
Sanjoy Das436e2392015-11-07 01:55:53 +0000496 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
497 return Attribute::None;
498 if (!CS.doesNotAccessMemory(UseIndex))
499 IsRead = true;
500 }
501
Nick Lewycky59633cb2014-05-30 02:31:27 +0000502 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000503 break;
504 }
505
506 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000507 // A volatile load has side effects beyond what readonly can be relied
508 // upon.
509 if (cast<LoadInst>(I)->isVolatile())
510 return Attribute::None;
511
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000512 IsRead = true;
513 break;
514
515 case Instruction::ICmp:
516 case Instruction::Ret:
517 break;
518
519 default:
520 return Attribute::None;
521 }
522 }
523
524 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
525}
526
David Majnemer5246e0b2016-07-19 18:50:26 +0000527/// Deduce returned attributes for the SCC.
528static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
529 bool Changed = false;
530
David Majnemer5246e0b2016-07-19 18:50:26 +0000531 // Check each function in turn, determining if an argument is always returned.
532 for (Function *F : SCCNodes) {
533 // We can infer and propagate function attributes only when we know that the
534 // definition we'll get at link time is *exactly* the definition we see now.
535 // For more details, see GlobalValue::mayBeDerefined.
536 if (!F->hasExactDefinition())
537 continue;
538
539 if (F->getReturnType()->isVoidTy())
540 continue;
541
David Majnemerc83044d2016-09-12 16:04:59 +0000542 // There is nothing to do if an argument is already marked as 'returned'.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000543 if (llvm::any_of(F->args(),
544 [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
David Majnemerc83044d2016-09-12 16:04:59 +0000545 continue;
546
David Majnemer5246e0b2016-07-19 18:50:26 +0000547 auto FindRetArg = [&]() -> Value * {
548 Value *RetArg = nullptr;
549 for (BasicBlock &BB : *F)
550 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
551 // Note that stripPointerCasts should look through functions with
552 // returned arguments.
553 Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
554 if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
555 return nullptr;
556
557 if (!RetArg)
558 RetArg = RetVal;
559 else if (RetArg != RetVal)
560 return nullptr;
561 }
562
563 return RetArg;
564 };
565
566 if (Value *RetArg = FindRetArg()) {
567 auto *A = cast<Argument>(RetArg);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000568 A->addAttr(Attribute::Returned);
David Majnemer5246e0b2016-07-19 18:50:26 +0000569 ++NumReturned;
570 Changed = true;
571 }
572 }
573
574 return Changed;
575}
576
Sanjay Patel4f742162017-02-13 23:10:51 +0000577/// If a callsite has arguments that are also arguments to the parent function,
578/// try to propagate attributes from the callsite's arguments to the parent's
579/// arguments. This may be important because inlining can cause information loss
580/// when attribute knowledge disappears with the inlined call.
581static bool addArgumentAttrsFromCallsites(Function &F) {
582 if (!EnableNonnullArgPropagation)
583 return false;
584
585 bool Changed = false;
586
587 // For an argument attribute to transfer from a callsite to the parent, the
588 // call must be guaranteed to execute every time the parent is called.
589 // Conservatively, just check for calls in the entry block that are guaranteed
590 // to execute.
591 // TODO: This could be enhanced by testing if the callsite post-dominates the
592 // entry block or by doing simple forward walks or backward walks to the
593 // callsite.
594 BasicBlock &Entry = F.getEntryBlock();
595 for (Instruction &I : Entry) {
596 if (auto CS = CallSite(&I)) {
597 if (auto *CalledFunc = CS.getCalledFunction()) {
598 for (auto &CSArg : CalledFunc->args()) {
599 if (!CSArg.hasNonNullAttr())
600 continue;
601
602 // If the non-null callsite argument operand is an argument to 'F'
603 // (the caller) and the call is guaranteed to execute, then the value
604 // must be non-null throughout 'F'.
605 auto *FArg = dyn_cast<Argument>(CS.getArgOperand(CSArg.getArgNo()));
606 if (FArg && !FArg->hasNonNullAttr()) {
607 FArg->addAttr(Attribute::NonNull);
608 Changed = true;
609 }
610 }
611 }
612 }
613 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
614 break;
615 }
616
617 return Changed;
618}
619
Chandler Carrutha632fb92015-09-13 06:57:25 +0000620/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000621static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000622 bool Changed = false;
623
Nick Lewycky4c378a42011-12-28 23:24:21 +0000624 ArgumentGraph AG;
625
Duncan Sands44c8cd92008-12-31 16:14:43 +0000626 // Check each function in turn, determining which pointer arguments are not
627 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000628 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000629 // We can infer and propagate function attributes only when we know that the
630 // definition we'll get at link time is *exactly* the definition we see now.
631 // For more details, see GlobalValue::mayBeDerefined.
632 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000633 continue;
634
Sanjay Patel4f742162017-02-13 23:10:51 +0000635 Changed |= addArgumentAttrsFromCallsites(*F);
636
Nick Lewycky4c378a42011-12-28 23:24:21 +0000637 // Functions that are readonly (or readnone) and nounwind and don't return
638 // a value can't capture arguments. Don't analyze them.
639 if (F->onlyReadsMemory() && F->doesNotThrow() &&
640 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000641 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
642 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000643 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000644 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000645 ++NumNoCapture;
646 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000647 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000648 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000649 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000650 }
651
Chandler Carruth63559d72015-09-13 06:47:20 +0000652 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
653 ++A) {
654 if (!A->getType()->isPointerTy())
655 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000656 bool HasNonLocalUses = false;
657 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000658 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000659 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000660 if (!Tracker.Captured) {
661 if (Tracker.Uses.empty()) {
662 // If it's trivially not captured, mark it nocapture now.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000663 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000664 ++NumNoCapture;
665 Changed = true;
666 } else {
667 // If it's not trivially captured and not trivially not captured,
668 // then it must be calling into another function in our SCC. Save
669 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000670 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000671 for (Argument *Use : Tracker.Uses) {
672 Node->Uses.push_back(AG[Use]);
673 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000674 HasNonLocalUses = true;
675 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000676 }
677 }
678 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
679 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000680 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
681 // Can we determine that it's readonly/readnone without doing an SCC?
682 // Note that we don't allow any calls at all here, or else our result
683 // will be dependent on the iteration order through the functions in the
684 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000685 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000686 Self.insert(&*A);
687 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000688 if (R != Attribute::None) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000689 A->addAttr(R);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000690 Changed = true;
691 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
692 }
693 }
694 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000695 }
696
697 // The graph we've collected is partial because we stopped scanning for
698 // argument uses once we solved the argument trivially. These partial nodes
699 // show up as ArgumentGraphNode objects with an empty Uses list, and for
700 // these nodes the final decision about whether they capture has already been
701 // made. If the definition doesn't have a 'nocapture' attribute by now, it
702 // captures.
703
Chandler Carruth63559d72015-09-13 06:47:20 +0000704 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000705 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000706 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000707 if (!ArgumentSCC[0]->Definition)
708 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000709
710 // eg. "void f(int* x) { if (...) f(x); }"
711 if (ArgumentSCC[0]->Uses.size() == 1 &&
712 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000713 Argument *A = ArgumentSCC[0]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000714 A->addAttr(Attribute::NoCapture);
Nick Lewycky7e820552009-01-02 03:46:56 +0000715 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000716 Changed = true;
717 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000718 continue;
719 }
720
721 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000722 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
723 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000724 ArgumentGraphNode *Node = *I;
725 if (Node->Uses.empty()) {
726 if (!Node->Definition->hasNoCaptureAttr())
727 SCCCaptured = true;
728 }
729 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000730 if (SCCCaptured)
731 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000732
Chandler Carruth63559d72015-09-13 06:47:20 +0000733 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000734 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
735 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000736 for (ArgumentGraphNode *I : ArgumentSCC) {
737 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000738 }
739
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000740 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
741 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000742 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000743 for (ArgumentGraphNode *Use : N->Uses) {
744 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000745 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
746 continue;
747 SCCCaptured = true;
748 break;
749 }
750 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000751 if (SCCCaptured)
752 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000753
Nick Lewyckyf740db32012-01-05 22:21:45 +0000754 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000755 Argument *A = ArgumentSCC[i]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000756 A->addAttr(Attribute::NoCapture);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000757 ++NumNoCapture;
758 Changed = true;
759 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000760
761 // We also want to compute readonly/readnone. With a small number of false
762 // negatives, we can assume that any pointer which is captured isn't going
763 // to be provably readonly or readnone, since by definition we can't
764 // analyze all uses of a captured pointer.
765 //
766 // The false negatives happen when the pointer is captured by a function
767 // that promises readonly/readnone behaviour on the pointer, then the
768 // pointer's lifetime ends before anything that writes to arbitrary memory.
769 // Also, a readonly/readnone pointer may be returned, but returning a
770 // pointer is capturing it.
771
772 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
773 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
774 Argument *A = ArgumentSCC[i]->Definition;
775 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
776 if (K == Attribute::ReadNone)
777 continue;
778 if (K == Attribute::ReadOnly) {
779 ReadAttr = Attribute::ReadOnly;
780 continue;
781 }
782 ReadAttr = K;
783 break;
784 }
785
786 if (ReadAttr != Attribute::None) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000787 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
788 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000789 // Clear out existing readonly/readnone attributes
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000790 A->removeAttr(Attribute::ReadOnly);
791 A->removeAttr(Attribute::ReadNone);
792 A->addAttr(ReadAttr);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000793 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
794 Changed = true;
795 }
796 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000797 }
798
799 return Changed;
800}
801
Chandler Carrutha632fb92015-09-13 06:57:25 +0000802/// Tests whether a function is "malloc-like".
803///
804/// A function is "malloc-like" if it returns either null or a pointer that
805/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000806static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000807 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000808 for (BasicBlock &BB : *F)
809 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000810 FlowsToReturn.insert(Ret->getReturnValue());
811
812 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000813 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000814
815 if (Constant *C = dyn_cast<Constant>(RetVal)) {
816 if (!C->isNullValue() && !isa<UndefValue>(C))
817 return false;
818
819 continue;
820 }
821
822 if (isa<Argument>(RetVal))
823 return false;
824
825 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
826 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000827 // Extend the analysis by looking upwards.
828 case Instruction::BitCast:
829 case Instruction::GetElementPtr:
830 case Instruction::AddrSpaceCast:
831 FlowsToReturn.insert(RVI->getOperand(0));
832 continue;
833 case Instruction::Select: {
834 SelectInst *SI = cast<SelectInst>(RVI);
835 FlowsToReturn.insert(SI->getTrueValue());
836 FlowsToReturn.insert(SI->getFalseValue());
837 continue;
838 }
839 case Instruction::PHI: {
840 PHINode *PN = cast<PHINode>(RVI);
841 for (Value *IncValue : PN->incoming_values())
842 FlowsToReturn.insert(IncValue);
843 continue;
844 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000845
Chandler Carruth63559d72015-09-13 06:47:20 +0000846 // Check whether the pointer came from an allocation.
847 case Instruction::Alloca:
848 break;
849 case Instruction::Call:
850 case Instruction::Invoke: {
851 CallSite CS(RVI);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000852 if (CS.hasRetAttr(Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000853 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000854 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
855 break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000856 LLVM_FALLTHROUGH;
857 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000858 default:
859 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000860 }
861
Dan Gohman94e61762009-11-19 21:57:48 +0000862 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000863 return false;
864 }
865
866 return true;
867}
868
Chandler Carrutha632fb92015-09-13 06:57:25 +0000869/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000870static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000871 // Check each function in turn, determining which functions return noalias
872 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000873 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000874 // Already noalias.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000875 if (F->returnDoesNotAlias())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000876 continue;
877
Sanjoy Das5ce32722016-04-08 00:48:30 +0000878 // We can infer and propagate function attributes only when we know that the
879 // definition we'll get at link time is *exactly* the definition we see now.
880 // For more details, see GlobalValue::mayBeDerefined.
881 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000882 return false;
883
Chandler Carruth63559d72015-09-13 06:47:20 +0000884 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000885 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000886 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000887 continue;
888
Chandler Carruth3824f852015-09-13 08:23:27 +0000889 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000890 return false;
891 }
892
893 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000894 for (Function *F : SCCNodes) {
Reid Klecknera0b45f42017-05-03 18:17:31 +0000895 if (F->returnDoesNotAlias() ||
Reid Kleckner6652a522017-04-28 18:37:16 +0000896 !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000897 continue;
898
Reid Klecknera0b45f42017-05-03 18:17:31 +0000899 F->setReturnDoesNotAlias();
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000900 ++NumNoAlias;
901 MadeChange = true;
902 }
903
904 return MadeChange;
905}
906
Chandler Carrutha632fb92015-09-13 06:57:25 +0000907/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000908///
909/// Requires that the function returns a pointer.
910///
911/// Returns true if it believes the function will not return a null, and sets
912/// \p Speculative based on whether the returned conclusion is a speculative
913/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000914static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000915 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000916 assert(F->getReturnType()->isPointerTy() &&
917 "nonnull only meaningful on pointer types");
918 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000919
Philip Reamesa88caea2015-08-31 19:44:38 +0000920 SmallSetVector<Value *, 8> FlowsToReturn;
921 for (BasicBlock &BB : *F)
922 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
923 FlowsToReturn.insert(Ret->getReturnValue());
924
Nuno Lopes404f1062017-09-09 18:23:11 +0000925 auto &DL = F->getParent()->getDataLayout();
926
Philip Reamesa88caea2015-08-31 19:44:38 +0000927 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
928 Value *RetVal = FlowsToReturn[i];
929
930 // If this value is locally known to be non-null, we're good
Nuno Lopes404f1062017-09-09 18:23:11 +0000931 if (isKnownNonZero(RetVal, DL))
Philip Reamesa88caea2015-08-31 19:44:38 +0000932 continue;
933
934 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000935 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000936 Instruction *RVI = dyn_cast<Instruction>(RetVal);
937 if (!RVI)
938 return false;
939 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000940 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000941 case Instruction::BitCast:
942 case Instruction::GetElementPtr:
943 case Instruction::AddrSpaceCast:
944 FlowsToReturn.insert(RVI->getOperand(0));
945 continue;
946 case Instruction::Select: {
947 SelectInst *SI = cast<SelectInst>(RVI);
948 FlowsToReturn.insert(SI->getTrueValue());
949 FlowsToReturn.insert(SI->getFalseValue());
950 continue;
951 }
952 case Instruction::PHI: {
953 PHINode *PN = cast<PHINode>(RVI);
954 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
955 FlowsToReturn.insert(PN->getIncomingValue(i));
956 continue;
957 }
958 case Instruction::Call:
959 case Instruction::Invoke: {
960 CallSite CS(RVI);
961 Function *Callee = CS.getCalledFunction();
962 // A call to a node within the SCC is assumed to return null until
963 // proven otherwise
964 if (Callee && SCCNodes.count(Callee)) {
965 Speculative = true;
966 continue;
967 }
968 return false;
969 }
970 default:
Chandler Carruth63559d72015-09-13 06:47:20 +0000971 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +0000972 };
973 llvm_unreachable("should have either continued or returned");
974 }
975
976 return true;
977}
978
Chandler Carrutha632fb92015-09-13 06:57:25 +0000979/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +0000980static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000981 // Speculative that all functions in the SCC return only nonnull
982 // pointers. We may refute this as we analyze functions.
983 bool SCCReturnsNonNull = true;
984
985 bool MadeChange = false;
986
987 // Check each function in turn, determining which functions return nonnull
988 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000989 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000990 // Already nonnull.
Reid Klecknerb5180542017-03-21 16:57:19 +0000991 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +0000992 Attribute::NonNull))
993 continue;
994
Sanjoy Das5ce32722016-04-08 00:48:30 +0000995 // We can infer and propagate function attributes only when we know that the
996 // definition we'll get at link time is *exactly* the definition we see now.
997 // For more details, see GlobalValue::mayBeDerefined.
998 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +0000999 return false;
1000
Chandler Carruth63559d72015-09-13 06:47:20 +00001001 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +00001002 // pointer types.
1003 if (!F->getReturnType()->isPointerTy())
1004 continue;
1005
1006 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +00001007 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001008 if (!Speculative) {
1009 // Mark the function eagerly since we may discover a function
1010 // which prevents us from speculating about the entire SCC
1011 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001012 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001013 ++NumNonNullReturn;
1014 MadeChange = true;
1015 }
1016 continue;
1017 }
1018 // At least one function returns something which could be null, can't
1019 // speculate any more.
1020 SCCReturnsNonNull = false;
1021 }
1022
1023 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001024 for (Function *F : SCCNodes) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001025 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001026 Attribute::NonNull) ||
1027 !F->getReturnType()->isPointerTy())
1028 continue;
1029
1030 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001031 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001032 ++NumNonNullReturn;
1033 MadeChange = true;
1034 }
1035 }
1036
1037 return MadeChange;
1038}
1039
Justin Lebar9d943972016-03-14 20:18:54 +00001040/// Remove the convergent attribute from all functions in the SCC if every
1041/// callsite within the SCC is not convergent (except for calls to functions
1042/// within the SCC). Returns true if changes were made.
Chandler Carruth3937bc72016-02-12 09:47:49 +00001043static bool removeConvergentAttrs(const SCCNodeSet &SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001044 // For every function in SCC, ensure that either
1045 // * it is not convergent, or
1046 // * we can remove its convergent attribute.
1047 bool HasConvergentFn = false;
Chandler Carruth3937bc72016-02-12 09:47:49 +00001048 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001049 if (!F->isConvergent()) continue;
1050 HasConvergentFn = true;
1051
1052 // Can't remove convergent from function declarations.
1053 if (F->isDeclaration()) return false;
1054
1055 // Can't remove convergent if any of our functions has a convergent call to a
1056 // function not in the SCC.
1057 for (Instruction &I : instructions(*F)) {
1058 CallSite CS(&I);
1059 // Bail if CS is a convergent call to a function not in the SCC.
1060 if (CS && CS.isConvergent() &&
1061 SCCNodes.count(CS.getCalledFunction()) == 0)
1062 return false;
1063 }
1064 }
1065
1066 // If the SCC doesn't have any convergent functions, we have nothing to do.
1067 if (!HasConvergentFn) return false;
1068
1069 // If we got here, all of the calls the SCC makes to functions not in the SCC
1070 // are non-convergent. Therefore all of the SCC's functions can also be made
1071 // non-convergent. We'll remove the attr from the callsites in
1072 // InstCombineCalls.
1073 for (Function *F : SCCNodes) {
1074 if (!F->isConvergent()) continue;
1075
1076 DEBUG(dbgs() << "Removing convergent attr from fn " << F->getName()
1077 << "\n");
Chandler Carruth3937bc72016-02-12 09:47:49 +00001078 F->setNotConvergent();
1079 }
Justin Lebar260854b2016-02-09 23:03:22 +00001080 return true;
1081}
1082
James Molloy7e9bdd52015-11-12 10:55:20 +00001083static bool setDoesNotRecurse(Function &F) {
1084 if (F.doesNotRecurse())
1085 return false;
1086 F.setDoesNotRecurse();
1087 ++NumNoRecurse;
1088 return true;
1089}
1090
Chandler Carruth632d2082016-02-13 08:47:51 +00001091static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +00001092 // Try and identify functions that do not recurse.
1093
1094 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +00001095 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +00001096 return false;
1097
Chandler Carruth632d2082016-02-13 08:47:51 +00001098 Function *F = *SCCNodes.begin();
James Molloy7e9bdd52015-11-12 10:55:20 +00001099 if (!F || F->isDeclaration() || F->doesNotRecurse())
1100 return false;
1101
1102 // If all of the calls in F are identifiable and are to norecurse functions, F
1103 // is norecurse. This check also detects self-recursion as F is not currently
1104 // marked norecurse, so any called from F to F will not be marked norecurse.
Chandler Carruth632d2082016-02-13 08:47:51 +00001105 for (Instruction &I : instructions(*F))
1106 if (auto CS = CallSite(&I)) {
1107 Function *Callee = CS.getCalledFunction();
1108 if (!Callee || Callee == F || !Callee->doesNotRecurse())
1109 // Function calls a potentially recursive function.
1110 return false;
1111 }
James Molloy7e9bdd52015-11-12 10:55:20 +00001112
Chandler Carruth632d2082016-02-13 08:47:51 +00001113 // Every call was to a non-recursive function other than this function, and
1114 // we have no indirect recursion as the SCC size is one. This function cannot
1115 // recurse.
1116 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +00001117}
1118
Chandler Carruthb47f8012016-03-11 11:05:24 +00001119PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
Chandler Carruth88823462016-08-24 09:37:14 +00001120 CGSCCAnalysisManager &AM,
1121 LazyCallGraph &CG,
1122 CGSCCUpdateResult &) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001123 FunctionAnalysisManager &FAM =
Chandler Carruth88823462016-08-24 09:37:14 +00001124 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001125
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001126 // We pass a lambda into functions to wire them up to the analysis manager
1127 // for getting function analyses.
1128 auto AARGetter = [&](Function &F) -> AAResults & {
1129 return FAM.getResult<AAManager>(F);
1130 };
1131
1132 // Fill SCCNodes with the elements of the SCC. Also track whether there are
1133 // any external or opt-none nodes that will prevent us from optimizing any
1134 // part of the SCC.
1135 SCCNodeSet SCCNodes;
1136 bool HasUnknownCall = false;
1137 for (LazyCallGraph::Node &N : C) {
1138 Function &F = N.getFunction();
1139 if (F.hasFnAttribute(Attribute::OptimizeNone)) {
1140 // Treat any function we're trying not to optimize as if it were an
1141 // indirect call and omit it from the node set used below.
1142 HasUnknownCall = true;
1143 continue;
1144 }
1145 // Track whether any functions in this SCC have an unknown call edge.
1146 // Note: if this is ever a performance hit, we can common it with
1147 // subsequent routines which also do scans over the instructions of the
1148 // function.
1149 if (!HasUnknownCall)
1150 for (Instruction &I : instructions(F))
1151 if (auto CS = CallSite(&I))
1152 if (!CS.getCalledFunction()) {
1153 HasUnknownCall = true;
1154 break;
1155 }
1156
1157 SCCNodes.insert(&F);
1158 }
1159
1160 bool Changed = false;
David Majnemer5246e0b2016-07-19 18:50:26 +00001161 Changed |= addArgumentReturnedAttrs(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001162 Changed |= addReadAttrs(SCCNodes, AARGetter);
1163 Changed |= addArgumentAttrs(SCCNodes);
1164
1165 // If we have no external nodes participating in the SCC, we can deduce some
1166 // more precise attributes as well.
1167 if (!HasUnknownCall) {
1168 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001169 Changed |= addNonNullAttrs(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001170 Changed |= removeConvergentAttrs(SCCNodes);
1171 Changed |= addNoRecurseAttrs(SCCNodes);
1172 }
1173
1174 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1175}
1176
1177namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001178
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001179struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001180 // Pass identification, replacement for typeid
1181 static char ID;
1182
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001183 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001184 initializePostOrderFunctionAttrsLegacyPassPass(
1185 *PassRegistry::getPassRegistry());
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001186 }
1187
1188 bool runOnSCC(CallGraphSCC &SCC) override;
1189
1190 void getAnalysisUsage(AnalysisUsage &AU) const override {
1191 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001192 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001193 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001194 CallGraphSCCPass::getAnalysisUsage(AU);
1195 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001196};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001197
1198} // end anonymous namespace
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001199
1200char PostOrderFunctionAttrsLegacyPass::ID = 0;
1201INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1202 "Deduce function attributes", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001203INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001204INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001205INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1206 "Deduce function attributes", false, false)
1207
Chad Rosier611b73b2016-11-07 16:28:04 +00001208Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1209 return new PostOrderFunctionAttrsLegacyPass();
1210}
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001211
Sean Silva997cbea2016-07-03 03:35:03 +00001212template <typename AARGetterT>
1213static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
Chandler Carruthcada2d82015-10-31 00:28:37 +00001214 bool Changed = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001215
1216 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1217 // whether a given CallGraphNode is in this SCC. Also track whether there are
1218 // any external or opt-none nodes that will prevent us from optimizing any
1219 // part of the SCC.
1220 SCCNodeSet SCCNodes;
1221 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001222 for (CallGraphNode *I : SCC) {
1223 Function *F = I->getFunction();
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001224 if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
1225 // External node or function we're trying not to optimize - we both avoid
1226 // transform them and avoid leveraging information they provide.
1227 ExternalNode = true;
1228 continue;
1229 }
1230
1231 SCCNodes.insert(F);
1232 }
1233
David Blaikie6aeacaa2017-06-02 21:24:17 +00001234 // Skip it if the SCC only contains optnone functions.
1235 if (SCCNodes.empty())
1236 return Changed;
1237
David Majnemer5246e0b2016-07-19 18:50:26 +00001238 Changed |= addArgumentReturnedAttrs(SCCNodes);
Chandler Carrutha8125352015-10-30 16:48:08 +00001239 Changed |= addReadAttrs(SCCNodes, AARGetter);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001240 Changed |= addArgumentAttrs(SCCNodes);
1241
Chandler Carruth3a040e62015-12-27 08:41:34 +00001242 // If we have no external nodes participating in the SCC, we can deduce some
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001243 // more precise attributes as well.
1244 if (!ExternalNode) {
1245 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001246 Changed |= addNonNullAttrs(SCCNodes);
Chandler Carruth3937bc72016-02-12 09:47:49 +00001247 Changed |= removeConvergentAttrs(SCCNodes);
Chandler Carruth632d2082016-02-13 08:47:51 +00001248 Changed |= addNoRecurseAttrs(SCCNodes);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001249 }
Chandler Carruth1926b702016-01-08 10:55:52 +00001250
James Molloy7e9bdd52015-11-12 10:55:20 +00001251 return Changed;
1252}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001253
Sean Silva997cbea2016-07-03 03:35:03 +00001254bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1255 if (skipSCC(SCC))
1256 return false;
Peter Collingbournecea1e4e2017-02-09 23:11:52 +00001257 return runImpl(SCC, LegacyAARGetter(*this));
Sean Silva997cbea2016-07-03 03:35:03 +00001258}
1259
Chandler Carruth1926b702016-01-08 10:55:52 +00001260namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001261
Sean Silvaf5080192016-06-12 07:48:51 +00001262struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001263 // Pass identification, replacement for typeid
1264 static char ID;
1265
Sean Silvaf5080192016-06-12 07:48:51 +00001266 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001267 initializeReversePostOrderFunctionAttrsLegacyPassPass(
1268 *PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001269 }
1270
1271 bool runOnModule(Module &M) override;
1272
1273 void getAnalysisUsage(AnalysisUsage &AU) const override {
1274 AU.setPreservesCFG();
1275 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001276 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001277 }
1278};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001279
1280} // end anonymous namespace
Chandler Carruth1926b702016-01-08 10:55:52 +00001281
Sean Silvaf5080192016-06-12 07:48:51 +00001282char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001283
Sean Silvaf5080192016-06-12 07:48:51 +00001284INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001285 "Deduce function attributes in RPO", false, false)
1286INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001287INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001288 "Deduce function attributes in RPO", false, false)
1289
1290Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001291 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001292}
1293
1294static bool addNoRecurseAttrsTopDown(Function &F) {
1295 // We check the preconditions for the function prior to calling this to avoid
1296 // the cost of building up a reversible post-order list. We assert them here
1297 // to make sure none of the invariants this relies on were violated.
1298 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1299 assert(!F.doesNotRecurse() &&
1300 "This function has already been deduced as norecurs!");
1301 assert(F.hasInternalLinkage() &&
1302 "Can only do top-down deduction for internal linkage functions!");
1303
1304 // If F is internal and all of its uses are calls from a non-recursive
1305 // functions, then none of its calls could in fact recurse without going
1306 // through a function marked norecurse, and so we can mark this function too
1307 // as norecurse. Note that the uses must actually be calls -- otherwise
1308 // a pointer to this function could be returned from a norecurse function but
1309 // this function could be recursively (indirectly) called. Note that this
1310 // also detects if F is directly recursive as F is not yet marked as
1311 // a norecurse function.
1312 for (auto *U : F.users()) {
1313 auto *I = dyn_cast<Instruction>(U);
1314 if (!I)
1315 return false;
1316 CallSite CS(I);
1317 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1318 return false;
1319 }
1320 return setDoesNotRecurse(F);
1321}
1322
Sean Silvaadc79392016-06-12 05:44:51 +00001323static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001324 // We only have a post-order SCC traversal (because SCCs are inherently
1325 // discovered in post-order), so we accumulate them in a vector and then walk
1326 // it in reverse. This is simpler than using the RPO iterator infrastructure
1327 // because we need to combine SCC detection and the PO walk of the call
1328 // graph. We can also cheat egregiously because we're primarily interested in
1329 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1330 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001331 SmallVector<Function *, 16> Worklist;
1332 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1333 if (I->size() != 1)
1334 continue;
1335
1336 Function *F = I->front()->getFunction();
1337 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1338 F->hasInternalLinkage())
1339 Worklist.push_back(F);
1340 }
1341
James Molloy7e9bdd52015-11-12 10:55:20 +00001342 bool Changed = false;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001343 for (auto *F : llvm::reverse(Worklist))
Chandler Carruth1926b702016-01-08 10:55:52 +00001344 Changed |= addNoRecurseAttrsTopDown(*F);
1345
Duncan Sands44c8cd92008-12-31 16:14:43 +00001346 return Changed;
1347}
Sean Silvaadc79392016-06-12 05:44:51 +00001348
Sean Silvaf5080192016-06-12 07:48:51 +00001349bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001350 if (skipModule(M))
1351 return false;
1352
1353 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1354
1355 return deduceFunctionAttributeInRPO(M, CG);
1356}
Sean Silvaf5080192016-06-12 07:48:51 +00001357
1358PreservedAnalyses
Sean Silvafd03ac62016-08-09 00:28:38 +00001359ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
Sean Silvaf5080192016-06-12 07:48:51 +00001360 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1361
Chandler Carruth6acdca72017-01-24 12:55:57 +00001362 if (!deduceFunctionAttributeInRPO(M, CG))
Sean Silvaf5080192016-06-12 07:48:51 +00001363 return PreservedAnalyses::all();
Chandler Carruth6acdca72017-01-24 12:55:57 +00001364
Sean Silvaf5080192016-06-12 07:48:51 +00001365 PreservedAnalyses PA;
1366 PA.preserve<CallGraphAnalysis>();
1367 return PA;
1368}