blob: b84620c48116be96da6288b4ce16d01c29bb3d7e [file] [log] [blame]
Meador Inge6b6a1612013-03-21 00:55:59 +00001//===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
Duncan Sands44c8cd92008-12-31 16:14:43 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chandler Carruth1926b702016-01-08 10:55:52 +00009///
10/// \file
11/// This file implements interprocedural passes which walk the
12/// call-graph deducing and/or propagating function attributes.
13///
Duncan Sands44c8cd92008-12-31 16:14:43 +000014//===----------------------------------------------------------------------===//
15
Duncan Sands44c8cd92008-12-31 16:14:43 +000016#include "llvm/Transforms/IPO.h"
Nick Lewycky4c378a42011-12-28 23:24:21 +000017#include "llvm/ADT/SCCIterator.h"
Benjamin Kramer15591272012-10-31 13:45:49 +000018#include "llvm/ADT/SetVector.h"
Duncan Sandsb193a372009-01-02 11:54:37 +000019#include "llvm/ADT/SmallSet.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000020#include "llvm/ADT/Statistic.h"
James Molloy0ecdbe72015-11-19 08:49:57 +000021#include "llvm/ADT/StringSwitch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000023#include "llvm/Analysis/AssumptionCache.h"
24#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/CallGraph.h"
Chandler Carruth839a98e2013-01-07 15:26:48 +000026#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000028#include "llvm/Analysis/TargetLibraryInfo.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000029#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000031#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/LLVMContext.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000034#include "llvm/Support/Debug.h"
Hans Wennborg043bf5b2015-08-31 21:19:18 +000035#include "llvm/Support/raw_ostream.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000036#include "llvm/Analysis/TargetLibraryInfo.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000037using namespace llvm;
38
Chandler Carruth964daaa2014-04-22 02:55:47 +000039#define DEBUG_TYPE "functionattrs"
40
Duncan Sands44c8cd92008-12-31 16:14:43 +000041STATISTIC(NumReadNone, "Number of functions marked readnone");
42STATISTIC(NumReadOnly, "Number of functions marked readonly");
43STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
Nick Lewyckyc2ec0722013-07-06 00:29:58 +000044STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
45STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
Nick Lewyckyfbed86a2009-03-08 06:20:47 +000046STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Philip Reamesa88caea2015-08-31 19:44:38 +000047STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
James Molloy7e9bdd52015-11-12 10:55:20 +000048STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
Duncan Sands44c8cd92008-12-31 16:14:43 +000049
50namespace {
Chandler Carruthc518ebd2015-10-29 18:29:15 +000051typedef SmallSetVector<Function *, 8> SCCNodeSet;
52}
53
54namespace {
Chandler Carruth1926b702016-01-08 10:55:52 +000055struct PostOrderFunctionAttrs : public CallGraphSCCPass {
Chandler Carruth63559d72015-09-13 06:47:20 +000056 static char ID; // Pass identification, replacement for typeid
Chandler Carruth1926b702016-01-08 10:55:52 +000057 PostOrderFunctionAttrs() : CallGraphSCCPass(ID) {
58 initializePostOrderFunctionAttrsPass(*PassRegistry::getPassRegistry());
Chandler Carruth63559d72015-09-13 06:47:20 +000059 }
60
Chandler Carruth63559d72015-09-13 06:47:20 +000061 bool runOnSCC(CallGraphSCC &SCC) override;
Chandler Carruth1926b702016-01-08 10:55:52 +000062
Chandler Carruth63559d72015-09-13 06:47:20 +000063 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 AU.setPreservesCFG();
65 AU.addRequired<AssumptionCacheTracker>();
66 AU.addRequired<TargetLibraryInfoWrapperPass>();
Sanjoy Das1c481f52016-02-09 01:21:57 +000067 addUsedAAAnalyses(AU);
Chandler Carruth63559d72015-09-13 06:47:20 +000068 CallGraphSCCPass::getAnalysisUsage(AU);
69 }
Meador Inge6b6a1612013-03-21 00:55:59 +000070
Chandler Carruth63559d72015-09-13 06:47:20 +000071private:
72 TargetLibraryInfo *TLI;
73};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000074}
Duncan Sands44c8cd92008-12-31 16:14:43 +000075
Chandler Carruth1926b702016-01-08 10:55:52 +000076char PostOrderFunctionAttrs::ID = 0;
77INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrs, "functionattrs",
Chandler Carruth63559d72015-09-13 06:47:20 +000078 "Deduce function attributes", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +000079INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth6378cf52013-11-26 04:19:30 +000080INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000081INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth1926b702016-01-08 10:55:52 +000082INITIALIZE_PASS_END(PostOrderFunctionAttrs, "functionattrs",
Chandler Carruth63559d72015-09-13 06:47:20 +000083 "Deduce function attributes", false, false)
Duncan Sands44c8cd92008-12-31 16:14:43 +000084
Chandler Carruth1926b702016-01-08 10:55:52 +000085Pass *llvm::createPostOrderFunctionAttrsPass() { return new PostOrderFunctionAttrs(); }
Duncan Sands44c8cd92008-12-31 16:14:43 +000086
Chandler Carruth7542d372015-09-21 17:39:41 +000087namespace {
88/// The three kinds of memory access relevant to 'readonly' and
89/// 'readnone' attributes.
90enum MemoryAccessKind {
91 MAK_ReadNone = 0,
92 MAK_ReadOnly = 1,
93 MAK_MayWrite = 2
94};
95}
96
Chandler Carruthc518ebd2015-10-29 18:29:15 +000097static MemoryAccessKind checkFunctionMemoryAccess(Function &F, AAResults &AAR,
98 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +000099 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
100 if (MRB == FMRB_DoesNotAccessMemory)
101 // Already perfect!
102 return MAK_ReadNone;
103
104 // Definitions with weak linkage may be overridden at linktime with
105 // something that writes memory, so treat them like declarations.
106 if (F.isDeclaration() || F.mayBeOverridden()) {
107 if (AliasAnalysis::onlyReadsMemory(MRB))
108 return MAK_ReadOnly;
109
110 // Conservatively assume it writes to memory.
111 return MAK_MayWrite;
112 }
113
114 // Scan the function body for instructions that may read or write memory.
115 bool ReadsMemory = false;
116 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
117 Instruction *I = &*II;
118
119 // Some instructions can be ignored even if they read or write memory.
120 // Detect these now, skipping to the next instruction if one is found.
121 CallSite CS(cast<Value>(I));
122 if (CS) {
123 // Ignore calls to functions in the same SCC.
124 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
125 continue;
126 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
Chandler Carruth7542d372015-09-21 17:39:41 +0000127
Chandler Carruth69798fb2015-10-27 01:41:43 +0000128 // If the call doesn't access memory, we're done.
129 if (!(MRB & MRI_ModRef))
130 continue;
131
132 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
133 // The call could access any memory. If that includes writes, give up.
134 if (MRB & MRI_Mod)
135 return MAK_MayWrite;
136 // If it reads, note it.
137 if (MRB & MRI_Ref)
138 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000139 continue;
140 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000141
142 // Check whether all pointer arguments point to local memory, and
143 // ignore calls that only access local memory.
144 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
145 CI != CE; ++CI) {
146 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000147 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000148 continue;
149
150 AAMDNodes AAInfo;
151 I->getAAMetadata(AAInfo);
152 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
153
154 // Skip accesses to local or constant memory as they don't impact the
155 // externally visible mod/ref behavior.
156 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
157 continue;
158
159 if (MRB & MRI_Mod)
160 // Writes non-local memory. Give up.
161 return MAK_MayWrite;
162 if (MRB & MRI_Ref)
163 // Ok, it reads non-local memory.
164 ReadsMemory = true;
165 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000166 continue;
167 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
168 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
169 if (!LI->isVolatile()) {
170 MemoryLocation Loc = MemoryLocation::get(LI);
171 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
172 continue;
173 }
174 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
175 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
176 if (!SI->isVolatile()) {
177 MemoryLocation Loc = MemoryLocation::get(SI);
178 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
179 continue;
180 }
181 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
182 // Ignore vaargs on local memory.
183 MemoryLocation Loc = MemoryLocation::get(VI);
184 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
185 continue;
186 }
187
188 // Any remaining instructions need to be taken seriously! Check if they
189 // read or write memory.
190 if (I->mayWriteToMemory())
191 // Writes memory. Just give up.
192 return MAK_MayWrite;
193
194 // If this instruction may read memory, remember that.
195 ReadsMemory |= I->mayReadFromMemory();
196 }
197
198 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
199}
200
Chandler Carrutha632fb92015-09-13 06:57:25 +0000201/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000202template <typename AARGetterT>
203static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000204 // Check if any of the functions in the SCC read or write memory. If they
205 // write memory then they can't be marked readnone or readonly.
206 bool ReadsMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000207 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000208 // Call the callable parameter to look up AA results for this function.
209 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000210
Chandler Carruth7542d372015-09-21 17:39:41 +0000211 switch (checkFunctionMemoryAccess(*F, AAR, SCCNodes)) {
212 case MAK_MayWrite:
213 return false;
214 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000215 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000216 break;
217 case MAK_ReadNone:
218 // Nothing to do!
219 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000220 }
221 }
222
223 // Success! Functions in this SCC do not access memory, or only read memory.
224 // Give them the appropriate attribute.
225 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000226 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000227 if (F->doesNotAccessMemory())
228 // Already perfect!
229 continue;
230
231 if (F->onlyReadsMemory() && ReadsMemory)
232 // No change.
233 continue;
234
235 MadeChange = true;
236
237 // Clear out any existing attributes.
Bill Wendling50d27842012-10-15 20:35:56 +0000238 AttrBuilder B;
Chandler Carruth63559d72015-09-13 06:47:20 +0000239 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
240 F->removeAttributes(
241 AttributeSet::FunctionIndex,
242 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
Duncan Sands44c8cd92008-12-31 16:14:43 +0000243
244 // Add in the new attribute.
Bill Wendlinge94d8432012-12-07 23:16:57 +0000245 F->addAttribute(AttributeSet::FunctionIndex,
Bill Wendlingc0e2a1f2013-01-23 00:20:53 +0000246 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000247
248 if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000249 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000250 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000251 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000252 }
253
254 return MadeChange;
255}
256
Nick Lewycky4c378a42011-12-28 23:24:21 +0000257namespace {
Chandler Carrutha632fb92015-09-13 06:57:25 +0000258/// For a given pointer Argument, this retains a list of Arguments of functions
259/// in the same SCC that the pointer data flows into. We use this to build an
260/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000261struct ArgumentGraphNode {
262 Argument *Definition;
263 SmallVector<ArgumentGraphNode *, 4> Uses;
264};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000265
Chandler Carruth63559d72015-09-13 06:47:20 +0000266class ArgumentGraph {
267 // We store pointers to ArgumentGraphNode objects, so it's important that
268 // that they not move around upon insert.
269 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000270
Chandler Carruth63559d72015-09-13 06:47:20 +0000271 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000272
Chandler Carruth63559d72015-09-13 06:47:20 +0000273 // There is no root node for the argument graph, in fact:
274 // void f(int *x, int *y) { if (...) f(x, y); }
275 // is an example where the graph is disconnected. The SCCIterator requires a
276 // single entry point, so we maintain a fake ("synthetic") root node that
277 // uses every node. Because the graph is directed and nothing points into
278 // the root, it will not participate in any SCCs (except for its own).
279 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000280
Chandler Carruth63559d72015-09-13 06:47:20 +0000281public:
282 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000283
Chandler Carruth63559d72015-09-13 06:47:20 +0000284 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000285
Chandler Carruth63559d72015-09-13 06:47:20 +0000286 iterator begin() { return SyntheticRoot.Uses.begin(); }
287 iterator end() { return SyntheticRoot.Uses.end(); }
288 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000289
Chandler Carruth63559d72015-09-13 06:47:20 +0000290 ArgumentGraphNode *operator[](Argument *A) {
291 ArgumentGraphNode &Node = ArgumentMap[A];
292 Node.Definition = A;
293 SyntheticRoot.Uses.push_back(&Node);
294 return &Node;
295 }
296};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000297
Chandler Carrutha632fb92015-09-13 06:57:25 +0000298/// This tracker checks whether callees are in the SCC, and if so it does not
299/// consider that a capture, instead adding it to the "Uses" list and
300/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000301struct ArgumentUsesTracker : public CaptureTracker {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000302 ArgumentUsesTracker(const SCCNodeSet &SCCNodes)
Nick Lewycky4c378a42011-12-28 23:24:21 +0000303 : Captured(false), SCCNodes(SCCNodes) {}
304
Chandler Carruth63559d72015-09-13 06:47:20 +0000305 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000306
Chandler Carruth63559d72015-09-13 06:47:20 +0000307 bool captured(const Use *U) override {
308 CallSite CS(U->getUser());
309 if (!CS.getInstruction()) {
310 Captured = true;
311 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000312 }
313
Chandler Carruth63559d72015-09-13 06:47:20 +0000314 Function *F = CS.getCalledFunction();
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000315 if (!F || F->isDeclaration() || F->mayBeOverridden() ||
316 !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000317 Captured = true;
318 return true;
319 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000320
Sanjoy Das98bfe262015-11-05 03:04:40 +0000321 // Note: the callee and the two successor blocks *follow* the argument
322 // operands. This means there is no need to adjust UseIndex to account for
323 // these.
324
325 unsigned UseIndex =
326 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
327
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000328 assert(UseIndex < CS.data_operands_size() &&
329 "Indirect function calls should have been filtered above!");
330
331 if (UseIndex >= CS.getNumArgOperands()) {
332 // Data operand, but not a argument operand -- must be a bundle operand
333 assert(CS.hasOperandBundles() && "Must be!");
334
335 // CaptureTracking told us that we're being captured by an operand bundle
336 // use. In this case it does not matter if the callee is within our SCC
337 // or not -- we've been captured in some unknown way, and we have to be
338 // conservative.
339 Captured = true;
340 return true;
341 }
342
Sanjoy Das98bfe262015-11-05 03:04:40 +0000343 if (UseIndex >= F->arg_size()) {
344 assert(F->isVarArg() && "More params than args in non-varargs call");
345 Captured = true;
346 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000347 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000348
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000349 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000350 return false;
351 }
352
353 bool Captured; // True only if certainly captured (used outside our SCC).
354 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
355
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000356 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000357};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000358}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000359
360namespace llvm {
Chandler Carruth63559d72015-09-13 06:47:20 +0000361template <> struct GraphTraits<ArgumentGraphNode *> {
362 typedef ArgumentGraphNode NodeType;
363 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000364
Chandler Carruth63559d72015-09-13 06:47:20 +0000365 static inline NodeType *getEntryNode(NodeType *A) { return A; }
366 static inline ChildIteratorType child_begin(NodeType *N) {
367 return N->Uses.begin();
368 }
369 static inline ChildIteratorType child_end(NodeType *N) {
370 return N->Uses.end();
371 }
372};
373template <>
374struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
375 static NodeType *getEntryNode(ArgumentGraph *AG) {
376 return AG->getEntryNode();
377 }
378 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
379 return AG->begin();
380 }
381 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
382};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000383}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000384
Chandler Carrutha632fb92015-09-13 06:57:25 +0000385/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000386static Attribute::AttrKind
387determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000388 const SmallPtrSet<Argument *, 8> &SCCNodes) {
389
390 SmallVector<Use *, 32> Worklist;
391 SmallSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000392
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000393 // inalloca arguments are always clobbered by the call.
394 if (A->hasInAllocaAttr())
395 return Attribute::None;
396
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000397 bool IsRead = false;
398 // We don't need to track IsWritten. If A is written to, return immediately.
399
Chandler Carruthcdf47882014-03-09 03:16:01 +0000400 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000401 Visited.insert(&U);
402 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000403 }
404
405 while (!Worklist.empty()) {
406 Use *U = Worklist.pop_back_val();
407 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000408
409 switch (I->getOpcode()) {
410 case Instruction::BitCast:
411 case Instruction::GetElementPtr:
412 case Instruction::PHI:
413 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000414 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000415 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000416 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000417 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000418 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000419 break;
420
421 case Instruction::Call:
422 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000423 bool Captures = true;
424
425 if (I->getType()->isVoidTy())
426 Captures = false;
427
428 auto AddUsersToWorklistIfCapturing = [&] {
429 if (Captures)
430 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000431 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000432 Worklist.push_back(&UU);
433 };
434
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000435 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000436 if (CS.doesNotAccessMemory()) {
437 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000438 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000439 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000440
441 Function *F = CS.getCalledFunction();
442 if (!F) {
443 if (CS.onlyReadsMemory()) {
444 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000445 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000446 continue;
447 }
448 return Attribute::None;
449 }
450
Sanjoy Das436e2392015-11-07 01:55:53 +0000451 // Note: the callee and the two successor blocks *follow* the argument
452 // operands. This means there is no need to adjust UseIndex to account
453 // for these.
454
455 unsigned UseIndex = std::distance(CS.arg_begin(), U);
456
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000457 // U cannot be the callee operand use: since we're exploring the
458 // transitive uses of an Argument, having such a use be a callee would
459 // imply the CallSite is an indirect call or invoke; and we'd take the
460 // early exit above.
461 assert(UseIndex < CS.data_operands_size() &&
462 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000463
464 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
465
466 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000467 assert(F->isVarArg() && "More params than args in non-varargs call");
468 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000469 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000470
Tilmann Scheller925b1932015-11-20 19:17:10 +0000471 Captures &= !CS.doesNotCapture(UseIndex);
472
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000473 // Since the optimizer (by design) cannot see the data flow corresponding
474 // to a operand bundle use, these cannot participate in the optimistic SCC
475 // analysis. Instead, we model the operand bundle uses as arguments in
476 // call to a function external to the SCC.
Sanjoy Das76dd2432015-11-07 02:26:53 +0000477 if (!SCCNodes.count(&*std::next(F->arg_begin(), UseIndex)) ||
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000478 IsOperandBundleUse) {
479
480 // The accessors used on CallSite here do the right thing for calls and
481 // invokes with operand bundles.
482
Sanjoy Das436e2392015-11-07 01:55:53 +0000483 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
484 return Attribute::None;
485 if (!CS.doesNotAccessMemory(UseIndex))
486 IsRead = true;
487 }
488
Nick Lewycky59633cb2014-05-30 02:31:27 +0000489 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000490 break;
491 }
492
493 case Instruction::Load:
494 IsRead = true;
495 break;
496
497 case Instruction::ICmp:
498 case Instruction::Ret:
499 break;
500
501 default:
502 return Attribute::None;
503 }
504 }
505
506 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
507}
508
Chandler Carrutha632fb92015-09-13 06:57:25 +0000509/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000510static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000511 bool Changed = false;
512
Nick Lewycky4c378a42011-12-28 23:24:21 +0000513 ArgumentGraph AG;
514
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000515 AttrBuilder B;
516 B.addAttribute(Attribute::NoCapture);
517
Duncan Sands44c8cd92008-12-31 16:14:43 +0000518 // Check each function in turn, determining which pointer arguments are not
519 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000520 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000521 // Definitions with weak linkage may be overridden at linktime with
Nick Lewycky4c378a42011-12-28 23:24:21 +0000522 // something that captures pointers, so treat them like declarations.
Duncan Sands44c8cd92008-12-31 16:14:43 +0000523 if (F->isDeclaration() || F->mayBeOverridden())
524 continue;
525
Nick Lewycky4c378a42011-12-28 23:24:21 +0000526 // Functions that are readonly (or readnone) and nounwind and don't return
527 // a value can't capture arguments. Don't analyze them.
528 if (F->onlyReadsMemory() && F->doesNotThrow() &&
529 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000530 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
531 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000532 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
533 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
534 ++NumNoCapture;
535 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000536 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000537 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000538 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000539 }
540
Chandler Carruth63559d72015-09-13 06:47:20 +0000541 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
542 ++A) {
543 if (!A->getType()->isPointerTy())
544 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000545 bool HasNonLocalUses = false;
546 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000547 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000548 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000549 if (!Tracker.Captured) {
550 if (Tracker.Uses.empty()) {
551 // If it's trivially not captured, mark it nocapture now.
Chandler Carruth63559d72015-09-13 06:47:20 +0000552 A->addAttr(
553 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000554 ++NumNoCapture;
555 Changed = true;
556 } else {
557 // If it's not trivially captured and not trivially not captured,
558 // then it must be calling into another function in our SCC. Save
559 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000560 ArgumentGraphNode *Node = AG[&*A];
Chandler Carruth63559d72015-09-13 06:47:20 +0000561 for (SmallVectorImpl<Argument *>::iterator
562 UI = Tracker.Uses.begin(),
563 UE = Tracker.Uses.end();
564 UI != UE; ++UI) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000565 Node->Uses.push_back(AG[*UI]);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000566 if (*UI != A)
567 HasNonLocalUses = true;
568 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000569 }
570 }
571 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
572 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000573 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
574 // Can we determine that it's readonly/readnone without doing an SCC?
575 // Note that we don't allow any calls at all here, or else our result
576 // will be dependent on the iteration order through the functions in the
577 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000578 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000579 Self.insert(&*A);
580 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000581 if (R != Attribute::None) {
582 AttrBuilder B;
583 B.addAttribute(R);
584 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
585 Changed = true;
586 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
587 }
588 }
589 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000590 }
591
592 // The graph we've collected is partial because we stopped scanning for
593 // argument uses once we solved the argument trivially. These partial nodes
594 // show up as ArgumentGraphNode objects with an empty Uses list, and for
595 // these nodes the final decision about whether they capture has already been
596 // made. If the definition doesn't have a 'nocapture' attribute by now, it
597 // captures.
598
Chandler Carruth63559d72015-09-13 06:47:20 +0000599 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000600 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000601 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000602 if (!ArgumentSCC[0]->Definition)
603 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000604
605 // eg. "void f(int* x) { if (...) f(x); }"
606 if (ArgumentSCC[0]->Uses.size() == 1 &&
607 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000608 Argument *A = ArgumentSCC[0]->Definition;
609 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky7e820552009-01-02 03:46:56 +0000610 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000611 Changed = true;
612 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000613 continue;
614 }
615
616 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000617 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
618 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000619 ArgumentGraphNode *Node = *I;
620 if (Node->Uses.empty()) {
621 if (!Node->Definition->hasNoCaptureAttr())
622 SCCCaptured = true;
623 }
624 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000625 if (SCCCaptured)
626 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000627
Chandler Carruth63559d72015-09-13 06:47:20 +0000628 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000629 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
630 // quickly looking up whether a given Argument is in this ArgumentSCC.
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000631 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000632 ArgumentSCCNodes.insert((*I)->Definition);
633 }
634
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000635 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
636 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000637 ArgumentGraphNode *N = *I;
Chandler Carruth63559d72015-09-13 06:47:20 +0000638 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
639 UE = N->Uses.end();
640 UI != UE; ++UI) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000641 Argument *A = (*UI)->Definition;
642 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
643 continue;
644 SCCCaptured = true;
645 break;
646 }
647 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000648 if (SCCCaptured)
649 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000650
Nick Lewyckyf740db32012-01-05 22:21:45 +0000651 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000652 Argument *A = ArgumentSCC[i]->Definition;
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000653 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky4c378a42011-12-28 23:24:21 +0000654 ++NumNoCapture;
655 Changed = true;
656 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000657
658 // We also want to compute readonly/readnone. With a small number of false
659 // negatives, we can assume that any pointer which is captured isn't going
660 // to be provably readonly or readnone, since by definition we can't
661 // analyze all uses of a captured pointer.
662 //
663 // The false negatives happen when the pointer is captured by a function
664 // that promises readonly/readnone behaviour on the pointer, then the
665 // pointer's lifetime ends before anything that writes to arbitrary memory.
666 // Also, a readonly/readnone pointer may be returned, but returning a
667 // pointer is capturing it.
668
669 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
670 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
671 Argument *A = ArgumentSCC[i]->Definition;
672 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
673 if (K == Attribute::ReadNone)
674 continue;
675 if (K == Attribute::ReadOnly) {
676 ReadAttr = Attribute::ReadOnly;
677 continue;
678 }
679 ReadAttr = K;
680 break;
681 }
682
683 if (ReadAttr != Attribute::None) {
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000684 AttrBuilder B, R;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000685 B.addAttribute(ReadAttr);
Chandler Carruth63559d72015-09-13 06:47:20 +0000686 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000687 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
688 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000689 // Clear out existing readonly/readnone attributes
690 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000691 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
692 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
693 Changed = true;
694 }
695 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000696 }
697
698 return Changed;
699}
700
Chandler Carrutha632fb92015-09-13 06:57:25 +0000701/// Tests whether a function is "malloc-like".
702///
703/// A function is "malloc-like" if it returns either null or a pointer that
704/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000705static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000706 SmallSetVector<Value *, 8> FlowsToReturn;
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000707 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
708 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
709 FlowsToReturn.insert(Ret->getReturnValue());
710
711 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000712 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000713
714 if (Constant *C = dyn_cast<Constant>(RetVal)) {
715 if (!C->isNullValue() && !isa<UndefValue>(C))
716 return false;
717
718 continue;
719 }
720
721 if (isa<Argument>(RetVal))
722 return false;
723
724 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
725 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000726 // Extend the analysis by looking upwards.
727 case Instruction::BitCast:
728 case Instruction::GetElementPtr:
729 case Instruction::AddrSpaceCast:
730 FlowsToReturn.insert(RVI->getOperand(0));
731 continue;
732 case Instruction::Select: {
733 SelectInst *SI = cast<SelectInst>(RVI);
734 FlowsToReturn.insert(SI->getTrueValue());
735 FlowsToReturn.insert(SI->getFalseValue());
736 continue;
737 }
738 case Instruction::PHI: {
739 PHINode *PN = cast<PHINode>(RVI);
740 for (Value *IncValue : PN->incoming_values())
741 FlowsToReturn.insert(IncValue);
742 continue;
743 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000744
Chandler Carruth63559d72015-09-13 06:47:20 +0000745 // Check whether the pointer came from an allocation.
746 case Instruction::Alloca:
747 break;
748 case Instruction::Call:
749 case Instruction::Invoke: {
750 CallSite CS(RVI);
751 if (CS.paramHasAttr(0, Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000752 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000753 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
754 break;
755 } // fall-through
756 default:
757 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000758 }
759
Dan Gohman94e61762009-11-19 21:57:48 +0000760 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000761 return false;
762 }
763
764 return true;
765}
766
Chandler Carrutha632fb92015-09-13 06:57:25 +0000767/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000768static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000769 // Check each function in turn, determining which functions return noalias
770 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000771 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000772 // Already noalias.
773 if (F->doesNotAlias(0))
774 continue;
775
776 // Definitions with weak linkage may be overridden at linktime, so
777 // treat them like declarations.
778 if (F->isDeclaration() || F->mayBeOverridden())
779 return false;
780
Chandler Carruth63559d72015-09-13 06:47:20 +0000781 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000782 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000783 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000784 continue;
785
Chandler Carruth3824f852015-09-13 08:23:27 +0000786 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000787 return false;
788 }
789
790 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000791 for (Function *F : SCCNodes) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000792 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000793 continue;
794
795 F->setDoesNotAlias(0);
796 ++NumNoAlias;
797 MadeChange = true;
798 }
799
800 return MadeChange;
801}
802
Chandler Carrutha632fb92015-09-13 06:57:25 +0000803/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000804///
805/// Requires that the function returns a pointer.
806///
807/// Returns true if it believes the function will not return a null, and sets
808/// \p Speculative based on whether the returned conclusion is a speculative
809/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000810static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Chandler Carruth8874b782015-09-13 08:17:14 +0000811 const TargetLibraryInfo &TLI, bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000812 assert(F->getReturnType()->isPointerTy() &&
813 "nonnull only meaningful on pointer types");
814 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000815
Philip Reamesa88caea2015-08-31 19:44:38 +0000816 SmallSetVector<Value *, 8> FlowsToReturn;
817 for (BasicBlock &BB : *F)
818 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
819 FlowsToReturn.insert(Ret->getReturnValue());
820
821 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
822 Value *RetVal = FlowsToReturn[i];
823
824 // If this value is locally known to be non-null, we're good
Chandler Carruth8874b782015-09-13 08:17:14 +0000825 if (isKnownNonNull(RetVal, &TLI))
Philip Reamesa88caea2015-08-31 19:44:38 +0000826 continue;
827
828 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000829 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000830 Instruction *RVI = dyn_cast<Instruction>(RetVal);
831 if (!RVI)
832 return false;
833 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000834 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000835 case Instruction::BitCast:
836 case Instruction::GetElementPtr:
837 case Instruction::AddrSpaceCast:
838 FlowsToReturn.insert(RVI->getOperand(0));
839 continue;
840 case Instruction::Select: {
841 SelectInst *SI = cast<SelectInst>(RVI);
842 FlowsToReturn.insert(SI->getTrueValue());
843 FlowsToReturn.insert(SI->getFalseValue());
844 continue;
845 }
846 case Instruction::PHI: {
847 PHINode *PN = cast<PHINode>(RVI);
848 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
849 FlowsToReturn.insert(PN->getIncomingValue(i));
850 continue;
851 }
852 case Instruction::Call:
853 case Instruction::Invoke: {
854 CallSite CS(RVI);
855 Function *Callee = CS.getCalledFunction();
856 // A call to a node within the SCC is assumed to return null until
857 // proven otherwise
858 if (Callee && SCCNodes.count(Callee)) {
859 Speculative = true;
860 continue;
861 }
862 return false;
863 }
864 default:
Chandler Carruth63559d72015-09-13 06:47:20 +0000865 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +0000866 };
867 llvm_unreachable("should have either continued or returned");
868 }
869
870 return true;
871}
872
Chandler Carrutha632fb92015-09-13 06:57:25 +0000873/// Deduce nonnull attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000874static bool addNonNullAttrs(const SCCNodeSet &SCCNodes,
875 const TargetLibraryInfo &TLI) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000876 // Speculative that all functions in the SCC return only nonnull
877 // pointers. We may refute this as we analyze functions.
878 bool SCCReturnsNonNull = true;
879
880 bool MadeChange = false;
881
882 // Check each function in turn, determining which functions return nonnull
883 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000884 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000885 // Already nonnull.
886 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
887 Attribute::NonNull))
888 continue;
889
890 // Definitions with weak linkage may be overridden at linktime, so
891 // treat them like declarations.
892 if (F->isDeclaration() || F->mayBeOverridden())
893 return false;
894
Chandler Carruth63559d72015-09-13 06:47:20 +0000895 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +0000896 // pointer types.
897 if (!F->getReturnType()->isPointerTy())
898 continue;
899
900 bool Speculative = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000901 if (isReturnNonNull(F, SCCNodes, TLI, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000902 if (!Speculative) {
903 // Mark the function eagerly since we may discover a function
904 // which prevents us from speculating about the entire SCC
905 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
906 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
907 ++NumNonNullReturn;
908 MadeChange = true;
909 }
910 continue;
911 }
912 // At least one function returns something which could be null, can't
913 // speculate any more.
914 SCCReturnsNonNull = false;
915 }
916
917 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000918 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000919 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
920 Attribute::NonNull) ||
921 !F->getReturnType()->isPointerTy())
922 continue;
923
924 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
925 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
926 ++NumNonNullReturn;
927 MadeChange = true;
928 }
929 }
930
931 return MadeChange;
932}
933
James Molloy7e9bdd52015-11-12 10:55:20 +0000934static bool setDoesNotRecurse(Function &F) {
935 if (F.doesNotRecurse())
936 return false;
937 F.setDoesNotRecurse();
938 ++NumNoRecurse;
939 return true;
940}
941
Chandler Carruth1926b702016-01-08 10:55:52 +0000942static bool addNoRecurseAttrs(const CallGraphSCC &SCC) {
James Molloy7e9bdd52015-11-12 10:55:20 +0000943 // Try and identify functions that do not recurse.
944
945 // If the SCC contains multiple nodes we know for sure there is recursion.
946 if (!SCC.isSingular())
947 return false;
948
949 const CallGraphNode *CGN = *SCC.begin();
950 Function *F = CGN->getFunction();
951 if (!F || F->isDeclaration() || F->doesNotRecurse())
952 return false;
953
954 // If all of the calls in F are identifiable and are to norecurse functions, F
955 // is norecurse. This check also detects self-recursion as F is not currently
956 // marked norecurse, so any called from F to F will not be marked norecurse.
957 if (std::all_of(CGN->begin(), CGN->end(),
958 [](const CallGraphNode::CallRecord &CR) {
959 Function *F = CR.second->getFunction();
960 return F && F->doesNotRecurse();
961 }))
962 // Function calls a potentially recursive function.
963 return setDoesNotRecurse(*F);
964
Chandler Carruth1926b702016-01-08 10:55:52 +0000965 // Nothing else we can deduce usefully during the postorder traversal.
James Molloy7e9bdd52015-11-12 10:55:20 +0000966 return false;
967}
968
Chandler Carruth1926b702016-01-08 10:55:52 +0000969bool PostOrderFunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000970 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthcada2d82015-10-31 00:28:37 +0000971 bool Changed = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000972
Chandler Carrutha8125352015-10-30 16:48:08 +0000973 // We compute dedicated AA results for each function in the SCC as needed. We
974 // use a lambda referencing external objects so that they live long enough to
975 // be queried, but we re-use them each time.
976 Optional<BasicAAResult> BAR;
977 Optional<AAResults> AAR;
978 auto AARGetter = [&](Function &F) -> AAResults & {
979 BAR.emplace(createLegacyPMBasicAAResult(*this, F));
980 AAR.emplace(createLegacyPMAAResults(*this, F, *BAR));
981 return *AAR;
982 };
983
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000984 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
985 // whether a given CallGraphNode is in this SCC. Also track whether there are
986 // any external or opt-none nodes that will prevent us from optimizing any
987 // part of the SCC.
988 SCCNodeSet SCCNodes;
989 bool ExternalNode = false;
990 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
991 Function *F = (*I)->getFunction();
992 if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
993 // External node or function we're trying not to optimize - we both avoid
994 // transform them and avoid leveraging information they provide.
995 ExternalNode = true;
996 continue;
997 }
998
999 SCCNodes.insert(F);
1000 }
1001
Chandler Carrutha8125352015-10-30 16:48:08 +00001002 Changed |= addReadAttrs(SCCNodes, AARGetter);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001003 Changed |= addArgumentAttrs(SCCNodes);
1004
Chandler Carruth3a040e62015-12-27 08:41:34 +00001005 // If we have no external nodes participating in the SCC, we can deduce some
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001006 // more precise attributes as well.
1007 if (!ExternalNode) {
1008 Changed |= addNoAliasAttrs(SCCNodes);
1009 Changed |= addNonNullAttrs(SCCNodes, *TLI);
1010 }
Chandler Carruth1926b702016-01-08 10:55:52 +00001011
1012 Changed |= addNoRecurseAttrs(SCC);
James Molloy7e9bdd52015-11-12 10:55:20 +00001013 return Changed;
1014}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001015
Chandler Carruth1926b702016-01-08 10:55:52 +00001016namespace {
1017/// A pass to do RPO deduction and propagation of function attributes.
1018///
1019/// This pass provides a general RPO or "top down" propagation of
1020/// function attributes. For a few (rare) cases, we can deduce significantly
1021/// more about function attributes by working in RPO, so this pass
1022/// provides the compliment to the post-order pass above where the majority of
1023/// deduction is performed.
1024// FIXME: Currently there is no RPO CGSCC pass structure to slide into and so
1025// this is a boring module pass, but eventually it should be an RPO CGSCC pass
1026// when such infrastructure is available.
1027struct ReversePostOrderFunctionAttrs : public ModulePass {
1028 static char ID; // Pass identification, replacement for typeid
1029 ReversePostOrderFunctionAttrs() : ModulePass(ID) {
1030 initializeReversePostOrderFunctionAttrsPass(*PassRegistry::getPassRegistry());
1031 }
1032
1033 bool runOnModule(Module &M) override;
1034
1035 void getAnalysisUsage(AnalysisUsage &AU) const override {
1036 AU.setPreservesCFG();
1037 AU.addRequired<CallGraphWrapperPass>();
1038 }
1039};
1040}
1041
1042char ReversePostOrderFunctionAttrs::ID = 0;
1043INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrs, "rpo-functionattrs",
1044 "Deduce function attributes in RPO", false, false)
1045INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1046INITIALIZE_PASS_END(ReversePostOrderFunctionAttrs, "rpo-functionattrs",
1047 "Deduce function attributes in RPO", false, false)
1048
1049Pass *llvm::createReversePostOrderFunctionAttrsPass() {
1050 return new ReversePostOrderFunctionAttrs();
1051}
1052
1053static bool addNoRecurseAttrsTopDown(Function &F) {
1054 // We check the preconditions for the function prior to calling this to avoid
1055 // the cost of building up a reversible post-order list. We assert them here
1056 // to make sure none of the invariants this relies on were violated.
1057 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1058 assert(!F.doesNotRecurse() &&
1059 "This function has already been deduced as norecurs!");
1060 assert(F.hasInternalLinkage() &&
1061 "Can only do top-down deduction for internal linkage functions!");
1062
1063 // If F is internal and all of its uses are calls from a non-recursive
1064 // functions, then none of its calls could in fact recurse without going
1065 // through a function marked norecurse, and so we can mark this function too
1066 // as norecurse. Note that the uses must actually be calls -- otherwise
1067 // a pointer to this function could be returned from a norecurse function but
1068 // this function could be recursively (indirectly) called. Note that this
1069 // also detects if F is directly recursive as F is not yet marked as
1070 // a norecurse function.
1071 for (auto *U : F.users()) {
1072 auto *I = dyn_cast<Instruction>(U);
1073 if (!I)
1074 return false;
1075 CallSite CS(I);
1076 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1077 return false;
1078 }
1079 return setDoesNotRecurse(F);
1080}
1081
1082bool ReversePostOrderFunctionAttrs::runOnModule(Module &M) {
1083 // We only have a post-order SCC traversal (because SCCs are inherently
1084 // discovered in post-order), so we accumulate them in a vector and then walk
1085 // it in reverse. This is simpler than using the RPO iterator infrastructure
1086 // because we need to combine SCC detection and the PO walk of the call
1087 // graph. We can also cheat egregiously because we're primarily interested in
1088 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1089 // with multiple functions in them will clearly be recursive.
1090 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1091 SmallVector<Function *, 16> Worklist;
1092 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1093 if (I->size() != 1)
1094 continue;
1095
1096 Function *F = I->front()->getFunction();
1097 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1098 F->hasInternalLinkage())
1099 Worklist.push_back(F);
1100 }
1101
James Molloy7e9bdd52015-11-12 10:55:20 +00001102 bool Changed = false;
Chandler Carruth1926b702016-01-08 10:55:52 +00001103 for (auto *F : reverse(Worklist))
1104 Changed |= addNoRecurseAttrsTopDown(*F);
1105
Duncan Sands44c8cd92008-12-31 16:14:43 +00001106 return Changed;
1107}