FunctionAttrs.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. //===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===//
  2. //
  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. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements a simple interprocedural pass which walks the
  11. // call-graph, looking for functions which do not access or only read
  12. // non-local memory, and marking them readnone/readonly. In addition,
  13. // it marks function arguments (of pointer type) 'nocapture' if a call
  14. // to the function does not create any copies of the pointer value that
  15. // outlive the call. This more or less means that the pointer is only
  16. // dereferenced, and not returned from the function or stored in a global.
  17. // This pass is implemented as a bottom-up traversal of the call-graph.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #define DEBUG_TYPE "functionattrs"
  21. #include "llvm/Transforms/IPO.h"
  22. #include "llvm/ADT/SCCIterator.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/ADT/SmallSet.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/Analysis/AliasAnalysis.h"
  27. #include "llvm/Analysis/CallGraph.h"
  28. #include "llvm/Analysis/CaptureTracking.h"
  29. #include "llvm/CallGraphSCCPass.h"
  30. #include "llvm/GlobalVariable.h"
  31. #include "llvm/IntrinsicInst.h"
  32. #include "llvm/LLVMContext.h"
  33. #include "llvm/Support/InstIterator.h"
  34. using namespace llvm;
  35. STATISTIC(NumReadNone, "Number of functions marked readnone");
  36. STATISTIC(NumReadOnly, "Number of functions marked readonly");
  37. STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
  38. STATISTIC(NumNoAlias, "Number of function returns marked noalias");
  39. namespace {
  40. struct FunctionAttrs : public CallGraphSCCPass {
  41. static char ID; // Pass identification, replacement for typeid
  42. FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {
  43. initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
  44. }
  45. // runOnSCC - Analyze the SCC, performing the transformation if possible.
  46. bool runOnSCC(CallGraphSCC &SCC);
  47. // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
  48. bool AddReadAttrs(const CallGraphSCC &SCC);
  49. // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
  50. bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
  51. // IsFunctionMallocLike - Does this function allocate new memory?
  52. bool IsFunctionMallocLike(Function *F,
  53. SmallPtrSet<Function*, 8> &) const;
  54. // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
  55. bool AddNoAliasAttrs(const CallGraphSCC &SCC);
  56. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  57. AU.setPreservesCFG();
  58. AU.addRequired<AliasAnalysis>();
  59. CallGraphSCCPass::getAnalysisUsage(AU);
  60. }
  61. private:
  62. AliasAnalysis *AA;
  63. };
  64. }
  65. char FunctionAttrs::ID = 0;
  66. INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
  67. "Deduce function attributes", false, false)
  68. INITIALIZE_AG_DEPENDENCY(CallGraph)
  69. INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
  70. "Deduce function attributes", false, false)
  71. Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
  72. /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
  73. bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
  74. SmallPtrSet<Function*, 8> SCCNodes;
  75. // Fill SCCNodes with the elements of the SCC. Used for quickly
  76. // looking up whether a given CallGraphNode is in this SCC.
  77. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
  78. SCCNodes.insert((*I)->getFunction());
  79. // Check if any of the functions in the SCC read or write memory. If they
  80. // write memory then they can't be marked readnone or readonly.
  81. bool ReadsMemory = false;
  82. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
  83. Function *F = (*I)->getFunction();
  84. if (F == 0)
  85. // External node - may write memory. Just give up.
  86. return false;
  87. AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(F);
  88. if (MRB == AliasAnalysis::DoesNotAccessMemory)
  89. // Already perfect!
  90. continue;
  91. // Definitions with weak linkage may be overridden at linktime with
  92. // something that writes memory, so treat them like declarations.
  93. if (F->isDeclaration() || F->mayBeOverridden()) {
  94. if (!AliasAnalysis::onlyReadsMemory(MRB))
  95. // May write memory. Just give up.
  96. return false;
  97. ReadsMemory = true;
  98. continue;
  99. }
  100. // Scan the function body for instructions that may read or write memory.
  101. for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
  102. Instruction *I = &*II;
  103. // Some instructions can be ignored even if they read or write memory.
  104. // Detect these now, skipping to the next instruction if one is found.
  105. CallSite CS(cast<Value>(I));
  106. if (CS) {
  107. // Ignore calls to functions in the same SCC.
  108. if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
  109. continue;
  110. AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(CS);
  111. // If the call doesn't access arbitrary memory, we may be able to
  112. // figure out something.
  113. if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
  114. // If the call does access argument pointees, check each argument.
  115. if (AliasAnalysis::doesAccessArgPointees(MRB))
  116. // Check whether all pointer arguments point to local memory, and
  117. // ignore calls that only access local memory.
  118. for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
  119. CI != CE; ++CI) {
  120. Value *Arg = *CI;
  121. if (Arg->getType()->isPointerTy()) {
  122. AliasAnalysis::Location Loc(Arg,
  123. AliasAnalysis::UnknownSize,
  124. I->getMetadata(LLVMContext::MD_tbaa));
  125. if (!AA->pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
  126. if (MRB & AliasAnalysis::Mod)
  127. // Writes non-local memory. Give up.
  128. return false;
  129. if (MRB & AliasAnalysis::Ref)
  130. // Ok, it reads non-local memory.
  131. ReadsMemory = true;
  132. }
  133. }
  134. }
  135. continue;
  136. }
  137. // The call could access any memory. If that includes writes, give up.
  138. if (MRB & AliasAnalysis::Mod)
  139. return false;
  140. // If it reads, note it.
  141. if (MRB & AliasAnalysis::Ref)
  142. ReadsMemory = true;
  143. continue;
  144. } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  145. // Ignore non-volatile loads from local memory. (Atomic is okay here.)
  146. if (!LI->isVolatile()) {
  147. AliasAnalysis::Location Loc = AA->getLocation(LI);
  148. if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
  149. continue;
  150. }
  151. } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  152. // Ignore non-volatile stores to local memory. (Atomic is okay here.)
  153. if (!SI->isVolatile()) {
  154. AliasAnalysis::Location Loc = AA->getLocation(SI);
  155. if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
  156. continue;
  157. }
  158. } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
  159. // Ignore vaargs on local memory.
  160. AliasAnalysis::Location Loc = AA->getLocation(VI);
  161. if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
  162. continue;
  163. }
  164. // Any remaining instructions need to be taken seriously! Check if they
  165. // read or write memory.
  166. if (I->mayWriteToMemory())
  167. // Writes memory. Just give up.
  168. return false;
  169. // If this instruction may read memory, remember that.
  170. ReadsMemory |= I->mayReadFromMemory();
  171. }
  172. }
  173. // Success! Functions in this SCC do not access memory, or only read memory.
  174. // Give them the appropriate attribute.
  175. bool MadeChange = false;
  176. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
  177. Function *F = (*I)->getFunction();
  178. if (F->doesNotAccessMemory())
  179. // Already perfect!
  180. continue;
  181. if (F->onlyReadsMemory() && ReadsMemory)
  182. // No change.
  183. continue;
  184. MadeChange = true;
  185. // Clear out any existing attributes.
  186. AttrBuilder B;
  187. B.addAttribute(Attribute::ReadOnly)
  188. .addAttribute(Attribute::ReadNone);
  189. F->removeAttribute(AttributeSet::FunctionIndex,
  190. Attribute::get(F->getContext(), B));
  191. // Add in the new attribute.
  192. B.clear();
  193. B.addAttribute(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
  194. F->addAttribute(AttributeSet::FunctionIndex,
  195. Attribute::get(F->getContext(), B));
  196. if (ReadsMemory)
  197. ++NumReadOnly;
  198. else
  199. ++NumReadNone;
  200. }
  201. return MadeChange;
  202. }
  203. namespace {
  204. // For a given pointer Argument, this retains a list of Arguments of functions
  205. // in the same SCC that the pointer data flows into. We use this to build an
  206. // SCC of the arguments.
  207. struct ArgumentGraphNode {
  208. Argument *Definition;
  209. SmallVector<ArgumentGraphNode*, 4> Uses;
  210. };
  211. class ArgumentGraph {
  212. // We store pointers to ArgumentGraphNode objects, so it's important that
  213. // that they not move around upon insert.
  214. typedef std::map<Argument*, ArgumentGraphNode> ArgumentMapTy;
  215. ArgumentMapTy ArgumentMap;
  216. // There is no root node for the argument graph, in fact:
  217. // void f(int *x, int *y) { if (...) f(x, y); }
  218. // is an example where the graph is disconnected. The SCCIterator requires a
  219. // single entry point, so we maintain a fake ("synthetic") root node that
  220. // uses every node. Because the graph is directed and nothing points into
  221. // the root, it will not participate in any SCCs (except for its own).
  222. ArgumentGraphNode SyntheticRoot;
  223. public:
  224. ArgumentGraph() { SyntheticRoot.Definition = 0; }
  225. typedef SmallVectorImpl<ArgumentGraphNode*>::iterator iterator;
  226. iterator begin() { return SyntheticRoot.Uses.begin(); }
  227. iterator end() { return SyntheticRoot.Uses.end(); }
  228. ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
  229. ArgumentGraphNode *operator[](Argument *A) {
  230. ArgumentGraphNode &Node = ArgumentMap[A];
  231. Node.Definition = A;
  232. SyntheticRoot.Uses.push_back(&Node);
  233. return &Node;
  234. }
  235. };
  236. // This tracker checks whether callees are in the SCC, and if so it does not
  237. // consider that a capture, instead adding it to the "Uses" list and
  238. // continuing with the analysis.
  239. struct ArgumentUsesTracker : public CaptureTracker {
  240. ArgumentUsesTracker(const SmallPtrSet<Function*, 8> &SCCNodes)
  241. : Captured(false), SCCNodes(SCCNodes) {}
  242. void tooManyUses() { Captured = true; }
  243. bool captured(Use *U) {
  244. CallSite CS(U->getUser());
  245. if (!CS.getInstruction()) { Captured = true; return true; }
  246. Function *F = CS.getCalledFunction();
  247. if (!F || !SCCNodes.count(F)) { Captured = true; return true; }
  248. Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
  249. for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
  250. PI != PE; ++PI, ++AI) {
  251. if (AI == AE) {
  252. assert(F->isVarArg() && "More params than args in non-varargs call");
  253. Captured = true;
  254. return true;
  255. }
  256. if (PI == U) {
  257. Uses.push_back(AI);
  258. break;
  259. }
  260. }
  261. assert(!Uses.empty() && "Capturing call-site captured nothing?");
  262. return false;
  263. }
  264. bool Captured; // True only if certainly captured (used outside our SCC).
  265. SmallVector<Argument*, 4> Uses; // Uses within our SCC.
  266. const SmallPtrSet<Function*, 8> &SCCNodes;
  267. };
  268. }
  269. namespace llvm {
  270. template<> struct GraphTraits<ArgumentGraphNode*> {
  271. typedef ArgumentGraphNode NodeType;
  272. typedef SmallVectorImpl<ArgumentGraphNode*>::iterator ChildIteratorType;
  273. static inline NodeType *getEntryNode(NodeType *A) { return A; }
  274. static inline ChildIteratorType child_begin(NodeType *N) {
  275. return N->Uses.begin();
  276. }
  277. static inline ChildIteratorType child_end(NodeType *N) {
  278. return N->Uses.end();
  279. }
  280. };
  281. template<> struct GraphTraits<ArgumentGraph*>
  282. : public GraphTraits<ArgumentGraphNode*> {
  283. static NodeType *getEntryNode(ArgumentGraph *AG) {
  284. return AG->getEntryNode();
  285. }
  286. static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
  287. return AG->begin();
  288. }
  289. static ChildIteratorType nodes_end(ArgumentGraph *AG) {
  290. return AG->end();
  291. }
  292. };
  293. }
  294. /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
  295. bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
  296. bool Changed = false;
  297. SmallPtrSet<Function*, 8> SCCNodes;
  298. // Fill SCCNodes with the elements of the SCC. Used for quickly
  299. // looking up whether a given CallGraphNode is in this SCC.
  300. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
  301. Function *F = (*I)->getFunction();
  302. if (F && !F->isDeclaration() && !F->mayBeOverridden())
  303. SCCNodes.insert(F);
  304. }
  305. ArgumentGraph AG;
  306. AttrBuilder B;
  307. B.addAttribute(Attribute::NoCapture);
  308. // Check each function in turn, determining which pointer arguments are not
  309. // captured.
  310. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
  311. Function *F = (*I)->getFunction();
  312. if (F == 0)
  313. // External node - only a problem for arguments that we pass to it.
  314. continue;
  315. // Definitions with weak linkage may be overridden at linktime with
  316. // something that captures pointers, so treat them like declarations.
  317. if (F->isDeclaration() || F->mayBeOverridden())
  318. continue;
  319. // Functions that are readonly (or readnone) and nounwind and don't return
  320. // a value can't capture arguments. Don't analyze them.
  321. if (F->onlyReadsMemory() && F->doesNotThrow() &&
  322. F->getReturnType()->isVoidTy()) {
  323. for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end();
  324. A != E; ++A) {
  325. if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
  326. A->addAttr(Attribute::get(F->getContext(), B));
  327. ++NumNoCapture;
  328. Changed = true;
  329. }
  330. }
  331. continue;
  332. }
  333. for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
  334. if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
  335. ArgumentUsesTracker Tracker(SCCNodes);
  336. PointerMayBeCaptured(A, &Tracker);
  337. if (!Tracker.Captured) {
  338. if (Tracker.Uses.empty()) {
  339. // If it's trivially not captured, mark it nocapture now.
  340. A->addAttr(Attribute::get(F->getContext(), B));
  341. ++NumNoCapture;
  342. Changed = true;
  343. } else {
  344. // If it's not trivially captured and not trivially not captured,
  345. // then it must be calling into another function in our SCC. Save
  346. // its particulars for Argument-SCC analysis later.
  347. ArgumentGraphNode *Node = AG[A];
  348. for (SmallVectorImpl<Argument*>::iterator UI = Tracker.Uses.begin(),
  349. UE = Tracker.Uses.end(); UI != UE; ++UI)
  350. Node->Uses.push_back(AG[*UI]);
  351. }
  352. }
  353. // Otherwise, it's captured. Don't bother doing SCC analysis on it.
  354. }
  355. }
  356. // The graph we've collected is partial because we stopped scanning for
  357. // argument uses once we solved the argument trivially. These partial nodes
  358. // show up as ArgumentGraphNode objects with an empty Uses list, and for
  359. // these nodes the final decision about whether they capture has already been
  360. // made. If the definition doesn't have a 'nocapture' attribute by now, it
  361. // captures.
  362. for (scc_iterator<ArgumentGraph*> I = scc_begin(&AG), E = scc_end(&AG);
  363. I != E; ++I) {
  364. std::vector<ArgumentGraphNode*> &ArgumentSCC = *I;
  365. if (ArgumentSCC.size() == 1) {
  366. if (!ArgumentSCC[0]->Definition) continue; // synthetic root node
  367. // eg. "void f(int* x) { if (...) f(x); }"
  368. if (ArgumentSCC[0]->Uses.size() == 1 &&
  369. ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
  370. ArgumentSCC[0]->
  371. Definition->
  372. addAttr(Attribute::get(ArgumentSCC[0]->Definition->getContext(), B));
  373. ++NumNoCapture;
  374. Changed = true;
  375. }
  376. continue;
  377. }
  378. bool SCCCaptured = false;
  379. for (std::vector<ArgumentGraphNode*>::iterator I = ArgumentSCC.begin(),
  380. E = ArgumentSCC.end(); I != E && !SCCCaptured; ++I) {
  381. ArgumentGraphNode *Node = *I;
  382. if (Node->Uses.empty()) {
  383. if (!Node->Definition->hasNoCaptureAttr())
  384. SCCCaptured = true;
  385. }
  386. }
  387. if (SCCCaptured) continue;
  388. SmallPtrSet<Argument*, 8> ArgumentSCCNodes;
  389. // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
  390. // quickly looking up whether a given Argument is in this ArgumentSCC.
  391. for (std::vector<ArgumentGraphNode*>::iterator I = ArgumentSCC.begin(),
  392. E = ArgumentSCC.end(); I != E; ++I) {
  393. ArgumentSCCNodes.insert((*I)->Definition);
  394. }
  395. for (std::vector<ArgumentGraphNode*>::iterator I = ArgumentSCC.begin(),
  396. E = ArgumentSCC.end(); I != E && !SCCCaptured; ++I) {
  397. ArgumentGraphNode *N = *I;
  398. for (SmallVectorImpl<ArgumentGraphNode*>::iterator UI = N->Uses.begin(),
  399. UE = N->Uses.end(); UI != UE; ++UI) {
  400. Argument *A = (*UI)->Definition;
  401. if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
  402. continue;
  403. SCCCaptured = true;
  404. break;
  405. }
  406. }
  407. if (SCCCaptured) continue;
  408. for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
  409. Argument *A = ArgumentSCC[i]->Definition;
  410. A->addAttr(Attribute::get(A->getContext(), B));
  411. ++NumNoCapture;
  412. Changed = true;
  413. }
  414. }
  415. return Changed;
  416. }
  417. /// IsFunctionMallocLike - A function is malloc-like if it returns either null
  418. /// or a pointer that doesn't alias any other pointer visible to the caller.
  419. bool FunctionAttrs::IsFunctionMallocLike(Function *F,
  420. SmallPtrSet<Function*, 8> &SCCNodes) const {
  421. SmallSetVector<Value *, 8> FlowsToReturn;
  422. for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
  423. if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
  424. FlowsToReturn.insert(Ret->getReturnValue());
  425. for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
  426. Value *RetVal = FlowsToReturn[i];
  427. if (Constant *C = dyn_cast<Constant>(RetVal)) {
  428. if (!C->isNullValue() && !isa<UndefValue>(C))
  429. return false;
  430. continue;
  431. }
  432. if (isa<Argument>(RetVal))
  433. return false;
  434. if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
  435. switch (RVI->getOpcode()) {
  436. // Extend the analysis by looking upwards.
  437. case Instruction::BitCast:
  438. case Instruction::GetElementPtr:
  439. FlowsToReturn.insert(RVI->getOperand(0));
  440. continue;
  441. case Instruction::Select: {
  442. SelectInst *SI = cast<SelectInst>(RVI);
  443. FlowsToReturn.insert(SI->getTrueValue());
  444. FlowsToReturn.insert(SI->getFalseValue());
  445. continue;
  446. }
  447. case Instruction::PHI: {
  448. PHINode *PN = cast<PHINode>(RVI);
  449. for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  450. FlowsToReturn.insert(PN->getIncomingValue(i));
  451. continue;
  452. }
  453. // Check whether the pointer came from an allocation.
  454. case Instruction::Alloca:
  455. break;
  456. case Instruction::Call:
  457. case Instruction::Invoke: {
  458. CallSite CS(RVI);
  459. if (CS.paramHasAttr(0, Attribute::NoAlias))
  460. break;
  461. if (CS.getCalledFunction() &&
  462. SCCNodes.count(CS.getCalledFunction()))
  463. break;
  464. } // fall-through
  465. default:
  466. return false; // Did not come from an allocation.
  467. }
  468. if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
  469. return false;
  470. }
  471. return true;
  472. }
  473. /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
  474. bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
  475. SmallPtrSet<Function*, 8> SCCNodes;
  476. // Fill SCCNodes with the elements of the SCC. Used for quickly
  477. // looking up whether a given CallGraphNode is in this SCC.
  478. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
  479. SCCNodes.insert((*I)->getFunction());
  480. // Check each function in turn, determining which functions return noalias
  481. // pointers.
  482. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
  483. Function *F = (*I)->getFunction();
  484. if (F == 0)
  485. // External node - skip it;
  486. return false;
  487. // Already noalias.
  488. if (F->doesNotAlias(0))
  489. continue;
  490. // Definitions with weak linkage may be overridden at linktime, so
  491. // treat them like declarations.
  492. if (F->isDeclaration() || F->mayBeOverridden())
  493. return false;
  494. // We annotate noalias return values, which are only applicable to
  495. // pointer types.
  496. if (!F->getReturnType()->isPointerTy())
  497. continue;
  498. if (!IsFunctionMallocLike(F, SCCNodes))
  499. return false;
  500. }
  501. bool MadeChange = false;
  502. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
  503. Function *F = (*I)->getFunction();
  504. if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
  505. continue;
  506. F->setDoesNotAlias(0);
  507. ++NumNoAlias;
  508. MadeChange = true;
  509. }
  510. return MadeChange;
  511. }
  512. bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
  513. AA = &getAnalysis<AliasAnalysis>();
  514. bool Changed = AddReadAttrs(SCC);
  515. Changed |= AddNoCaptureAttrs(SCC);
  516. Changed |= AddNoAliasAttrs(SCC);
  517. return Changed;
  518. }