blob: 4e2a82b56eec6481f6519c315a29939a8ddcd4a3 [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"
Christian Bruel4ead99b2018-12-05 16:48:00 +000044#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000045#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");
Brian Homerding3ecabd72018-08-23 15:05:22 +000070STATISTIC(NumWriteOnly, "Number of functions marked writeonly");
Duncan Sands44c8cd92008-12-31 16:14:43 +000071STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
David Majnemer5246e0b2016-07-19 18:50:26 +000072STATISTIC(NumReturned, "Number of arguments marked returned");
Nick Lewyckyc2ec0722013-07-06 00:29:58 +000073STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
74STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
Nick Lewyckyfbed86a2009-03-08 06:20:47 +000075STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Philip Reamesa88caea2015-08-31 19:44:38 +000076STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
James Molloy7e9bdd52015-11-12 10:55:20 +000077STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
Fedor Sergeev6660fd02018-03-23 21:46:16 +000078STATISTIC(NumNoUnwind, "Number of functions marked as nounwind");
Duncan Sands44c8cd92008-12-31 16:14:43 +000079
Sanjay Patel4f742162017-02-13 23:10:51 +000080// FIXME: This is disabled by default to avoid exposing security vulnerabilities
81// in C/C++ code compiled by clang:
82// http://lists.llvm.org/pipermail/cfe-dev/2017-January/052066.html
83static cl::opt<bool> EnableNonnullArgPropagation(
84 "enable-nonnull-arg-prop", cl::Hidden,
85 cl::desc("Try to propagate nonnull argument attributes from callsites to "
86 "caller functions."));
87
Fedor Sergeev6660fd02018-03-23 21:46:16 +000088static cl::opt<bool> DisableNoUnwindInference(
89 "disable-nounwind-inference", cl::Hidden,
90 cl::desc("Stop inferring nounwind attribute during function-attrs pass"));
91
Duncan Sands44c8cd92008-12-31 16:14:43 +000092namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +000093
94using SCCNodeSet = SmallSetVector<Function *, 8>;
95
96} // end anonymous namespace
Chandler Carruthc518ebd2015-10-29 18:29:15 +000097
Peter Collingbournec45f7f32017-02-14 00:28:13 +000098/// Returns the memory access attribute for function F using AAR for AA results,
99/// where SCCNodes is the current SCC.
100///
101/// If ThisBody is true, this function may examine the function body and will
102/// return a result pertaining to this copy of the function. If it is false, the
103/// result will be based only on AA results for the function declaration; it
104/// will be assumed that some other (perhaps less optimized) version of the
105/// function may be selected at link time.
106static MemoryAccessKind checkFunctionMemoryAccess(Function &F, bool ThisBody,
107 AAResults &AAR,
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000108 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000109 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
110 if (MRB == FMRB_DoesNotAccessMemory)
111 // Already perfect!
112 return MAK_ReadNone;
113
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000114 if (!ThisBody) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000115 if (AliasAnalysis::onlyReadsMemory(MRB))
116 return MAK_ReadOnly;
117
Brian Homerding3ecabd72018-08-23 15:05:22 +0000118 if (AliasAnalysis::doesNotReadMemory(MRB))
119 return MAK_WriteOnly;
120
121 // Conservatively assume it reads and writes to memory.
Chandler Carruth7542d372015-09-21 17:39:41 +0000122 return MAK_MayWrite;
123 }
124
125 // Scan the function body for instructions that may read or write memory.
126 bool ReadsMemory = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000127 bool WritesMemory = false;
Chandler Carruth7542d372015-09-21 17:39:41 +0000128 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
129 Instruction *I = &*II;
130
131 // Some instructions can be ignored even if they read or write memory.
132 // Detect these now, skipping to the next instruction if one is found.
Chandler Carruth363ac682019-01-07 05:42:51 +0000133 if (auto *Call = dyn_cast<CallBase>(I)) {
Sanjoy Das10c8a042016-02-09 18:40:40 +0000134 // Ignore calls to functions in the same SCC, as long as the call sites
135 // don't have operand bundles. Calls with operand bundles are allowed to
136 // have memory effects not described by the memory effects of the call
137 // target.
Chandler Carruth363ac682019-01-07 05:42:51 +0000138 if (!Call->hasOperandBundles() && Call->getCalledFunction() &&
139 SCCNodes.count(Call->getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +0000140 continue;
Chandler Carruth363ac682019-01-07 05:42:51 +0000141 FunctionModRefBehavior MRB = AAR.getModRefBehavior(Call);
Alina Sbirlea63d22502017-12-05 20:12:23 +0000142 ModRefInfo MRI = createModRefInfo(MRB);
Chandler Carruth7542d372015-09-21 17:39:41 +0000143
Chandler Carruth69798fb2015-10-27 01:41:43 +0000144 // If the call doesn't access memory, we're done.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000145 if (isNoModRef(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000146 continue;
147
148 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
Brian Homerding3ecabd72018-08-23 15:05:22 +0000149 // The call could access any memory. If that includes writes, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000150 if (isModSet(MRI))
Brian Homerding3ecabd72018-08-23 15:05:22 +0000151 WritesMemory = true;
Chandler Carruth69798fb2015-10-27 01:41:43 +0000152 // If it reads, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000153 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000154 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000155 continue;
156 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000157
158 // Check whether all pointer arguments point to local memory, and
159 // ignore calls that only access local memory.
Chandler Carruth363ac682019-01-07 05:42:51 +0000160 for (CallSite::arg_iterator CI = Call->arg_begin(), CE = Call->arg_end();
Chandler Carruth69798fb2015-10-27 01:41:43 +0000161 CI != CE; ++CI) {
162 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000163 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000164 continue;
165
166 AAMDNodes AAInfo;
167 I->getAAMetadata(AAInfo);
George Burgess IV6ef80022018-10-10 21:28:44 +0000168 MemoryLocation Loc(Arg, LocationSize::unknown(), AAInfo);
Chandler Carruth69798fb2015-10-27 01:41:43 +0000169
170 // Skip accesses to local or constant memory as they don't impact the
171 // externally visible mod/ref behavior.
172 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
173 continue;
174
Alina Sbirlea63d22502017-12-05 20:12:23 +0000175 if (isModSet(MRI))
Brian Homerding3ecabd72018-08-23 15:05:22 +0000176 // Writes non-local memory.
177 WritesMemory = true;
Alina Sbirlea63d22502017-12-05 20:12:23 +0000178 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000179 // Ok, it reads non-local memory.
180 ReadsMemory = true;
181 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000182 continue;
183 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
184 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
185 if (!LI->isVolatile()) {
186 MemoryLocation Loc = MemoryLocation::get(LI);
187 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
188 continue;
189 }
190 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
191 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
192 if (!SI->isVolatile()) {
193 MemoryLocation Loc = MemoryLocation::get(SI);
194 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
195 continue;
196 }
197 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
198 // Ignore vaargs on local memory.
199 MemoryLocation Loc = MemoryLocation::get(VI);
200 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
201 continue;
202 }
203
204 // Any remaining instructions need to be taken seriously! Check if they
205 // read or write memory.
Brian Homerding3ecabd72018-08-23 15:05:22 +0000206 //
207 // Writes memory, remember that.
208 WritesMemory |= I->mayWriteToMemory();
Chandler Carruth7542d372015-09-21 17:39:41 +0000209
210 // If this instruction may read memory, remember that.
211 ReadsMemory |= I->mayReadFromMemory();
212 }
213
Brian Homerding3ecabd72018-08-23 15:05:22 +0000214 if (WritesMemory) {
215 if (!ReadsMemory)
216 return MAK_WriteOnly;
217 else
218 return MAK_MayWrite;
219 }
220
Chandler Carruth7542d372015-09-21 17:39:41 +0000221 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
222}
223
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000224MemoryAccessKind llvm::computeFunctionBodyMemoryAccess(Function &F,
225 AAResults &AAR) {
226 return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {});
227}
228
Chandler Carrutha632fb92015-09-13 06:57:25 +0000229/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000230template <typename AARGetterT>
Peter Collingbournecea1e4e2017-02-09 23:11:52 +0000231static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000232 // Check if any of the functions in the SCC read or write memory. If they
233 // write memory then they can't be marked readnone or readonly.
234 bool ReadsMemory = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000235 bool WritesMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000236 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000237 // Call the callable parameter to look up AA results for this function.
238 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000239
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000240 // Non-exact function definitions may not be selected at link time, and an
241 // alternative version that writes to memory may be selected. See the
242 // comment on GlobalValue::isDefinitionExact for more details.
243 switch (checkFunctionMemoryAccess(*F, F->hasExactDefinition(),
244 AAR, SCCNodes)) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000245 case MAK_MayWrite:
246 return false;
247 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000248 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000249 break;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000250 case MAK_WriteOnly:
251 WritesMemory = true;
252 break;
Chandler Carruth7542d372015-09-21 17:39:41 +0000253 case MAK_ReadNone:
254 // Nothing to do!
255 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000256 }
257 }
258
259 // Success! Functions in this SCC do not access memory, or only read memory.
260 // Give them the appropriate attribute.
261 bool MadeChange = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000262
263 assert(!(ReadsMemory && WritesMemory) &&
264 "Function marked read-only and write-only");
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000265 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000266 if (F->doesNotAccessMemory())
267 // Already perfect!
268 continue;
269
270 if (F->onlyReadsMemory() && ReadsMemory)
271 // No change.
272 continue;
273
Brian Homerding3ecabd72018-08-23 15:05:22 +0000274 if (F->doesNotReadMemory() && WritesMemory)
275 continue;
276
Duncan Sands44c8cd92008-12-31 16:14:43 +0000277 MadeChange = true;
278
279 // Clear out any existing attributes.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000280 F->removeFnAttr(Attribute::ReadOnly);
281 F->removeFnAttr(Attribute::ReadNone);
Brian Homerding3ecabd72018-08-23 15:05:22 +0000282 F->removeFnAttr(Attribute::WriteOnly);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000283
Johannes Doerfertae3cfeb2018-09-11 11:51:29 +0000284 if (!WritesMemory && !ReadsMemory) {
285 // Clear out any "access range attributes" if readnone was deduced.
286 F->removeFnAttr(Attribute::ArgMemOnly);
287 F->removeFnAttr(Attribute::InaccessibleMemOnly);
288 F->removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
289 }
290
Duncan Sands44c8cd92008-12-31 16:14:43 +0000291 // Add in the new attribute.
Brian Homerding3ecabd72018-08-23 15:05:22 +0000292 if (WritesMemory && !ReadsMemory)
293 F->addFnAttr(Attribute::WriteOnly);
294 else
295 F->addFnAttr(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000296
Brian Homerding3ecabd72018-08-23 15:05:22 +0000297 if (WritesMemory && !ReadsMemory)
298 ++NumWriteOnly;
299 else if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000300 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000301 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000302 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000303 }
304
305 return MadeChange;
306}
307
Nick Lewycky4c378a42011-12-28 23:24:21 +0000308namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000309
Chandler Carrutha632fb92015-09-13 06:57:25 +0000310/// For a given pointer Argument, this retains a list of Arguments of functions
311/// in the same SCC that the pointer data flows into. We use this to build an
312/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000313struct ArgumentGraphNode {
314 Argument *Definition;
315 SmallVector<ArgumentGraphNode *, 4> Uses;
316};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000317
Chandler Carruth63559d72015-09-13 06:47:20 +0000318class ArgumentGraph {
319 // We store pointers to ArgumentGraphNode objects, so it's important that
320 // that they not move around upon insert.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000321 using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000322
Chandler Carruth63559d72015-09-13 06:47:20 +0000323 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000324
Chandler Carruth63559d72015-09-13 06:47:20 +0000325 // There is no root node for the argument graph, in fact:
326 // void f(int *x, int *y) { if (...) f(x, y); }
327 // is an example where the graph is disconnected. The SCCIterator requires a
328 // single entry point, so we maintain a fake ("synthetic") root node that
329 // uses every node. Because the graph is directed and nothing points into
330 // the root, it will not participate in any SCCs (except for its own).
331 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000332
Chandler Carruth63559d72015-09-13 06:47:20 +0000333public:
334 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000335
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000336 using iterator = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000337
Chandler Carruth63559d72015-09-13 06:47:20 +0000338 iterator begin() { return SyntheticRoot.Uses.begin(); }
339 iterator end() { return SyntheticRoot.Uses.end(); }
340 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000341
Chandler Carruth63559d72015-09-13 06:47:20 +0000342 ArgumentGraphNode *operator[](Argument *A) {
343 ArgumentGraphNode &Node = ArgumentMap[A];
344 Node.Definition = A;
345 SyntheticRoot.Uses.push_back(&Node);
346 return &Node;
347 }
348};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000349
Chandler Carrutha632fb92015-09-13 06:57:25 +0000350/// This tracker checks whether callees are in the SCC, and if so it does not
351/// consider that a capture, instead adding it to the "Uses" list and
352/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000353struct ArgumentUsesTracker : public CaptureTracker {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000354 ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000355
Chandler Carruth63559d72015-09-13 06:47:20 +0000356 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000357
Chandler Carruth63559d72015-09-13 06:47:20 +0000358 bool captured(const Use *U) override {
359 CallSite CS(U->getUser());
360 if (!CS.getInstruction()) {
361 Captured = true;
362 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000363 }
364
Chandler Carruth63559d72015-09-13 06:47:20 +0000365 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000366 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000367 Captured = true;
368 return true;
369 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000370
Sanjoy Das98bfe262015-11-05 03:04:40 +0000371 // Note: the callee and the two successor blocks *follow* the argument
372 // operands. This means there is no need to adjust UseIndex to account for
373 // these.
374
375 unsigned UseIndex =
376 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
377
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000378 assert(UseIndex < CS.data_operands_size() &&
379 "Indirect function calls should have been filtered above!");
380
381 if (UseIndex >= CS.getNumArgOperands()) {
382 // Data operand, but not a argument operand -- must be a bundle operand
383 assert(CS.hasOperandBundles() && "Must be!");
384
385 // CaptureTracking told us that we're being captured by an operand bundle
386 // use. In this case it does not matter if the callee is within our SCC
387 // or not -- we've been captured in some unknown way, and we have to be
388 // conservative.
389 Captured = true;
390 return true;
391 }
392
Sanjoy Das98bfe262015-11-05 03:04:40 +0000393 if (UseIndex >= F->arg_size()) {
394 assert(F->isVarArg() && "More params than args in non-varargs call");
395 Captured = true;
396 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000397 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000398
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000399 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000400 return false;
401 }
402
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000403 // True only if certainly captured (used outside our SCC).
404 bool Captured = false;
405
406 // Uses within our SCC.
407 SmallVector<Argument *, 4> Uses;
Chandler Carruth63559d72015-09-13 06:47:20 +0000408
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000409 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000410};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000411
412} // end anonymous namespace
Nick Lewycky4c378a42011-12-28 23:24:21 +0000413
414namespace llvm {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000415
Chandler Carruth63559d72015-09-13 06:47:20 +0000416template <> struct GraphTraits<ArgumentGraphNode *> {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000417 using NodeRef = ArgumentGraphNode *;
418 using ChildIteratorType = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000419
Tim Shen48f814e2016-08-31 16:48:13 +0000420 static NodeRef getEntryNode(NodeRef A) { return A; }
421 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
422 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000423};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000424
Chandler Carruth63559d72015-09-13 06:47:20 +0000425template <>
426struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
Tim Shenf2187ed2016-08-22 21:09:30 +0000427 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000428
Chandler Carruth63559d72015-09-13 06:47:20 +0000429 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
430 return AG->begin();
431 }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000432
Chandler Carruth63559d72015-09-13 06:47:20 +0000433 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
434};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000435
436} // end namespace llvm
Nick Lewycky4c378a42011-12-28 23:24:21 +0000437
Chandler Carrutha632fb92015-09-13 06:57:25 +0000438/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000439static Attribute::AttrKind
440determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000441 const SmallPtrSet<Argument *, 8> &SCCNodes) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000442 SmallVector<Use *, 32> Worklist;
Florian Hahna1cc8482018-06-12 11:16:56 +0000443 SmallPtrSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000444
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000445 // inalloca arguments are always clobbered by the call.
446 if (A->hasInAllocaAttr())
447 return Attribute::None;
448
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000449 bool IsRead = false;
450 // We don't need to track IsWritten. If A is written to, return immediately.
451
Chandler Carruthcdf47882014-03-09 03:16:01 +0000452 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000453 Visited.insert(&U);
454 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000455 }
456
457 while (!Worklist.empty()) {
458 Use *U = Worklist.pop_back_val();
459 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000460
461 switch (I->getOpcode()) {
462 case Instruction::BitCast:
463 case Instruction::GetElementPtr:
464 case Instruction::PHI:
465 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000466 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000467 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000468 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000469 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000470 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000471 break;
472
473 case Instruction::Call:
474 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000475 bool Captures = true;
476
477 if (I->getType()->isVoidTy())
478 Captures = false;
479
480 auto AddUsersToWorklistIfCapturing = [&] {
481 if (Captures)
482 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000483 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000484 Worklist.push_back(&UU);
485 };
486
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000487 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000488 if (CS.doesNotAccessMemory()) {
489 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000490 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000491 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000492
493 Function *F = CS.getCalledFunction();
494 if (!F) {
495 if (CS.onlyReadsMemory()) {
496 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000497 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000498 continue;
499 }
500 return Attribute::None;
501 }
502
Sanjoy Das436e2392015-11-07 01:55:53 +0000503 // Note: the callee and the two successor blocks *follow* the argument
504 // operands. This means there is no need to adjust UseIndex to account
505 // for these.
506
507 unsigned UseIndex = std::distance(CS.arg_begin(), U);
508
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000509 // U cannot be the callee operand use: since we're exploring the
510 // transitive uses of an Argument, having such a use be a callee would
511 // imply the CallSite is an indirect call or invoke; and we'd take the
512 // early exit above.
513 assert(UseIndex < CS.data_operands_size() &&
514 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000515
516 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
517
518 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000519 assert(F->isVarArg() && "More params than args in non-varargs call");
520 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000521 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000522
Tilmann Scheller925b1932015-11-20 19:17:10 +0000523 Captures &= !CS.doesNotCapture(UseIndex);
524
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000525 // Since the optimizer (by design) cannot see the data flow corresponding
526 // to a operand bundle use, these cannot participate in the optimistic SCC
527 // analysis. Instead, we model the operand bundle uses as arguments in
528 // call to a function external to the SCC.
Duncan P. N. Exon Smith9e3edad2016-08-17 01:23:58 +0000529 if (IsOperandBundleUse ||
530 !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000531
532 // The accessors used on CallSite here do the right thing for calls and
533 // invokes with operand bundles.
534
Sanjoy Das436e2392015-11-07 01:55:53 +0000535 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
536 return Attribute::None;
537 if (!CS.doesNotAccessMemory(UseIndex))
538 IsRead = true;
539 }
540
Nick Lewycky59633cb2014-05-30 02:31:27 +0000541 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000542 break;
543 }
544
545 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000546 // A volatile load has side effects beyond what readonly can be relied
547 // upon.
548 if (cast<LoadInst>(I)->isVolatile())
549 return Attribute::None;
550
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000551 IsRead = true;
552 break;
553
554 case Instruction::ICmp:
555 case Instruction::Ret:
556 break;
557
558 default:
559 return Attribute::None;
560 }
561 }
562
563 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
564}
565
David Majnemer5246e0b2016-07-19 18:50:26 +0000566/// Deduce returned attributes for the SCC.
567static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
568 bool Changed = false;
569
David Majnemer5246e0b2016-07-19 18:50:26 +0000570 // Check each function in turn, determining if an argument is always returned.
571 for (Function *F : SCCNodes) {
572 // We can infer and propagate function attributes only when we know that the
573 // definition we'll get at link time is *exactly* the definition we see now.
574 // For more details, see GlobalValue::mayBeDerefined.
575 if (!F->hasExactDefinition())
576 continue;
577
578 if (F->getReturnType()->isVoidTy())
579 continue;
580
David Majnemerc83044d2016-09-12 16:04:59 +0000581 // There is nothing to do if an argument is already marked as 'returned'.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000582 if (llvm::any_of(F->args(),
583 [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
David Majnemerc83044d2016-09-12 16:04:59 +0000584 continue;
585
David Majnemer5246e0b2016-07-19 18:50:26 +0000586 auto FindRetArg = [&]() -> Value * {
587 Value *RetArg = nullptr;
588 for (BasicBlock &BB : *F)
589 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
590 // Note that stripPointerCasts should look through functions with
591 // returned arguments.
592 Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
593 if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
594 return nullptr;
595
596 if (!RetArg)
597 RetArg = RetVal;
598 else if (RetArg != RetVal)
599 return nullptr;
600 }
601
602 return RetArg;
603 };
604
605 if (Value *RetArg = FindRetArg()) {
606 auto *A = cast<Argument>(RetArg);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000607 A->addAttr(Attribute::Returned);
David Majnemer5246e0b2016-07-19 18:50:26 +0000608 ++NumReturned;
609 Changed = true;
610 }
611 }
612
613 return Changed;
614}
615
Sanjay Patel4f742162017-02-13 23:10:51 +0000616/// If a callsite has arguments that are also arguments to the parent function,
617/// try to propagate attributes from the callsite's arguments to the parent's
618/// arguments. This may be important because inlining can cause information loss
619/// when attribute knowledge disappears with the inlined call.
620static bool addArgumentAttrsFromCallsites(Function &F) {
621 if (!EnableNonnullArgPropagation)
622 return false;
623
624 bool Changed = false;
625
626 // For an argument attribute to transfer from a callsite to the parent, the
627 // call must be guaranteed to execute every time the parent is called.
628 // Conservatively, just check for calls in the entry block that are guaranteed
629 // to execute.
630 // TODO: This could be enhanced by testing if the callsite post-dominates the
631 // entry block or by doing simple forward walks or backward walks to the
632 // callsite.
633 BasicBlock &Entry = F.getEntryBlock();
634 for (Instruction &I : Entry) {
635 if (auto CS = CallSite(&I)) {
636 if (auto *CalledFunc = CS.getCalledFunction()) {
637 for (auto &CSArg : CalledFunc->args()) {
638 if (!CSArg.hasNonNullAttr())
639 continue;
640
641 // If the non-null callsite argument operand is an argument to 'F'
642 // (the caller) and the call is guaranteed to execute, then the value
643 // must be non-null throughout 'F'.
644 auto *FArg = dyn_cast<Argument>(CS.getArgOperand(CSArg.getArgNo()));
645 if (FArg && !FArg->hasNonNullAttr()) {
646 FArg->addAttr(Attribute::NonNull);
647 Changed = true;
648 }
649 }
650 }
651 }
652 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
653 break;
654 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000655
Sanjay Patel4f742162017-02-13 23:10:51 +0000656 return Changed;
657}
658
Chandler Carrutha632fb92015-09-13 06:57:25 +0000659/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000660static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000661 bool Changed = false;
662
Nick Lewycky4c378a42011-12-28 23:24:21 +0000663 ArgumentGraph AG;
664
Duncan Sands44c8cd92008-12-31 16:14:43 +0000665 // Check each function in turn, determining which pointer arguments are not
666 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000667 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000668 // We can infer and propagate function attributes only when we know that the
669 // definition we'll get at link time is *exactly* the definition we see now.
670 // For more details, see GlobalValue::mayBeDerefined.
671 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000672 continue;
673
Sanjay Patel4f742162017-02-13 23:10:51 +0000674 Changed |= addArgumentAttrsFromCallsites(*F);
675
Nick Lewycky4c378a42011-12-28 23:24:21 +0000676 // Functions that are readonly (or readnone) and nounwind and don't return
677 // a value can't capture arguments. Don't analyze them.
678 if (F->onlyReadsMemory() && F->doesNotThrow() &&
679 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000680 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
681 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000682 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000683 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000684 ++NumNoCapture;
685 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000686 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000687 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000688 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000689 }
690
Chandler Carruth63559d72015-09-13 06:47:20 +0000691 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
692 ++A) {
693 if (!A->getType()->isPointerTy())
694 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000695 bool HasNonLocalUses = false;
696 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000697 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000698 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000699 if (!Tracker.Captured) {
700 if (Tracker.Uses.empty()) {
701 // If it's trivially not captured, mark it nocapture now.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000702 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000703 ++NumNoCapture;
704 Changed = true;
705 } else {
706 // If it's not trivially captured and not trivially not captured,
707 // then it must be calling into another function in our SCC. Save
708 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000709 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000710 for (Argument *Use : Tracker.Uses) {
711 Node->Uses.push_back(AG[Use]);
712 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000713 HasNonLocalUses = true;
714 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000715 }
716 }
717 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
718 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000719 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
720 // Can we determine that it's readonly/readnone without doing an SCC?
721 // Note that we don't allow any calls at all here, or else our result
722 // will be dependent on the iteration order through the functions in the
723 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000724 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000725 Self.insert(&*A);
726 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000727 if (R != Attribute::None) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000728 A->addAttr(R);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000729 Changed = true;
730 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
731 }
732 }
733 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000734 }
735
736 // The graph we've collected is partial because we stopped scanning for
737 // argument uses once we solved the argument trivially. These partial nodes
738 // show up as ArgumentGraphNode objects with an empty Uses list, and for
739 // these nodes the final decision about whether they capture has already been
740 // made. If the definition doesn't have a 'nocapture' attribute by now, it
741 // captures.
742
Chandler Carruth63559d72015-09-13 06:47:20 +0000743 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000744 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000745 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000746 if (!ArgumentSCC[0]->Definition)
747 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000748
749 // eg. "void f(int* x) { if (...) f(x); }"
750 if (ArgumentSCC[0]->Uses.size() == 1 &&
751 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000752 Argument *A = ArgumentSCC[0]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000753 A->addAttr(Attribute::NoCapture);
Nick Lewycky7e820552009-01-02 03:46:56 +0000754 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000755 Changed = true;
756 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000757 continue;
758 }
759
760 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000761 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
762 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000763 ArgumentGraphNode *Node = *I;
764 if (Node->Uses.empty()) {
765 if (!Node->Definition->hasNoCaptureAttr())
766 SCCCaptured = true;
767 }
768 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000769 if (SCCCaptured)
770 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000771
Chandler Carruth63559d72015-09-13 06:47:20 +0000772 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000773 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
774 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000775 for (ArgumentGraphNode *I : ArgumentSCC) {
776 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000777 }
778
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000779 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
780 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000781 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000782 for (ArgumentGraphNode *Use : N->Uses) {
783 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000784 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
785 continue;
786 SCCCaptured = true;
787 break;
788 }
789 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000790 if (SCCCaptured)
791 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000792
Nick Lewyckyf740db32012-01-05 22:21:45 +0000793 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000794 Argument *A = ArgumentSCC[i]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000795 A->addAttr(Attribute::NoCapture);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000796 ++NumNoCapture;
797 Changed = true;
798 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000799
800 // We also want to compute readonly/readnone. With a small number of false
801 // negatives, we can assume that any pointer which is captured isn't going
802 // to be provably readonly or readnone, since by definition we can't
803 // analyze all uses of a captured pointer.
804 //
805 // The false negatives happen when the pointer is captured by a function
806 // that promises readonly/readnone behaviour on the pointer, then the
807 // pointer's lifetime ends before anything that writes to arbitrary memory.
808 // Also, a readonly/readnone pointer may be returned, but returning a
809 // pointer is capturing it.
810
811 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
812 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
813 Argument *A = ArgumentSCC[i]->Definition;
814 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
815 if (K == Attribute::ReadNone)
816 continue;
817 if (K == Attribute::ReadOnly) {
818 ReadAttr = Attribute::ReadOnly;
819 continue;
820 }
821 ReadAttr = K;
822 break;
823 }
824
825 if (ReadAttr != Attribute::None) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000826 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
827 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000828 // Clear out existing readonly/readnone attributes
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000829 A->removeAttr(Attribute::ReadOnly);
830 A->removeAttr(Attribute::ReadNone);
831 A->addAttr(ReadAttr);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000832 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
833 Changed = true;
834 }
835 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000836 }
837
838 return Changed;
839}
840
Chandler Carrutha632fb92015-09-13 06:57:25 +0000841/// Tests whether a function is "malloc-like".
842///
843/// A function is "malloc-like" if it returns either null or a pointer that
844/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000845static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000846 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000847 for (BasicBlock &BB : *F)
848 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000849 FlowsToReturn.insert(Ret->getReturnValue());
850
851 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000852 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000853
854 if (Constant *C = dyn_cast<Constant>(RetVal)) {
855 if (!C->isNullValue() && !isa<UndefValue>(C))
856 return false;
857
858 continue;
859 }
860
861 if (isa<Argument>(RetVal))
862 return false;
863
864 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
865 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000866 // Extend the analysis by looking upwards.
867 case Instruction::BitCast:
868 case Instruction::GetElementPtr:
869 case Instruction::AddrSpaceCast:
870 FlowsToReturn.insert(RVI->getOperand(0));
871 continue;
872 case Instruction::Select: {
873 SelectInst *SI = cast<SelectInst>(RVI);
874 FlowsToReturn.insert(SI->getTrueValue());
875 FlowsToReturn.insert(SI->getFalseValue());
876 continue;
877 }
878 case Instruction::PHI: {
879 PHINode *PN = cast<PHINode>(RVI);
880 for (Value *IncValue : PN->incoming_values())
881 FlowsToReturn.insert(IncValue);
882 continue;
883 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000884
Chandler Carruth63559d72015-09-13 06:47:20 +0000885 // Check whether the pointer came from an allocation.
886 case Instruction::Alloca:
887 break;
888 case Instruction::Call:
889 case Instruction::Invoke: {
890 CallSite CS(RVI);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000891 if (CS.hasRetAttr(Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000892 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000893 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
894 break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000895 LLVM_FALLTHROUGH;
896 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000897 default:
898 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000899 }
900
Dan Gohman94e61762009-11-19 21:57:48 +0000901 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000902 return false;
903 }
904
905 return true;
906}
907
Chandler Carrutha632fb92015-09-13 06:57:25 +0000908/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000909static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000910 // Check each function in turn, determining which functions return noalias
911 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000912 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000913 // Already noalias.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000914 if (F->returnDoesNotAlias())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000915 continue;
916
Sanjoy Das5ce32722016-04-08 00:48:30 +0000917 // We can infer and propagate function attributes only when we know that the
918 // definition we'll get at link time is *exactly* the definition we see now.
919 // For more details, see GlobalValue::mayBeDerefined.
920 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000921 return false;
922
Chandler Carruth63559d72015-09-13 06:47:20 +0000923 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000924 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000925 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000926 continue;
927
Chandler Carruth3824f852015-09-13 08:23:27 +0000928 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000929 return false;
930 }
931
932 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000933 for (Function *F : SCCNodes) {
Reid Klecknera0b45f42017-05-03 18:17:31 +0000934 if (F->returnDoesNotAlias() ||
Reid Kleckner6652a522017-04-28 18:37:16 +0000935 !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000936 continue;
937
Reid Klecknera0b45f42017-05-03 18:17:31 +0000938 F->setReturnDoesNotAlias();
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000939 ++NumNoAlias;
940 MadeChange = true;
941 }
942
943 return MadeChange;
944}
945
Chandler Carrutha632fb92015-09-13 06:57:25 +0000946/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000947///
948/// Requires that the function returns a pointer.
949///
950/// Returns true if it believes the function will not return a null, and sets
951/// \p Speculative based on whether the returned conclusion is a speculative
952/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000953static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000954 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000955 assert(F->getReturnType()->isPointerTy() &&
956 "nonnull only meaningful on pointer types");
957 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000958
Philip Reamesa88caea2015-08-31 19:44:38 +0000959 SmallSetVector<Value *, 8> FlowsToReturn;
960 for (BasicBlock &BB : *F)
961 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
962 FlowsToReturn.insert(Ret->getReturnValue());
963
Nuno Lopes404f1062017-09-09 18:23:11 +0000964 auto &DL = F->getParent()->getDataLayout();
965
Philip Reamesa88caea2015-08-31 19:44:38 +0000966 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
967 Value *RetVal = FlowsToReturn[i];
968
969 // If this value is locally known to be non-null, we're good
Nuno Lopes404f1062017-09-09 18:23:11 +0000970 if (isKnownNonZero(RetVal, DL))
Philip Reamesa88caea2015-08-31 19:44:38 +0000971 continue;
972
973 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000974 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000975 Instruction *RVI = dyn_cast<Instruction>(RetVal);
976 if (!RVI)
977 return false;
978 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000979 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000980 case Instruction::BitCast:
981 case Instruction::GetElementPtr:
982 case Instruction::AddrSpaceCast:
983 FlowsToReturn.insert(RVI->getOperand(0));
984 continue;
985 case Instruction::Select: {
986 SelectInst *SI = cast<SelectInst>(RVI);
987 FlowsToReturn.insert(SI->getTrueValue());
988 FlowsToReturn.insert(SI->getFalseValue());
989 continue;
990 }
991 case Instruction::PHI: {
992 PHINode *PN = cast<PHINode>(RVI);
993 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
994 FlowsToReturn.insert(PN->getIncomingValue(i));
995 continue;
996 }
997 case Instruction::Call:
998 case Instruction::Invoke: {
999 CallSite CS(RVI);
1000 Function *Callee = CS.getCalledFunction();
1001 // A call to a node within the SCC is assumed to return null until
1002 // proven otherwise
1003 if (Callee && SCCNodes.count(Callee)) {
1004 Speculative = true;
1005 continue;
1006 }
1007 return false;
1008 }
1009 default:
Chandler Carruth63559d72015-09-13 06:47:20 +00001010 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +00001011 };
1012 llvm_unreachable("should have either continued or returned");
1013 }
1014
1015 return true;
1016}
1017
Chandler Carrutha632fb92015-09-13 06:57:25 +00001018/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +00001019static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001020 // Speculative that all functions in the SCC return only nonnull
1021 // pointers. We may refute this as we analyze functions.
1022 bool SCCReturnsNonNull = true;
1023
1024 bool MadeChange = false;
1025
1026 // Check each function in turn, determining which functions return nonnull
1027 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001028 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001029 // Already nonnull.
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 continue;
1033
Sanjoy Das5ce32722016-04-08 00:48:30 +00001034 // We can infer and propagate function attributes only when we know that the
1035 // definition we'll get at link time is *exactly* the definition we see now.
1036 // For more details, see GlobalValue::mayBeDerefined.
1037 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +00001038 return false;
1039
Chandler Carruth63559d72015-09-13 06:47:20 +00001040 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +00001041 // pointer types.
1042 if (!F->getReturnType()->isPointerTy())
1043 continue;
1044
1045 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +00001046 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001047 if (!Speculative) {
1048 // Mark the function eagerly since we may discover a function
1049 // which prevents us from speculating about the entire SCC
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001050 LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1051 << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001052 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001053 ++NumNonNullReturn;
1054 MadeChange = true;
1055 }
1056 continue;
1057 }
1058 // At least one function returns something which could be null, can't
1059 // speculate any more.
1060 SCCReturnsNonNull = false;
1061 }
1062
1063 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001064 for (Function *F : SCCNodes) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001065 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001066 Attribute::NonNull) ||
1067 !F->getReturnType()->isPointerTy())
1068 continue;
1069
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001070 LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001071 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001072 ++NumNonNullReturn;
1073 MadeChange = true;
1074 }
1075 }
1076
1077 return MadeChange;
1078}
1079
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001080namespace {
1081
1082/// Collects a set of attribute inference requests and performs them all in one
1083/// go on a single SCC Node. Inference involves scanning function bodies
1084/// looking for instructions that violate attribute assumptions.
1085/// As soon as all the bodies are fine we are free to set the attribute.
1086/// Customization of inference for individual attributes is performed by
1087/// providing a handful of predicates for each attribute.
1088class AttributeInferer {
1089public:
1090 /// Describes a request for inference of a single attribute.
1091 struct InferenceDescriptor {
1092
1093 /// Returns true if this function does not have to be handled.
1094 /// General intent for this predicate is to provide an optimization
1095 /// for functions that do not need this attribute inference at all
1096 /// (say, for functions that already have the attribute).
1097 std::function<bool(const Function &)> SkipFunction;
1098
1099 /// Returns true if this instruction violates attribute assumptions.
1100 std::function<bool(Instruction &)> InstrBreaksAttribute;
1101
1102 /// Sets the inferred attribute for this function.
1103 std::function<void(Function &)> SetAttribute;
1104
1105 /// Attribute we derive.
1106 Attribute::AttrKind AKind;
1107
1108 /// If true, only "exact" definitions can be used to infer this attribute.
1109 /// See GlobalValue::isDefinitionExact.
1110 bool RequiresExactDefinition;
1111
1112 InferenceDescriptor(Attribute::AttrKind AK,
1113 std::function<bool(const Function &)> SkipFunc,
1114 std::function<bool(Instruction &)> InstrScan,
1115 std::function<void(Function &)> SetAttr,
1116 bool ReqExactDef)
1117 : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1118 SetAttribute(SetAttr), AKind(AK),
1119 RequiresExactDefinition(ReqExactDef) {}
1120 };
1121
1122private:
1123 SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1124
1125public:
1126 void registerAttrInference(InferenceDescriptor AttrInference) {
1127 InferenceDescriptors.push_back(AttrInference);
1128 }
1129
1130 bool run(const SCCNodeSet &SCCNodes);
1131};
1132
1133/// Perform all the requested attribute inference actions according to the
1134/// attribute predicates stored before.
1135bool AttributeInferer::run(const SCCNodeSet &SCCNodes) {
1136 SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1137 // Go through all the functions in SCC and check corresponding attribute
1138 // assumptions for each of them. Attributes that are invalid for this SCC
1139 // will be removed from InferInSCC.
Chandler Carruth3937bc72016-02-12 09:47:49 +00001140 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001141
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001142 // No attributes whose assumptions are still valid - done.
1143 if (InferInSCC.empty())
1144 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001145
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001146 // Check if our attributes ever need scanning/can be scanned.
1147 llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1148 if (ID.SkipFunction(*F))
Justin Lebar9d943972016-03-14 20:18:54 +00001149 return false;
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001150
1151 // Remove from further inference (invalidate) when visiting a function
1152 // that has no instructions to scan/has an unsuitable definition.
1153 return F->isDeclaration() ||
1154 (ID.RequiresExactDefinition && !F->hasExactDefinition());
1155 });
1156
1157 // For each attribute still in InferInSCC that doesn't explicitly skip F,
1158 // set up the F instructions scan to verify assumptions of the attribute.
1159 SmallVector<InferenceDescriptor, 4> InferInThisFunc;
1160 llvm::copy_if(
1161 InferInSCC, std::back_inserter(InferInThisFunc),
1162 [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1163
1164 if (InferInThisFunc.empty())
1165 continue;
1166
1167 // Start instruction scan.
1168 for (Instruction &I : instructions(*F)) {
1169 llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1170 if (!ID.InstrBreaksAttribute(I))
1171 return false;
1172 // Remove attribute from further inference on any other functions
1173 // because attribute assumptions have just been violated.
1174 llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1175 return D.AKind == ID.AKind;
1176 });
1177 // Remove attribute from the rest of current instruction scan.
1178 return true;
1179 });
1180
1181 if (InferInThisFunc.empty())
1182 break;
Justin Lebar9d943972016-03-14 20:18:54 +00001183 }
1184 }
1185
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001186 if (InferInSCC.empty())
1187 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001188
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001189 bool Changed = false;
1190 for (Function *F : SCCNodes)
1191 // At this point InferInSCC contains only functions that were either:
1192 // - explicitly skipped from scan/inference, or
1193 // - verified to have no instructions that break attribute assumptions.
1194 // Hence we just go and force the attribute for all non-skipped functions.
1195 for (auto &ID : InferInSCC) {
1196 if (ID.SkipFunction(*F))
1197 continue;
1198 Changed = true;
1199 ID.SetAttribute(*F);
1200 }
1201 return Changed;
1202}
Justin Lebar9d943972016-03-14 20:18:54 +00001203
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001204} // end anonymous namespace
1205
1206/// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1207static bool InstrBreaksNonConvergent(Instruction &I,
1208 const SCCNodeSet &SCCNodes) {
1209 const CallSite CS(&I);
1210 // Breaks non-convergent assumption if CS is a convergent call to a function
1211 // not in the SCC.
1212 return CS && CS.isConvergent() && SCCNodes.count(CS.getCalledFunction()) == 0;
1213}
1214
1215/// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1216static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1217 if (!I.mayThrow())
1218 return false;
1219 if (const auto *CI = dyn_cast<CallInst>(&I)) {
1220 if (Function *Callee = CI->getCalledFunction()) {
1221 // I is a may-throw call to a function inside our SCC. This doesn't
1222 // invalidate our current working assumption that the SCC is no-throw; we
1223 // just have to scan that other function.
1224 if (SCCNodes.count(Callee) > 0)
1225 return false;
1226 }
Chandler Carruth3937bc72016-02-12 09:47:49 +00001227 }
Justin Lebar260854b2016-02-09 23:03:22 +00001228 return true;
1229}
1230
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001231/// Infer attributes from all functions in the SCC by scanning every
1232/// instruction for compliance to the attribute assumptions. Currently it
1233/// does:
1234/// - removal of Convergent attribute
1235/// - addition of NoUnwind attribute
1236///
1237/// Returns true if any changes to function attributes were made.
1238static bool inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes) {
1239
1240 AttributeInferer AI;
1241
1242 // Request to remove the convergent attribute from all functions in the SCC
1243 // if every callsite within the SCC is not convergent (except for calls
1244 // to functions within the SCC).
1245 // Note: Removal of the attr from the callsites will happen in
1246 // InstCombineCalls separately.
1247 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1248 Attribute::Convergent,
1249 // Skip non-convergent functions.
1250 [](const Function &F) { return !F.isConvergent(); },
1251 // Instructions that break non-convergent assumption.
1252 [SCCNodes](Instruction &I) {
1253 return InstrBreaksNonConvergent(I, SCCNodes);
1254 },
1255 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001256 LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1257 << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001258 F.setNotConvergent();
1259 },
1260 /* RequiresExactDefinition= */ false});
1261
1262 if (!DisableNoUnwindInference)
1263 // Request to infer nounwind attribute for all the functions in the SCC if
1264 // every callsite within the SCC is not throwing (except for calls to
1265 // functions within the SCC). Note that nounwind attribute suffers from
1266 // derefinement - results may change depending on how functions are
1267 // optimized. Thus it can be inferred only from exact definitions.
1268 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1269 Attribute::NoUnwind,
1270 // Skip non-throwing functions.
1271 [](const Function &F) { return F.doesNotThrow(); },
1272 // Instructions that break non-throwing assumption.
1273 [SCCNodes](Instruction &I) {
1274 return InstrBreaksNonThrowing(I, SCCNodes);
1275 },
1276 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001277 LLVM_DEBUG(dbgs()
1278 << "Adding nounwind attr to fn " << F.getName() << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001279 F.setDoesNotThrow();
1280 ++NumNoUnwind;
1281 },
1282 /* RequiresExactDefinition= */ true});
1283
1284 // Perform all the requested attribute inference actions.
1285 return AI.run(SCCNodes);
1286}
1287
James Molloy7e9bdd52015-11-12 10:55:20 +00001288static bool setDoesNotRecurse(Function &F) {
1289 if (F.doesNotRecurse())
1290 return false;
1291 F.setDoesNotRecurse();
1292 ++NumNoRecurse;
1293 return true;
1294}
1295
Chandler Carruth632d2082016-02-13 08:47:51 +00001296static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +00001297 // Try and identify functions that do not recurse.
1298
1299 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +00001300 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +00001301 return false;
1302
Chandler Carruth632d2082016-02-13 08:47:51 +00001303 Function *F = *SCCNodes.begin();
James Molloy7e9bdd52015-11-12 10:55:20 +00001304 if (!F || F->isDeclaration() || F->doesNotRecurse())
1305 return false;
1306
1307 // If all of the calls in F are identifiable and are to norecurse functions, F
1308 // is norecurse. This check also detects self-recursion as F is not currently
1309 // marked norecurse, so any called from F to F will not be marked norecurse.
Christian Bruel4ead99b2018-12-05 16:48:00 +00001310 for (auto &BB : *F)
1311 for (auto &I : BB.instructionsWithoutDebug())
1312 if (auto CS = CallSite(&I)) {
1313 Function *Callee = CS.getCalledFunction();
1314 if (!Callee || Callee == F || !Callee->doesNotRecurse())
1315 // Function calls a potentially recursive function.
1316 return false;
1317 }
James Molloy7e9bdd52015-11-12 10:55:20 +00001318
Chandler Carruth632d2082016-02-13 08:47:51 +00001319 // Every call was to a non-recursive function other than this function, and
1320 // we have no indirect recursion as the SCC size is one. This function cannot
1321 // recurse.
1322 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +00001323}
1324
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001325template <typename AARGetterT>
1326static bool deriveAttrsInPostOrder(SCCNodeSet &SCCNodes, AARGetterT &&AARGetter,
1327 bool HasUnknownCall) {
1328 bool Changed = false;
1329
1330 // Bail if the SCC only contains optnone functions.
1331 if (SCCNodes.empty())
1332 return Changed;
1333
1334 Changed |= addArgumentReturnedAttrs(SCCNodes);
1335 Changed |= addReadAttrs(SCCNodes, AARGetter);
1336 Changed |= addArgumentAttrs(SCCNodes);
1337
1338 // If we have no external nodes participating in the SCC, we can deduce some
1339 // more precise attributes as well.
1340 if (!HasUnknownCall) {
1341 Changed |= addNoAliasAttrs(SCCNodes);
1342 Changed |= addNonNullAttrs(SCCNodes);
1343 Changed |= inferAttrsFromFunctionBodies(SCCNodes);
1344 Changed |= addNoRecurseAttrs(SCCNodes);
1345 }
1346
1347 return Changed;
1348}
1349
Chandler Carruthb47f8012016-03-11 11:05:24 +00001350PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
Chandler Carruth88823462016-08-24 09:37:14 +00001351 CGSCCAnalysisManager &AM,
1352 LazyCallGraph &CG,
1353 CGSCCUpdateResult &) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001354 FunctionAnalysisManager &FAM =
Chandler Carruth88823462016-08-24 09:37:14 +00001355 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001356
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001357 // We pass a lambda into functions to wire them up to the analysis manager
1358 // for getting function analyses.
1359 auto AARGetter = [&](Function &F) -> AAResults & {
1360 return FAM.getResult<AAManager>(F);
1361 };
1362
1363 // Fill SCCNodes with the elements of the SCC. Also track whether there are
1364 // any external or opt-none nodes that will prevent us from optimizing any
1365 // part of the SCC.
1366 SCCNodeSet SCCNodes;
1367 bool HasUnknownCall = false;
1368 for (LazyCallGraph::Node &N : C) {
1369 Function &F = N.getFunction();
Luke Cheeseman6c1e6bb2018-02-22 14:42:08 +00001370 if (F.hasFnAttribute(Attribute::OptimizeNone) ||
1371 F.hasFnAttribute(Attribute::Naked)) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001372 // Treat any function we're trying not to optimize as if it were an
1373 // indirect call and omit it from the node set used below.
1374 HasUnknownCall = true;
1375 continue;
1376 }
1377 // Track whether any functions in this SCC have an unknown call edge.
1378 // Note: if this is ever a performance hit, we can common it with
1379 // subsequent routines which also do scans over the instructions of the
1380 // function.
1381 if (!HasUnknownCall)
1382 for (Instruction &I : instructions(F))
1383 if (auto CS = CallSite(&I))
1384 if (!CS.getCalledFunction()) {
1385 HasUnknownCall = true;
1386 break;
1387 }
1388
1389 SCCNodes.insert(&F);
1390 }
1391
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001392 if (deriveAttrsInPostOrder(SCCNodes, AARGetter, HasUnknownCall))
1393 return PreservedAnalyses::none();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001394
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001395 return PreservedAnalyses::all();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001396}
1397
1398namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001399
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001400struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001401 // Pass identification, replacement for typeid
1402 static char ID;
1403
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001404 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001405 initializePostOrderFunctionAttrsLegacyPassPass(
1406 *PassRegistry::getPassRegistry());
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001407 }
1408
1409 bool runOnSCC(CallGraphSCC &SCC) override;
1410
1411 void getAnalysisUsage(AnalysisUsage &AU) const override {
1412 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001413 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001414 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001415 CallGraphSCCPass::getAnalysisUsage(AU);
1416 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001417};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001418
1419} // end anonymous namespace
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001420
1421char PostOrderFunctionAttrsLegacyPass::ID = 0;
1422INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1423 "Deduce function attributes", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001424INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001425INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001426INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1427 "Deduce function attributes", false, false)
1428
Chad Rosier611b73b2016-11-07 16:28:04 +00001429Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1430 return new PostOrderFunctionAttrsLegacyPass();
1431}
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001432
Sean Silva997cbea2016-07-03 03:35:03 +00001433template <typename AARGetterT>
1434static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001435
1436 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1437 // whether a given CallGraphNode is in this SCC. Also track whether there are
1438 // any external or opt-none nodes that will prevent us from optimizing any
1439 // part of the SCC.
1440 SCCNodeSet SCCNodes;
1441 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001442 for (CallGraphNode *I : SCC) {
1443 Function *F = I->getFunction();
Luke Cheeseman6c1e6bb2018-02-22 14:42:08 +00001444 if (!F || F->hasFnAttribute(Attribute::OptimizeNone) ||
1445 F->hasFnAttribute(Attribute::Naked)) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001446 // External node or function we're trying not to optimize - we both avoid
1447 // transform them and avoid leveraging information they provide.
1448 ExternalNode = true;
1449 continue;
1450 }
1451
1452 SCCNodes.insert(F);
1453 }
1454
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001455 return deriveAttrsInPostOrder(SCCNodes, AARGetter, ExternalNode);
James Molloy7e9bdd52015-11-12 10:55:20 +00001456}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001457
Sean Silva997cbea2016-07-03 03:35:03 +00001458bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1459 if (skipSCC(SCC))
1460 return false;
Peter Collingbournecea1e4e2017-02-09 23:11:52 +00001461 return runImpl(SCC, LegacyAARGetter(*this));
Sean Silva997cbea2016-07-03 03:35:03 +00001462}
1463
Chandler Carruth1926b702016-01-08 10:55:52 +00001464namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001465
Sean Silvaf5080192016-06-12 07:48:51 +00001466struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001467 // Pass identification, replacement for typeid
1468 static char ID;
1469
Sean Silvaf5080192016-06-12 07:48:51 +00001470 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001471 initializeReversePostOrderFunctionAttrsLegacyPassPass(
1472 *PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001473 }
1474
1475 bool runOnModule(Module &M) override;
1476
1477 void getAnalysisUsage(AnalysisUsage &AU) const override {
1478 AU.setPreservesCFG();
1479 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001480 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001481 }
1482};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001483
1484} // end anonymous namespace
Chandler Carruth1926b702016-01-08 10:55:52 +00001485
Sean Silvaf5080192016-06-12 07:48:51 +00001486char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001487
Sean Silvaf5080192016-06-12 07:48:51 +00001488INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001489 "Deduce function attributes in RPO", false, false)
1490INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001491INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001492 "Deduce function attributes in RPO", false, false)
1493
1494Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001495 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001496}
1497
1498static bool addNoRecurseAttrsTopDown(Function &F) {
1499 // We check the preconditions for the function prior to calling this to avoid
1500 // the cost of building up a reversible post-order list. We assert them here
1501 // to make sure none of the invariants this relies on were violated.
1502 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1503 assert(!F.doesNotRecurse() &&
1504 "This function has already been deduced as norecurs!");
1505 assert(F.hasInternalLinkage() &&
1506 "Can only do top-down deduction for internal linkage functions!");
1507
1508 // If F is internal and all of its uses are calls from a non-recursive
1509 // functions, then none of its calls could in fact recurse without going
1510 // through a function marked norecurse, and so we can mark this function too
1511 // as norecurse. Note that the uses must actually be calls -- otherwise
1512 // a pointer to this function could be returned from a norecurse function but
1513 // this function could be recursively (indirectly) called. Note that this
1514 // also detects if F is directly recursive as F is not yet marked as
1515 // a norecurse function.
1516 for (auto *U : F.users()) {
1517 auto *I = dyn_cast<Instruction>(U);
1518 if (!I)
1519 return false;
1520 CallSite CS(I);
1521 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1522 return false;
1523 }
1524 return setDoesNotRecurse(F);
1525}
1526
Sean Silvaadc79392016-06-12 05:44:51 +00001527static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001528 // We only have a post-order SCC traversal (because SCCs are inherently
1529 // discovered in post-order), so we accumulate them in a vector and then walk
1530 // it in reverse. This is simpler than using the RPO iterator infrastructure
1531 // because we need to combine SCC detection and the PO walk of the call
1532 // graph. We can also cheat egregiously because we're primarily interested in
1533 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1534 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001535 SmallVector<Function *, 16> Worklist;
1536 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1537 if (I->size() != 1)
1538 continue;
1539
1540 Function *F = I->front()->getFunction();
1541 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1542 F->hasInternalLinkage())
1543 Worklist.push_back(F);
1544 }
1545
James Molloy7e9bdd52015-11-12 10:55:20 +00001546 bool Changed = false;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001547 for (auto *F : llvm::reverse(Worklist))
Chandler Carruth1926b702016-01-08 10:55:52 +00001548 Changed |= addNoRecurseAttrsTopDown(*F);
1549
Duncan Sands44c8cd92008-12-31 16:14:43 +00001550 return Changed;
1551}
Sean Silvaadc79392016-06-12 05:44:51 +00001552
Sean Silvaf5080192016-06-12 07:48:51 +00001553bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001554 if (skipModule(M))
1555 return false;
1556
1557 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1558
1559 return deduceFunctionAttributeInRPO(M, CG);
1560}
Sean Silvaf5080192016-06-12 07:48:51 +00001561
1562PreservedAnalyses
Sean Silvafd03ac62016-08-09 00:28:38 +00001563ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
Sean Silvaf5080192016-06-12 07:48:51 +00001564 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1565
Chandler Carruth6acdca72017-01-24 12:55:57 +00001566 if (!deduceFunctionAttributeInRPO(M, CG))
Sean Silvaf5080192016-06-12 07:48:51 +00001567 return PreservedAnalyses::all();
Chandler Carruth6acdca72017-01-24 12:55:57 +00001568
Sean Silvaf5080192016-06-12 07:48:51 +00001569 PreservedAnalyses PA;
1570 PA.preserve<CallGraphAnalysis>();
1571 return PA;
1572}