blob: 2797da6c0abddf26ffa5b80c68b72a67ed24bfab [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"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000021#include "llvm/ADT/SmallVector.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000022#include "llvm/ADT/Statistic.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"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000026#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/CallGraph.h"
Chandler Carruth839a98e2013-01-07 15:26:48 +000028#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Analysis/CaptureTracking.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000030#include "llvm/Analysis/LazyCallGraph.h"
31#include "llvm/Analysis/MemoryLocation.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000032#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000033#include "llvm/IR/Argument.h"
34#include "llvm/IR/Attributes.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/CallSite.h"
37#include "llvm/IR/Constant.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000040#include "llvm/IR/InstIterator.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000041#include "llvm/IR/InstrTypes.h"
42#include "llvm/IR/Instruction.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/Metadata.h"
45#include "llvm/IR/PassManager.h"
46#include "llvm/IR/Type.h"
47#include "llvm/IR/Use.h"
48#include "llvm/IR/User.h"
49#include "llvm/IR/Value.h"
50#include "llvm/Pass.h"
51#include "llvm/Support/Casting.h"
52#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Compiler.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000054#include "llvm/Support/Debug.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000055#include "llvm/Support/ErrorHandling.h"
Hans Wennborg043bf5b2015-08-31 21:19:18 +000056#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000057#include "llvm/Transforms/IPO.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000058#include <cassert>
59#include <iterator>
60#include <map>
61#include <vector>
62
Duncan Sands44c8cd92008-12-31 16:14:43 +000063using namespace llvm;
64
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "functionattrs"
66
Duncan Sands44c8cd92008-12-31 16:14:43 +000067STATISTIC(NumReadNone, "Number of functions marked readnone");
68STATISTIC(NumReadOnly, "Number of functions marked readonly");
69STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
David Majnemer5246e0b2016-07-19 18:50:26 +000070STATISTIC(NumReturned, "Number of arguments marked returned");
Nick Lewyckyc2ec0722013-07-06 00:29:58 +000071STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
72STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
Nick Lewyckyfbed86a2009-03-08 06:20:47 +000073STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Philip Reamesa88caea2015-08-31 19:44:38 +000074STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
James Molloy7e9bdd52015-11-12 10:55:20 +000075STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
Fedor Sergeev6660fd02018-03-23 21:46:16 +000076STATISTIC(NumNoUnwind, "Number of functions marked as nounwind");
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
Fedor Sergeev6660fd02018-03-23 21:46:16 +000086static cl::opt<bool> DisableNoUnwindInference(
87 "disable-nounwind-inference", cl::Hidden,
88 cl::desc("Stop inferring nounwind attribute during function-attrs pass"));
89
Duncan Sands44c8cd92008-12-31 16:14:43 +000090namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +000091
92using SCCNodeSet = SmallSetVector<Function *, 8>;
93
94} // end anonymous namespace
Chandler Carruthc518ebd2015-10-29 18:29:15 +000095
Peter Collingbournec45f7f32017-02-14 00:28:13 +000096/// Returns the memory access attribute for function F using AAR for AA results,
97/// where SCCNodes is the current SCC.
98///
99/// If ThisBody is true, this function may examine the function body and will
100/// return a result pertaining to this copy of the function. If it is false, the
101/// result will be based only on AA results for the function declaration; it
102/// will be assumed that some other (perhaps less optimized) version of the
103/// function may be selected at link time.
104static MemoryAccessKind checkFunctionMemoryAccess(Function &F, bool ThisBody,
105 AAResults &AAR,
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000106 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000107 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
108 if (MRB == FMRB_DoesNotAccessMemory)
109 // Already perfect!
110 return MAK_ReadNone;
111
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000112 if (!ThisBody) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000113 if (AliasAnalysis::onlyReadsMemory(MRB))
114 return MAK_ReadOnly;
115
116 // Conservatively assume it writes to memory.
117 return MAK_MayWrite;
118 }
119
120 // Scan the function body for instructions that may read or write memory.
121 bool ReadsMemory = false;
122 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
123 Instruction *I = &*II;
124
125 // Some instructions can be ignored even if they read or write memory.
126 // Detect these now, skipping to the next instruction if one is found.
127 CallSite CS(cast<Value>(I));
128 if (CS) {
Sanjoy Das10c8a042016-02-09 18:40:40 +0000129 // Ignore calls to functions in the same SCC, as long as the call sites
130 // don't have operand bundles. Calls with operand bundles are allowed to
131 // have memory effects not described by the memory effects of the call
132 // target.
133 if (!CS.hasOperandBundles() && CS.getCalledFunction() &&
134 SCCNodes.count(CS.getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +0000135 continue;
136 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
Alina Sbirlea63d22502017-12-05 20:12:23 +0000137 ModRefInfo MRI = createModRefInfo(MRB);
Chandler Carruth7542d372015-09-21 17:39:41 +0000138
Chandler Carruth69798fb2015-10-27 01:41:43 +0000139 // If the call doesn't access memory, we're done.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000140 if (isNoModRef(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000141 continue;
142
143 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
144 // The call could access any memory. If that includes writes, give up.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000145 if (isModSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000146 return MAK_MayWrite;
147 // If it reads, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000148 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000149 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000150 continue;
151 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000152
153 // Check whether all pointer arguments point to local memory, and
154 // ignore calls that only access local memory.
155 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
156 CI != CE; ++CI) {
157 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000158 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000159 continue;
160
161 AAMDNodes AAInfo;
162 I->getAAMetadata(AAInfo);
163 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
164
165 // Skip accesses to local or constant memory as they don't impact the
166 // externally visible mod/ref behavior.
167 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
168 continue;
169
Alina Sbirlea63d22502017-12-05 20:12:23 +0000170 if (isModSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000171 // Writes non-local memory. Give up.
172 return MAK_MayWrite;
Alina Sbirlea63d22502017-12-05 20:12:23 +0000173 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000174 // Ok, it reads non-local memory.
175 ReadsMemory = true;
176 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000177 continue;
178 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
179 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
180 if (!LI->isVolatile()) {
181 MemoryLocation Loc = MemoryLocation::get(LI);
182 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
183 continue;
184 }
185 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
186 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
187 if (!SI->isVolatile()) {
188 MemoryLocation Loc = MemoryLocation::get(SI);
189 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
190 continue;
191 }
192 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
193 // Ignore vaargs on local memory.
194 MemoryLocation Loc = MemoryLocation::get(VI);
195 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
196 continue;
197 }
198
199 // Any remaining instructions need to be taken seriously! Check if they
200 // read or write memory.
201 if (I->mayWriteToMemory())
202 // Writes memory. Just give up.
203 return MAK_MayWrite;
204
205 // If this instruction may read memory, remember that.
206 ReadsMemory |= I->mayReadFromMemory();
207 }
208
209 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
210}
211
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000212MemoryAccessKind llvm::computeFunctionBodyMemoryAccess(Function &F,
213 AAResults &AAR) {
214 return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {});
215}
216
Chandler Carrutha632fb92015-09-13 06:57:25 +0000217/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000218template <typename AARGetterT>
Peter Collingbournecea1e4e2017-02-09 23:11:52 +0000219static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000220 // Check if any of the functions in the SCC read or write memory. If they
221 // write memory then they can't be marked readnone or readonly.
222 bool ReadsMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000223 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000224 // Call the callable parameter to look up AA results for this function.
225 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000226
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000227 // Non-exact function definitions may not be selected at link time, and an
228 // alternative version that writes to memory may be selected. See the
229 // comment on GlobalValue::isDefinitionExact for more details.
230 switch (checkFunctionMemoryAccess(*F, F->hasExactDefinition(),
231 AAR, SCCNodes)) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000232 case MAK_MayWrite:
233 return false;
234 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000235 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000236 break;
237 case MAK_ReadNone:
238 // Nothing to do!
239 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000240 }
241 }
242
243 // Success! Functions in this SCC do not access memory, or only read memory.
244 // Give them the appropriate attribute.
245 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000246 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000247 if (F->doesNotAccessMemory())
248 // Already perfect!
249 continue;
250
251 if (F->onlyReadsMemory() && ReadsMemory)
252 // No change.
253 continue;
254
255 MadeChange = true;
256
257 // Clear out any existing attributes.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000258 F->removeFnAttr(Attribute::ReadOnly);
259 F->removeFnAttr(Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000260
261 // Add in the new attribute.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000262 F->addFnAttr(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000263
264 if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000265 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000266 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000267 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000268 }
269
270 return MadeChange;
271}
272
Nick Lewycky4c378a42011-12-28 23:24:21 +0000273namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000274
Chandler Carrutha632fb92015-09-13 06:57:25 +0000275/// For a given pointer Argument, this retains a list of Arguments of functions
276/// in the same SCC that the pointer data flows into. We use this to build an
277/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000278struct ArgumentGraphNode {
279 Argument *Definition;
280 SmallVector<ArgumentGraphNode *, 4> Uses;
281};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000282
Chandler Carruth63559d72015-09-13 06:47:20 +0000283class ArgumentGraph {
284 // We store pointers to ArgumentGraphNode objects, so it's important that
285 // that they not move around upon insert.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000286 using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000287
Chandler Carruth63559d72015-09-13 06:47:20 +0000288 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000289
Chandler Carruth63559d72015-09-13 06:47:20 +0000290 // There is no root node for the argument graph, in fact:
291 // void f(int *x, int *y) { if (...) f(x, y); }
292 // is an example where the graph is disconnected. The SCCIterator requires a
293 // single entry point, so we maintain a fake ("synthetic") root node that
294 // uses every node. Because the graph is directed and nothing points into
295 // the root, it will not participate in any SCCs (except for its own).
296 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000297
Chandler Carruth63559d72015-09-13 06:47:20 +0000298public:
299 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000300
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000301 using iterator = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000302
Chandler Carruth63559d72015-09-13 06:47:20 +0000303 iterator begin() { return SyntheticRoot.Uses.begin(); }
304 iterator end() { return SyntheticRoot.Uses.end(); }
305 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000306
Chandler Carruth63559d72015-09-13 06:47:20 +0000307 ArgumentGraphNode *operator[](Argument *A) {
308 ArgumentGraphNode &Node = ArgumentMap[A];
309 Node.Definition = A;
310 SyntheticRoot.Uses.push_back(&Node);
311 return &Node;
312 }
313};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000314
Chandler Carrutha632fb92015-09-13 06:57:25 +0000315/// This tracker checks whether callees are in the SCC, and if so it does not
316/// consider that a capture, instead adding it to the "Uses" list and
317/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000318struct ArgumentUsesTracker : public CaptureTracker {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000319 ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000320
Chandler Carruth63559d72015-09-13 06:47:20 +0000321 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000322
Chandler Carruth63559d72015-09-13 06:47:20 +0000323 bool captured(const Use *U) override {
324 CallSite CS(U->getUser());
325 if (!CS.getInstruction()) {
326 Captured = true;
327 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000328 }
329
Chandler Carruth63559d72015-09-13 06:47:20 +0000330 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000331 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000332 Captured = true;
333 return true;
334 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000335
Sanjoy Das98bfe262015-11-05 03:04:40 +0000336 // Note: the callee and the two successor blocks *follow* the argument
337 // operands. This means there is no need to adjust UseIndex to account for
338 // these.
339
340 unsigned UseIndex =
341 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
342
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000343 assert(UseIndex < CS.data_operands_size() &&
344 "Indirect function calls should have been filtered above!");
345
346 if (UseIndex >= CS.getNumArgOperands()) {
347 // Data operand, but not a argument operand -- must be a bundle operand
348 assert(CS.hasOperandBundles() && "Must be!");
349
350 // CaptureTracking told us that we're being captured by an operand bundle
351 // use. In this case it does not matter if the callee is within our SCC
352 // or not -- we've been captured in some unknown way, and we have to be
353 // conservative.
354 Captured = true;
355 return true;
356 }
357
Sanjoy Das98bfe262015-11-05 03:04:40 +0000358 if (UseIndex >= F->arg_size()) {
359 assert(F->isVarArg() && "More params than args in non-varargs call");
360 Captured = true;
361 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000362 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000363
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000364 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000365 return false;
366 }
367
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000368 // True only if certainly captured (used outside our SCC).
369 bool Captured = false;
370
371 // Uses within our SCC.
372 SmallVector<Argument *, 4> Uses;
Chandler Carruth63559d72015-09-13 06:47:20 +0000373
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000374 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000375};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000376
377} // end anonymous namespace
Nick Lewycky4c378a42011-12-28 23:24:21 +0000378
379namespace llvm {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000380
Chandler Carruth63559d72015-09-13 06:47:20 +0000381template <> struct GraphTraits<ArgumentGraphNode *> {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000382 using NodeRef = ArgumentGraphNode *;
383 using ChildIteratorType = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000384
Tim Shen48f814e2016-08-31 16:48:13 +0000385 static NodeRef getEntryNode(NodeRef A) { return A; }
386 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
387 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000388};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000389
Chandler Carruth63559d72015-09-13 06:47:20 +0000390template <>
391struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
Tim Shenf2187ed2016-08-22 21:09:30 +0000392 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000393
Chandler Carruth63559d72015-09-13 06:47:20 +0000394 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
395 return AG->begin();
396 }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000397
Chandler Carruth63559d72015-09-13 06:47:20 +0000398 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
399};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000400
401} // end namespace llvm
Nick Lewycky4c378a42011-12-28 23:24:21 +0000402
Chandler Carrutha632fb92015-09-13 06:57:25 +0000403/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000404static Attribute::AttrKind
405determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000406 const SmallPtrSet<Argument *, 8> &SCCNodes) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000407 SmallVector<Use *, 32> Worklist;
Florian Hahna1cc8482018-06-12 11:16:56 +0000408 SmallPtrSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000409
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000410 // inalloca arguments are always clobbered by the call.
411 if (A->hasInAllocaAttr())
412 return Attribute::None;
413
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000414 bool IsRead = false;
415 // We don't need to track IsWritten. If A is written to, return immediately.
416
Chandler Carruthcdf47882014-03-09 03:16:01 +0000417 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000418 Visited.insert(&U);
419 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000420 }
421
422 while (!Worklist.empty()) {
423 Use *U = Worklist.pop_back_val();
424 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000425
426 switch (I->getOpcode()) {
427 case Instruction::BitCast:
428 case Instruction::GetElementPtr:
429 case Instruction::PHI:
430 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000431 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000432 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000433 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000434 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000435 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000436 break;
437
438 case Instruction::Call:
439 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000440 bool Captures = true;
441
442 if (I->getType()->isVoidTy())
443 Captures = false;
444
445 auto AddUsersToWorklistIfCapturing = [&] {
446 if (Captures)
447 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000448 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000449 Worklist.push_back(&UU);
450 };
451
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000452 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000453 if (CS.doesNotAccessMemory()) {
454 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000455 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000456 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000457
458 Function *F = CS.getCalledFunction();
459 if (!F) {
460 if (CS.onlyReadsMemory()) {
461 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000462 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000463 continue;
464 }
465 return Attribute::None;
466 }
467
Sanjoy Das436e2392015-11-07 01:55:53 +0000468 // Note: the callee and the two successor blocks *follow* the argument
469 // operands. This means there is no need to adjust UseIndex to account
470 // for these.
471
472 unsigned UseIndex = std::distance(CS.arg_begin(), U);
473
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000474 // U cannot be the callee operand use: since we're exploring the
475 // transitive uses of an Argument, having such a use be a callee would
476 // imply the CallSite is an indirect call or invoke; and we'd take the
477 // early exit above.
478 assert(UseIndex < CS.data_operands_size() &&
479 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000480
481 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
482
483 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000484 assert(F->isVarArg() && "More params than args in non-varargs call");
485 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000486 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000487
Tilmann Scheller925b1932015-11-20 19:17:10 +0000488 Captures &= !CS.doesNotCapture(UseIndex);
489
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000490 // Since the optimizer (by design) cannot see the data flow corresponding
491 // to a operand bundle use, these cannot participate in the optimistic SCC
492 // analysis. Instead, we model the operand bundle uses as arguments in
493 // call to a function external to the SCC.
Duncan P. N. Exon Smith9e3edad2016-08-17 01:23:58 +0000494 if (IsOperandBundleUse ||
495 !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000496
497 // The accessors used on CallSite here do the right thing for calls and
498 // invokes with operand bundles.
499
Sanjoy Das436e2392015-11-07 01:55:53 +0000500 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
501 return Attribute::None;
502 if (!CS.doesNotAccessMemory(UseIndex))
503 IsRead = true;
504 }
505
Nick Lewycky59633cb2014-05-30 02:31:27 +0000506 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000507 break;
508 }
509
510 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000511 // A volatile load has side effects beyond what readonly can be relied
512 // upon.
513 if (cast<LoadInst>(I)->isVolatile())
514 return Attribute::None;
515
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000516 IsRead = true;
517 break;
518
519 case Instruction::ICmp:
520 case Instruction::Ret:
521 break;
522
523 default:
524 return Attribute::None;
525 }
526 }
527
528 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
529}
530
David Majnemer5246e0b2016-07-19 18:50:26 +0000531/// Deduce returned attributes for the SCC.
532static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
533 bool Changed = false;
534
David Majnemer5246e0b2016-07-19 18:50:26 +0000535 // Check each function in turn, determining if an argument is always returned.
536 for (Function *F : SCCNodes) {
537 // We can infer and propagate function attributes only when we know that the
538 // definition we'll get at link time is *exactly* the definition we see now.
539 // For more details, see GlobalValue::mayBeDerefined.
540 if (!F->hasExactDefinition())
541 continue;
542
543 if (F->getReturnType()->isVoidTy())
544 continue;
545
David Majnemerc83044d2016-09-12 16:04:59 +0000546 // There is nothing to do if an argument is already marked as 'returned'.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000547 if (llvm::any_of(F->args(),
548 [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
David Majnemerc83044d2016-09-12 16:04:59 +0000549 continue;
550
David Majnemer5246e0b2016-07-19 18:50:26 +0000551 auto FindRetArg = [&]() -> Value * {
552 Value *RetArg = nullptr;
553 for (BasicBlock &BB : *F)
554 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
555 // Note that stripPointerCasts should look through functions with
556 // returned arguments.
557 Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
558 if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
559 return nullptr;
560
561 if (!RetArg)
562 RetArg = RetVal;
563 else if (RetArg != RetVal)
564 return nullptr;
565 }
566
567 return RetArg;
568 };
569
570 if (Value *RetArg = FindRetArg()) {
571 auto *A = cast<Argument>(RetArg);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000572 A->addAttr(Attribute::Returned);
David Majnemer5246e0b2016-07-19 18:50:26 +0000573 ++NumReturned;
574 Changed = true;
575 }
576 }
577
578 return Changed;
579}
580
Sanjay Patel4f742162017-02-13 23:10:51 +0000581/// If a callsite has arguments that are also arguments to the parent function,
582/// try to propagate attributes from the callsite's arguments to the parent's
583/// arguments. This may be important because inlining can cause information loss
584/// when attribute knowledge disappears with the inlined call.
585static bool addArgumentAttrsFromCallsites(Function &F) {
586 if (!EnableNonnullArgPropagation)
587 return false;
588
589 bool Changed = false;
590
591 // For an argument attribute to transfer from a callsite to the parent, the
592 // call must be guaranteed to execute every time the parent is called.
593 // Conservatively, just check for calls in the entry block that are guaranteed
594 // to execute.
595 // TODO: This could be enhanced by testing if the callsite post-dominates the
596 // entry block or by doing simple forward walks or backward walks to the
597 // callsite.
598 BasicBlock &Entry = F.getEntryBlock();
599 for (Instruction &I : Entry) {
600 if (auto CS = CallSite(&I)) {
601 if (auto *CalledFunc = CS.getCalledFunction()) {
602 for (auto &CSArg : CalledFunc->args()) {
603 if (!CSArg.hasNonNullAttr())
604 continue;
605
606 // If the non-null callsite argument operand is an argument to 'F'
607 // (the caller) and the call is guaranteed to execute, then the value
608 // must be non-null throughout 'F'.
609 auto *FArg = dyn_cast<Argument>(CS.getArgOperand(CSArg.getArgNo()));
610 if (FArg && !FArg->hasNonNullAttr()) {
611 FArg->addAttr(Attribute::NonNull);
612 Changed = true;
613 }
614 }
615 }
616 }
617 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
618 break;
619 }
620
621 return Changed;
622}
623
Chandler Carrutha632fb92015-09-13 06:57:25 +0000624/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000625static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000626 bool Changed = false;
627
Nick Lewycky4c378a42011-12-28 23:24:21 +0000628 ArgumentGraph AG;
629
Duncan Sands44c8cd92008-12-31 16:14:43 +0000630 // Check each function in turn, determining which pointer arguments are not
631 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000632 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000633 // We can infer and propagate function attributes only when we know that the
634 // definition we'll get at link time is *exactly* the definition we see now.
635 // For more details, see GlobalValue::mayBeDerefined.
636 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000637 continue;
638
Sanjay Patel4f742162017-02-13 23:10:51 +0000639 Changed |= addArgumentAttrsFromCallsites(*F);
640
Nick Lewycky4c378a42011-12-28 23:24:21 +0000641 // Functions that are readonly (or readnone) and nounwind and don't return
642 // a value can't capture arguments. Don't analyze them.
643 if (F->onlyReadsMemory() && F->doesNotThrow() &&
644 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000645 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
646 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000647 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000648 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000649 ++NumNoCapture;
650 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000651 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000652 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000653 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000654 }
655
Chandler Carruth63559d72015-09-13 06:47:20 +0000656 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
657 ++A) {
658 if (!A->getType()->isPointerTy())
659 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000660 bool HasNonLocalUses = false;
661 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000662 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000663 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000664 if (!Tracker.Captured) {
665 if (Tracker.Uses.empty()) {
666 // If it's trivially not captured, mark it nocapture now.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000667 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000668 ++NumNoCapture;
669 Changed = true;
670 } else {
671 // If it's not trivially captured and not trivially not captured,
672 // then it must be calling into another function in our SCC. Save
673 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000674 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000675 for (Argument *Use : Tracker.Uses) {
676 Node->Uses.push_back(AG[Use]);
677 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000678 HasNonLocalUses = true;
679 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000680 }
681 }
682 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
683 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000684 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
685 // Can we determine that it's readonly/readnone without doing an SCC?
686 // Note that we don't allow any calls at all here, or else our result
687 // will be dependent on the iteration order through the functions in the
688 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000689 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000690 Self.insert(&*A);
691 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000692 if (R != Attribute::None) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000693 A->addAttr(R);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000694 Changed = true;
695 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
696 }
697 }
698 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000699 }
700
701 // The graph we've collected is partial because we stopped scanning for
702 // argument uses once we solved the argument trivially. These partial nodes
703 // show up as ArgumentGraphNode objects with an empty Uses list, and for
704 // these nodes the final decision about whether they capture has already been
705 // made. If the definition doesn't have a 'nocapture' attribute by now, it
706 // captures.
707
Chandler Carruth63559d72015-09-13 06:47:20 +0000708 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000709 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000710 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000711 if (!ArgumentSCC[0]->Definition)
712 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000713
714 // eg. "void f(int* x) { if (...) f(x); }"
715 if (ArgumentSCC[0]->Uses.size() == 1 &&
716 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000717 Argument *A = ArgumentSCC[0]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000718 A->addAttr(Attribute::NoCapture);
Nick Lewycky7e820552009-01-02 03:46:56 +0000719 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000720 Changed = true;
721 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000722 continue;
723 }
724
725 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000726 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
727 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000728 ArgumentGraphNode *Node = *I;
729 if (Node->Uses.empty()) {
730 if (!Node->Definition->hasNoCaptureAttr())
731 SCCCaptured = true;
732 }
733 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000734 if (SCCCaptured)
735 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000736
Chandler Carruth63559d72015-09-13 06:47:20 +0000737 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000738 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
739 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000740 for (ArgumentGraphNode *I : ArgumentSCC) {
741 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000742 }
743
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000744 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
745 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000746 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000747 for (ArgumentGraphNode *Use : N->Uses) {
748 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000749 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
750 continue;
751 SCCCaptured = true;
752 break;
753 }
754 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000755 if (SCCCaptured)
756 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000757
Nick Lewyckyf740db32012-01-05 22:21:45 +0000758 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000759 Argument *A = ArgumentSCC[i]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000760 A->addAttr(Attribute::NoCapture);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000761 ++NumNoCapture;
762 Changed = true;
763 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000764
765 // We also want to compute readonly/readnone. With a small number of false
766 // negatives, we can assume that any pointer which is captured isn't going
767 // to be provably readonly or readnone, since by definition we can't
768 // analyze all uses of a captured pointer.
769 //
770 // The false negatives happen when the pointer is captured by a function
771 // that promises readonly/readnone behaviour on the pointer, then the
772 // pointer's lifetime ends before anything that writes to arbitrary memory.
773 // Also, a readonly/readnone pointer may be returned, but returning a
774 // pointer is capturing it.
775
776 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
777 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
778 Argument *A = ArgumentSCC[i]->Definition;
779 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
780 if (K == Attribute::ReadNone)
781 continue;
782 if (K == Attribute::ReadOnly) {
783 ReadAttr = Attribute::ReadOnly;
784 continue;
785 }
786 ReadAttr = K;
787 break;
788 }
789
790 if (ReadAttr != Attribute::None) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000791 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
792 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000793 // Clear out existing readonly/readnone attributes
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000794 A->removeAttr(Attribute::ReadOnly);
795 A->removeAttr(Attribute::ReadNone);
796 A->addAttr(ReadAttr);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000797 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
798 Changed = true;
799 }
800 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000801 }
802
803 return Changed;
804}
805
Chandler Carrutha632fb92015-09-13 06:57:25 +0000806/// Tests whether a function is "malloc-like".
807///
808/// A function is "malloc-like" if it returns either null or a pointer that
809/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000810static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000811 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000812 for (BasicBlock &BB : *F)
813 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000814 FlowsToReturn.insert(Ret->getReturnValue());
815
816 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000817 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000818
819 if (Constant *C = dyn_cast<Constant>(RetVal)) {
820 if (!C->isNullValue() && !isa<UndefValue>(C))
821 return false;
822
823 continue;
824 }
825
826 if (isa<Argument>(RetVal))
827 return false;
828
829 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
830 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000831 // Extend the analysis by looking upwards.
832 case Instruction::BitCast:
833 case Instruction::GetElementPtr:
834 case Instruction::AddrSpaceCast:
835 FlowsToReturn.insert(RVI->getOperand(0));
836 continue;
837 case Instruction::Select: {
838 SelectInst *SI = cast<SelectInst>(RVI);
839 FlowsToReturn.insert(SI->getTrueValue());
840 FlowsToReturn.insert(SI->getFalseValue());
841 continue;
842 }
843 case Instruction::PHI: {
844 PHINode *PN = cast<PHINode>(RVI);
845 for (Value *IncValue : PN->incoming_values())
846 FlowsToReturn.insert(IncValue);
847 continue;
848 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000849
Chandler Carruth63559d72015-09-13 06:47:20 +0000850 // Check whether the pointer came from an allocation.
851 case Instruction::Alloca:
852 break;
853 case Instruction::Call:
854 case Instruction::Invoke: {
855 CallSite CS(RVI);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000856 if (CS.hasRetAttr(Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000857 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000858 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
859 break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000860 LLVM_FALLTHROUGH;
861 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000862 default:
863 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000864 }
865
Dan Gohman94e61762009-11-19 21:57:48 +0000866 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000867 return false;
868 }
869
870 return true;
871}
872
Chandler Carrutha632fb92015-09-13 06:57:25 +0000873/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000874static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000875 // Check each function in turn, determining which functions return noalias
876 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000877 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000878 // Already noalias.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000879 if (F->returnDoesNotAlias())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000880 continue;
881
Sanjoy Das5ce32722016-04-08 00:48:30 +0000882 // We can infer and propagate function attributes only when we know that the
883 // definition we'll get at link time is *exactly* the definition we see now.
884 // For more details, see GlobalValue::mayBeDerefined.
885 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000886 return false;
887
Chandler Carruth63559d72015-09-13 06:47:20 +0000888 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000889 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000890 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000891 continue;
892
Chandler Carruth3824f852015-09-13 08:23:27 +0000893 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000894 return false;
895 }
896
897 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000898 for (Function *F : SCCNodes) {
Reid Klecknera0b45f42017-05-03 18:17:31 +0000899 if (F->returnDoesNotAlias() ||
Reid Kleckner6652a522017-04-28 18:37:16 +0000900 !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000901 continue;
902
Reid Klecknera0b45f42017-05-03 18:17:31 +0000903 F->setReturnDoesNotAlias();
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000904 ++NumNoAlias;
905 MadeChange = true;
906 }
907
908 return MadeChange;
909}
910
Chandler Carrutha632fb92015-09-13 06:57:25 +0000911/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000912///
913/// Requires that the function returns a pointer.
914///
915/// Returns true if it believes the function will not return a null, and sets
916/// \p Speculative based on whether the returned conclusion is a speculative
917/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000918static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000919 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000920 assert(F->getReturnType()->isPointerTy() &&
921 "nonnull only meaningful on pointer types");
922 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000923
Philip Reamesa88caea2015-08-31 19:44:38 +0000924 SmallSetVector<Value *, 8> FlowsToReturn;
925 for (BasicBlock &BB : *F)
926 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
927 FlowsToReturn.insert(Ret->getReturnValue());
928
Nuno Lopes404f1062017-09-09 18:23:11 +0000929 auto &DL = F->getParent()->getDataLayout();
930
Philip Reamesa88caea2015-08-31 19:44:38 +0000931 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
932 Value *RetVal = FlowsToReturn[i];
933
934 // If this value is locally known to be non-null, we're good
Nuno Lopes404f1062017-09-09 18:23:11 +0000935 if (isKnownNonZero(RetVal, DL))
Philip Reamesa88caea2015-08-31 19:44:38 +0000936 continue;
937
938 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000939 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000940 Instruction *RVI = dyn_cast<Instruction>(RetVal);
941 if (!RVI)
942 return false;
943 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000944 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000945 case Instruction::BitCast:
946 case Instruction::GetElementPtr:
947 case Instruction::AddrSpaceCast:
948 FlowsToReturn.insert(RVI->getOperand(0));
949 continue;
950 case Instruction::Select: {
951 SelectInst *SI = cast<SelectInst>(RVI);
952 FlowsToReturn.insert(SI->getTrueValue());
953 FlowsToReturn.insert(SI->getFalseValue());
954 continue;
955 }
956 case Instruction::PHI: {
957 PHINode *PN = cast<PHINode>(RVI);
958 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
959 FlowsToReturn.insert(PN->getIncomingValue(i));
960 continue;
961 }
962 case Instruction::Call:
963 case Instruction::Invoke: {
964 CallSite CS(RVI);
965 Function *Callee = CS.getCalledFunction();
966 // A call to a node within the SCC is assumed to return null until
967 // proven otherwise
968 if (Callee && SCCNodes.count(Callee)) {
969 Speculative = true;
970 continue;
971 }
972 return false;
973 }
974 default:
Chandler Carruth63559d72015-09-13 06:47:20 +0000975 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +0000976 };
977 llvm_unreachable("should have either continued or returned");
978 }
979
980 return true;
981}
982
Chandler Carrutha632fb92015-09-13 06:57:25 +0000983/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +0000984static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000985 // Speculative that all functions in the SCC return only nonnull
986 // pointers. We may refute this as we analyze functions.
987 bool SCCReturnsNonNull = true;
988
989 bool MadeChange = false;
990
991 // Check each function in turn, determining which functions return nonnull
992 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000993 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000994 // Already nonnull.
Reid Klecknerb5180542017-03-21 16:57:19 +0000995 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +0000996 Attribute::NonNull))
997 continue;
998
Sanjoy Das5ce32722016-04-08 00:48:30 +0000999 // We can infer and propagate function attributes only when we know that the
1000 // definition we'll get at link time is *exactly* the definition we see now.
1001 // For more details, see GlobalValue::mayBeDerefined.
1002 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +00001003 return false;
1004
Chandler Carruth63559d72015-09-13 06:47:20 +00001005 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +00001006 // pointer types.
1007 if (!F->getReturnType()->isPointerTy())
1008 continue;
1009
1010 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +00001011 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001012 if (!Speculative) {
1013 // Mark the function eagerly since we may discover a function
1014 // which prevents us from speculating about the entire SCC
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001015 LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1016 << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001017 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001018 ++NumNonNullReturn;
1019 MadeChange = true;
1020 }
1021 continue;
1022 }
1023 // At least one function returns something which could be null, can't
1024 // speculate any more.
1025 SCCReturnsNonNull = false;
1026 }
1027
1028 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001029 for (Function *F : SCCNodes) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001030 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001031 Attribute::NonNull) ||
1032 !F->getReturnType()->isPointerTy())
1033 continue;
1034
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001035 LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001036 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001037 ++NumNonNullReturn;
1038 MadeChange = true;
1039 }
1040 }
1041
1042 return MadeChange;
1043}
1044
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001045namespace {
1046
1047/// Collects a set of attribute inference requests and performs them all in one
1048/// go on a single SCC Node. Inference involves scanning function bodies
1049/// looking for instructions that violate attribute assumptions.
1050/// As soon as all the bodies are fine we are free to set the attribute.
1051/// Customization of inference for individual attributes is performed by
1052/// providing a handful of predicates for each attribute.
1053class AttributeInferer {
1054public:
1055 /// Describes a request for inference of a single attribute.
1056 struct InferenceDescriptor {
1057
1058 /// Returns true if this function does not have to be handled.
1059 /// General intent for this predicate is to provide an optimization
1060 /// for functions that do not need this attribute inference at all
1061 /// (say, for functions that already have the attribute).
1062 std::function<bool(const Function &)> SkipFunction;
1063
1064 /// Returns true if this instruction violates attribute assumptions.
1065 std::function<bool(Instruction &)> InstrBreaksAttribute;
1066
1067 /// Sets the inferred attribute for this function.
1068 std::function<void(Function &)> SetAttribute;
1069
1070 /// Attribute we derive.
1071 Attribute::AttrKind AKind;
1072
1073 /// If true, only "exact" definitions can be used to infer this attribute.
1074 /// See GlobalValue::isDefinitionExact.
1075 bool RequiresExactDefinition;
1076
1077 InferenceDescriptor(Attribute::AttrKind AK,
1078 std::function<bool(const Function &)> SkipFunc,
1079 std::function<bool(Instruction &)> InstrScan,
1080 std::function<void(Function &)> SetAttr,
1081 bool ReqExactDef)
1082 : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1083 SetAttribute(SetAttr), AKind(AK),
1084 RequiresExactDefinition(ReqExactDef) {}
1085 };
1086
1087private:
1088 SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1089
1090public:
1091 void registerAttrInference(InferenceDescriptor AttrInference) {
1092 InferenceDescriptors.push_back(AttrInference);
1093 }
1094
1095 bool run(const SCCNodeSet &SCCNodes);
1096};
1097
1098/// Perform all the requested attribute inference actions according to the
1099/// attribute predicates stored before.
1100bool AttributeInferer::run(const SCCNodeSet &SCCNodes) {
1101 SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1102 // Go through all the functions in SCC and check corresponding attribute
1103 // assumptions for each of them. Attributes that are invalid for this SCC
1104 // will be removed from InferInSCC.
Chandler Carruth3937bc72016-02-12 09:47:49 +00001105 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001106
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001107 // No attributes whose assumptions are still valid - done.
1108 if (InferInSCC.empty())
1109 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001110
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001111 // Check if our attributes ever need scanning/can be scanned.
1112 llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1113 if (ID.SkipFunction(*F))
Justin Lebar9d943972016-03-14 20:18:54 +00001114 return false;
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001115
1116 // Remove from further inference (invalidate) when visiting a function
1117 // that has no instructions to scan/has an unsuitable definition.
1118 return F->isDeclaration() ||
1119 (ID.RequiresExactDefinition && !F->hasExactDefinition());
1120 });
1121
1122 // For each attribute still in InferInSCC that doesn't explicitly skip F,
1123 // set up the F instructions scan to verify assumptions of the attribute.
1124 SmallVector<InferenceDescriptor, 4> InferInThisFunc;
1125 llvm::copy_if(
1126 InferInSCC, std::back_inserter(InferInThisFunc),
1127 [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1128
1129 if (InferInThisFunc.empty())
1130 continue;
1131
1132 // Start instruction scan.
1133 for (Instruction &I : instructions(*F)) {
1134 llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1135 if (!ID.InstrBreaksAttribute(I))
1136 return false;
1137 // Remove attribute from further inference on any other functions
1138 // because attribute assumptions have just been violated.
1139 llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1140 return D.AKind == ID.AKind;
1141 });
1142 // Remove attribute from the rest of current instruction scan.
1143 return true;
1144 });
1145
1146 if (InferInThisFunc.empty())
1147 break;
Justin Lebar9d943972016-03-14 20:18:54 +00001148 }
1149 }
1150
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001151 if (InferInSCC.empty())
1152 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001153
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001154 bool Changed = false;
1155 for (Function *F : SCCNodes)
1156 // At this point InferInSCC contains only functions that were either:
1157 // - explicitly skipped from scan/inference, or
1158 // - verified to have no instructions that break attribute assumptions.
1159 // Hence we just go and force the attribute for all non-skipped functions.
1160 for (auto &ID : InferInSCC) {
1161 if (ID.SkipFunction(*F))
1162 continue;
1163 Changed = true;
1164 ID.SetAttribute(*F);
1165 }
1166 return Changed;
1167}
Justin Lebar9d943972016-03-14 20:18:54 +00001168
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001169} // end anonymous namespace
1170
1171/// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1172static bool InstrBreaksNonConvergent(Instruction &I,
1173 const SCCNodeSet &SCCNodes) {
1174 const CallSite CS(&I);
1175 // Breaks non-convergent assumption if CS is a convergent call to a function
1176 // not in the SCC.
1177 return CS && CS.isConvergent() && SCCNodes.count(CS.getCalledFunction()) == 0;
1178}
1179
1180/// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1181static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1182 if (!I.mayThrow())
1183 return false;
1184 if (const auto *CI = dyn_cast<CallInst>(&I)) {
1185 if (Function *Callee = CI->getCalledFunction()) {
1186 // I is a may-throw call to a function inside our SCC. This doesn't
1187 // invalidate our current working assumption that the SCC is no-throw; we
1188 // just have to scan that other function.
1189 if (SCCNodes.count(Callee) > 0)
1190 return false;
1191 }
Chandler Carruth3937bc72016-02-12 09:47:49 +00001192 }
Justin Lebar260854b2016-02-09 23:03:22 +00001193 return true;
1194}
1195
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001196/// Infer attributes from all functions in the SCC by scanning every
1197/// instruction for compliance to the attribute assumptions. Currently it
1198/// does:
1199/// - removal of Convergent attribute
1200/// - addition of NoUnwind attribute
1201///
1202/// Returns true if any changes to function attributes were made.
1203static bool inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes) {
1204
1205 AttributeInferer AI;
1206
1207 // Request to remove the convergent attribute from all functions in the SCC
1208 // if every callsite within the SCC is not convergent (except for calls
1209 // to functions within the SCC).
1210 // Note: Removal of the attr from the callsites will happen in
1211 // InstCombineCalls separately.
1212 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1213 Attribute::Convergent,
1214 // Skip non-convergent functions.
1215 [](const Function &F) { return !F.isConvergent(); },
1216 // Instructions that break non-convergent assumption.
1217 [SCCNodes](Instruction &I) {
1218 return InstrBreaksNonConvergent(I, SCCNodes);
1219 },
1220 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001221 LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1222 << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001223 F.setNotConvergent();
1224 },
1225 /* RequiresExactDefinition= */ false});
1226
1227 if (!DisableNoUnwindInference)
1228 // Request to infer nounwind attribute for all the functions in the SCC if
1229 // every callsite within the SCC is not throwing (except for calls to
1230 // functions within the SCC). Note that nounwind attribute suffers from
1231 // derefinement - results may change depending on how functions are
1232 // optimized. Thus it can be inferred only from exact definitions.
1233 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1234 Attribute::NoUnwind,
1235 // Skip non-throwing functions.
1236 [](const Function &F) { return F.doesNotThrow(); },
1237 // Instructions that break non-throwing assumption.
1238 [SCCNodes](Instruction &I) {
1239 return InstrBreaksNonThrowing(I, SCCNodes);
1240 },
1241 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001242 LLVM_DEBUG(dbgs()
1243 << "Adding nounwind attr to fn " << F.getName() << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001244 F.setDoesNotThrow();
1245 ++NumNoUnwind;
1246 },
1247 /* RequiresExactDefinition= */ true});
1248
1249 // Perform all the requested attribute inference actions.
1250 return AI.run(SCCNodes);
1251}
1252
James Molloy7e9bdd52015-11-12 10:55:20 +00001253static bool setDoesNotRecurse(Function &F) {
1254 if (F.doesNotRecurse())
1255 return false;
1256 F.setDoesNotRecurse();
1257 ++NumNoRecurse;
1258 return true;
1259}
1260
Chandler Carruth632d2082016-02-13 08:47:51 +00001261static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +00001262 // Try and identify functions that do not recurse.
1263
1264 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +00001265 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +00001266 return false;
1267
Chandler Carruth632d2082016-02-13 08:47:51 +00001268 Function *F = *SCCNodes.begin();
James Molloy7e9bdd52015-11-12 10:55:20 +00001269 if (!F || F->isDeclaration() || F->doesNotRecurse())
1270 return false;
1271
1272 // If all of the calls in F are identifiable and are to norecurse functions, F
1273 // is norecurse. This check also detects self-recursion as F is not currently
1274 // marked norecurse, so any called from F to F will not be marked norecurse.
Chandler Carruth632d2082016-02-13 08:47:51 +00001275 for (Instruction &I : instructions(*F))
1276 if (auto CS = CallSite(&I)) {
1277 Function *Callee = CS.getCalledFunction();
1278 if (!Callee || Callee == F || !Callee->doesNotRecurse())
1279 // Function calls a potentially recursive function.
1280 return false;
1281 }
James Molloy7e9bdd52015-11-12 10:55:20 +00001282
Chandler Carruth632d2082016-02-13 08:47:51 +00001283 // Every call was to a non-recursive function other than this function, and
1284 // we have no indirect recursion as the SCC size is one. This function cannot
1285 // recurse.
1286 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +00001287}
1288
Chandler Carruthb47f8012016-03-11 11:05:24 +00001289PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
Chandler Carruth88823462016-08-24 09:37:14 +00001290 CGSCCAnalysisManager &AM,
1291 LazyCallGraph &CG,
1292 CGSCCUpdateResult &) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001293 FunctionAnalysisManager &FAM =
Chandler Carruth88823462016-08-24 09:37:14 +00001294 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001295
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001296 // We pass a lambda into functions to wire them up to the analysis manager
1297 // for getting function analyses.
1298 auto AARGetter = [&](Function &F) -> AAResults & {
1299 return FAM.getResult<AAManager>(F);
1300 };
1301
1302 // Fill SCCNodes with the elements of the SCC. Also track whether there are
1303 // any external or opt-none nodes that will prevent us from optimizing any
1304 // part of the SCC.
1305 SCCNodeSet SCCNodes;
1306 bool HasUnknownCall = false;
1307 for (LazyCallGraph::Node &N : C) {
1308 Function &F = N.getFunction();
Luke Cheeseman6c1e6bb2018-02-22 14:42:08 +00001309 if (F.hasFnAttribute(Attribute::OptimizeNone) ||
1310 F.hasFnAttribute(Attribute::Naked)) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001311 // Treat any function we're trying not to optimize as if it were an
1312 // indirect call and omit it from the node set used below.
1313 HasUnknownCall = true;
1314 continue;
1315 }
1316 // Track whether any functions in this SCC have an unknown call edge.
1317 // Note: if this is ever a performance hit, we can common it with
1318 // subsequent routines which also do scans over the instructions of the
1319 // function.
1320 if (!HasUnknownCall)
1321 for (Instruction &I : instructions(F))
1322 if (auto CS = CallSite(&I))
1323 if (!CS.getCalledFunction()) {
1324 HasUnknownCall = true;
1325 break;
1326 }
1327
1328 SCCNodes.insert(&F);
1329 }
1330
1331 bool Changed = false;
David Majnemer5246e0b2016-07-19 18:50:26 +00001332 Changed |= addArgumentReturnedAttrs(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001333 Changed |= addReadAttrs(SCCNodes, AARGetter);
1334 Changed |= addArgumentAttrs(SCCNodes);
1335
1336 // If we have no external nodes participating in the SCC, we can deduce some
1337 // more precise attributes as well.
1338 if (!HasUnknownCall) {
1339 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001340 Changed |= addNonNullAttrs(SCCNodes);
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001341 Changed |= inferAttrsFromFunctionBodies(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001342 Changed |= addNoRecurseAttrs(SCCNodes);
1343 }
1344
1345 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1346}
1347
1348namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001349
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001350struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001351 // Pass identification, replacement for typeid
1352 static char ID;
1353
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001354 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001355 initializePostOrderFunctionAttrsLegacyPassPass(
1356 *PassRegistry::getPassRegistry());
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001357 }
1358
1359 bool runOnSCC(CallGraphSCC &SCC) override;
1360
1361 void getAnalysisUsage(AnalysisUsage &AU) const override {
1362 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001363 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001364 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001365 CallGraphSCCPass::getAnalysisUsage(AU);
1366 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001367};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001368
1369} // end anonymous namespace
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001370
1371char PostOrderFunctionAttrsLegacyPass::ID = 0;
1372INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1373 "Deduce function attributes", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001374INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001375INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001376INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1377 "Deduce function attributes", false, false)
1378
Chad Rosier611b73b2016-11-07 16:28:04 +00001379Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1380 return new PostOrderFunctionAttrsLegacyPass();
1381}
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001382
Sean Silva997cbea2016-07-03 03:35:03 +00001383template <typename AARGetterT>
1384static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
Chandler Carruthcada2d82015-10-31 00:28:37 +00001385 bool Changed = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001386
1387 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1388 // whether a given CallGraphNode is in this SCC. Also track whether there are
1389 // any external or opt-none nodes that will prevent us from optimizing any
1390 // part of the SCC.
1391 SCCNodeSet SCCNodes;
1392 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001393 for (CallGraphNode *I : SCC) {
1394 Function *F = I->getFunction();
Luke Cheeseman6c1e6bb2018-02-22 14:42:08 +00001395 if (!F || F->hasFnAttribute(Attribute::OptimizeNone) ||
1396 F->hasFnAttribute(Attribute::Naked)) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001397 // External node or function we're trying not to optimize - we both avoid
1398 // transform them and avoid leveraging information they provide.
1399 ExternalNode = true;
1400 continue;
1401 }
1402
1403 SCCNodes.insert(F);
1404 }
1405
David Blaikie6aeacaa2017-06-02 21:24:17 +00001406 // Skip it if the SCC only contains optnone functions.
1407 if (SCCNodes.empty())
1408 return Changed;
1409
David Majnemer5246e0b2016-07-19 18:50:26 +00001410 Changed |= addArgumentReturnedAttrs(SCCNodes);
Chandler Carrutha8125352015-10-30 16:48:08 +00001411 Changed |= addReadAttrs(SCCNodes, AARGetter);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001412 Changed |= addArgumentAttrs(SCCNodes);
1413
Chandler Carruth3a040e62015-12-27 08:41:34 +00001414 // If we have no external nodes participating in the SCC, we can deduce some
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001415 // more precise attributes as well.
1416 if (!ExternalNode) {
1417 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001418 Changed |= addNonNullAttrs(SCCNodes);
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001419 Changed |= inferAttrsFromFunctionBodies(SCCNodes);
Chandler Carruth632d2082016-02-13 08:47:51 +00001420 Changed |= addNoRecurseAttrs(SCCNodes);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001421 }
Chandler Carruth1926b702016-01-08 10:55:52 +00001422
James Molloy7e9bdd52015-11-12 10:55:20 +00001423 return Changed;
1424}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001425
Sean Silva997cbea2016-07-03 03:35:03 +00001426bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1427 if (skipSCC(SCC))
1428 return false;
Peter Collingbournecea1e4e2017-02-09 23:11:52 +00001429 return runImpl(SCC, LegacyAARGetter(*this));
Sean Silva997cbea2016-07-03 03:35:03 +00001430}
1431
Chandler Carruth1926b702016-01-08 10:55:52 +00001432namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001433
Sean Silvaf5080192016-06-12 07:48:51 +00001434struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001435 // Pass identification, replacement for typeid
1436 static char ID;
1437
Sean Silvaf5080192016-06-12 07:48:51 +00001438 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001439 initializeReversePostOrderFunctionAttrsLegacyPassPass(
1440 *PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001441 }
1442
1443 bool runOnModule(Module &M) override;
1444
1445 void getAnalysisUsage(AnalysisUsage &AU) const override {
1446 AU.setPreservesCFG();
1447 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001448 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001449 }
1450};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001451
1452} // end anonymous namespace
Chandler Carruth1926b702016-01-08 10:55:52 +00001453
Sean Silvaf5080192016-06-12 07:48:51 +00001454char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001455
Sean Silvaf5080192016-06-12 07:48:51 +00001456INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001457 "Deduce function attributes in RPO", false, false)
1458INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001459INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001460 "Deduce function attributes in RPO", false, false)
1461
1462Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001463 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001464}
1465
1466static bool addNoRecurseAttrsTopDown(Function &F) {
1467 // We check the preconditions for the function prior to calling this to avoid
1468 // the cost of building up a reversible post-order list. We assert them here
1469 // to make sure none of the invariants this relies on were violated.
1470 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1471 assert(!F.doesNotRecurse() &&
1472 "This function has already been deduced as norecurs!");
1473 assert(F.hasInternalLinkage() &&
1474 "Can only do top-down deduction for internal linkage functions!");
1475
1476 // If F is internal and all of its uses are calls from a non-recursive
1477 // functions, then none of its calls could in fact recurse without going
1478 // through a function marked norecurse, and so we can mark this function too
1479 // as norecurse. Note that the uses must actually be calls -- otherwise
1480 // a pointer to this function could be returned from a norecurse function but
1481 // this function could be recursively (indirectly) called. Note that this
1482 // also detects if F is directly recursive as F is not yet marked as
1483 // a norecurse function.
1484 for (auto *U : F.users()) {
1485 auto *I = dyn_cast<Instruction>(U);
1486 if (!I)
1487 return false;
1488 CallSite CS(I);
1489 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1490 return false;
1491 }
1492 return setDoesNotRecurse(F);
1493}
1494
Sean Silvaadc79392016-06-12 05:44:51 +00001495static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001496 // We only have a post-order SCC traversal (because SCCs are inherently
1497 // discovered in post-order), so we accumulate them in a vector and then walk
1498 // it in reverse. This is simpler than using the RPO iterator infrastructure
1499 // because we need to combine SCC detection and the PO walk of the call
1500 // graph. We can also cheat egregiously because we're primarily interested in
1501 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1502 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001503 SmallVector<Function *, 16> Worklist;
1504 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1505 if (I->size() != 1)
1506 continue;
1507
1508 Function *F = I->front()->getFunction();
1509 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1510 F->hasInternalLinkage())
1511 Worklist.push_back(F);
1512 }
1513
James Molloy7e9bdd52015-11-12 10:55:20 +00001514 bool Changed = false;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001515 for (auto *F : llvm::reverse(Worklist))
Chandler Carruth1926b702016-01-08 10:55:52 +00001516 Changed |= addNoRecurseAttrsTopDown(*F);
1517
Duncan Sands44c8cd92008-12-31 16:14:43 +00001518 return Changed;
1519}
Sean Silvaadc79392016-06-12 05:44:51 +00001520
Sean Silvaf5080192016-06-12 07:48:51 +00001521bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001522 if (skipModule(M))
1523 return false;
1524
1525 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1526
1527 return deduceFunctionAttributeInRPO(M, CG);
1528}
Sean Silvaf5080192016-06-12 07:48:51 +00001529
1530PreservedAnalyses
Sean Silvafd03ac62016-08-09 00:28:38 +00001531ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
Sean Silvaf5080192016-06-12 07:48:51 +00001532 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1533
Chandler Carruth6acdca72017-01-24 12:55:57 +00001534 if (!deduceFunctionAttributeInRPO(M, CG))
Sean Silvaf5080192016-06-12 07:48:51 +00001535 return PreservedAnalyses::all();
Chandler Carruth6acdca72017-01-24 12:55:57 +00001536
Sean Silvaf5080192016-06-12 07:48:51 +00001537 PreservedAnalyses PA;
1538 PA.preserve<CallGraphAnalysis>();
1539 return PA;
1540}