1 //===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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. It does the
13 // same with function arguments independently, marking them readonly/
14 // readnone/nocapture. Finally, well-known library call declarations
15 // are marked with all attributes that are consistent with the
16 // function's standard definition. This pass is implemented as a
17 // bottom-up traversal of the call-graph.
19 //===----------------------------------------------------------------------===//
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/AssumptionCache.h"
28 #include "llvm/Analysis/BasicAliasAnalysis.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Analysis/CallGraphSCCPass.h"
31 #include "llvm/Analysis/CaptureTracking.h"
32 #include "llvm/Analysis/TargetLibraryInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/InstIterator.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Analysis/TargetLibraryInfo.h"
43 #define DEBUG_TYPE "functionattrs"
45 STATISTIC(NumReadNone, "Number of functions marked readnone");
46 STATISTIC(NumReadOnly, "Number of functions marked readonly");
47 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
48 STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
49 STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
50 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
51 STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
52 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
55 typedef SmallSetVector<Function *, 8> SCCNodeSet;
59 struct FunctionAttrs : public CallGraphSCCPass {
60 static char ID; // Pass identification, replacement for typeid
61 FunctionAttrs() : CallGraphSCCPass(ID) {
62 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
65 bool runOnSCC(CallGraphSCC &SCC) override;
67 void getAnalysisUsage(AnalysisUsage &AU) const override {
69 AU.addRequired<AssumptionCacheTracker>();
70 AU.addRequired<TargetLibraryInfoWrapperPass>();
71 CallGraphSCCPass::getAnalysisUsage(AU);
75 TargetLibraryInfo *TLI;
79 char FunctionAttrs::ID = 0;
80 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
81 "Deduce function attributes", false, false)
82 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
83 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
84 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
85 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
86 "Deduce function attributes", false, false)
88 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
91 /// The three kinds of memory access relevant to 'readonly' and
92 /// 'readnone' attributes.
93 enum MemoryAccessKind {
100 static MemoryAccessKind checkFunctionMemoryAccess(Function &F, AAResults &AAR,
101 const SCCNodeSet &SCCNodes) {
102 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
103 if (MRB == FMRB_DoesNotAccessMemory)
107 // Definitions with weak linkage may be overridden at linktime with
108 // something that writes memory, so treat them like declarations.
109 if (F.isDeclaration() || F.mayBeOverridden()) {
110 if (AliasAnalysis::onlyReadsMemory(MRB))
113 // Conservatively assume it writes to memory.
117 // Scan the function body for instructions that may read or write memory.
118 bool ReadsMemory = false;
119 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
120 Instruction *I = &*II;
122 // Some instructions can be ignored even if they read or write memory.
123 // Detect these now, skipping to the next instruction if one is found.
124 CallSite CS(cast<Value>(I));
126 // Ignore calls to functions in the same SCC.
127 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
129 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
131 // If the call doesn't access memory, we're done.
132 if (!(MRB & MRI_ModRef))
135 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
136 // The call could access any memory. If that includes writes, give up.
139 // If it reads, note it.
145 // Check whether all pointer arguments point to local memory, and
146 // ignore calls that only access local memory.
147 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
150 if (!Arg->getType()->isPointerTy())
154 I->getAAMetadata(AAInfo);
155 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
157 // Skip accesses to local or constant memory as they don't impact the
158 // externally visible mod/ref behavior.
159 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
163 // Writes non-local memory. Give up.
166 // Ok, it reads non-local memory.
170 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
171 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
172 if (!LI->isVolatile()) {
173 MemoryLocation Loc = MemoryLocation::get(LI);
174 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
177 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
178 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
179 if (!SI->isVolatile()) {
180 MemoryLocation Loc = MemoryLocation::get(SI);
181 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
184 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
185 // Ignore vaargs on local memory.
186 MemoryLocation Loc = MemoryLocation::get(VI);
187 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
191 // Any remaining instructions need to be taken seriously! Check if they
192 // read or write memory.
193 if (I->mayWriteToMemory())
194 // Writes memory. Just give up.
197 // If this instruction may read memory, remember that.
198 ReadsMemory |= I->mayReadFromMemory();
201 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
204 /// Deduce readonly/readnone attributes for the SCC.
205 template <typename AARGetterT>
206 static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT AARGetter) {
207 // Check if any of the functions in the SCC read or write memory. If they
208 // write memory then they can't be marked readnone or readonly.
209 bool ReadsMemory = false;
210 for (Function *F : SCCNodes) {
211 // Call the callable parameter to look up AA results for this function.
212 AAResults &AAR = AARGetter(*F);
214 switch (checkFunctionMemoryAccess(*F, AAR, SCCNodes)) {
226 // Success! Functions in this SCC do not access memory, or only read memory.
227 // Give them the appropriate attribute.
228 bool MadeChange = false;
229 for (Function *F : SCCNodes) {
230 if (F->doesNotAccessMemory())
234 if (F->onlyReadsMemory() && ReadsMemory)
240 // Clear out any existing attributes.
242 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
244 AttributeSet::FunctionIndex,
245 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
247 // Add in the new attribute.
248 F->addAttribute(AttributeSet::FunctionIndex,
249 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
261 /// For a given pointer Argument, this retains a list of Arguments of functions
262 /// in the same SCC that the pointer data flows into. We use this to build an
263 /// SCC of the arguments.
264 struct ArgumentGraphNode {
265 Argument *Definition;
266 SmallVector<ArgumentGraphNode *, 4> Uses;
269 class ArgumentGraph {
270 // We store pointers to ArgumentGraphNode objects, so it's important that
271 // that they not move around upon insert.
272 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
274 ArgumentMapTy ArgumentMap;
276 // There is no root node for the argument graph, in fact:
277 // void f(int *x, int *y) { if (...) f(x, y); }
278 // is an example where the graph is disconnected. The SCCIterator requires a
279 // single entry point, so we maintain a fake ("synthetic") root node that
280 // uses every node. Because the graph is directed and nothing points into
281 // the root, it will not participate in any SCCs (except for its own).
282 ArgumentGraphNode SyntheticRoot;
285 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
287 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
289 iterator begin() { return SyntheticRoot.Uses.begin(); }
290 iterator end() { return SyntheticRoot.Uses.end(); }
291 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
293 ArgumentGraphNode *operator[](Argument *A) {
294 ArgumentGraphNode &Node = ArgumentMap[A];
296 SyntheticRoot.Uses.push_back(&Node);
301 /// This tracker checks whether callees are in the SCC, and if so it does not
302 /// consider that a capture, instead adding it to the "Uses" list and
303 /// continuing with the analysis.
304 struct ArgumentUsesTracker : public CaptureTracker {
305 ArgumentUsesTracker(const SCCNodeSet &SCCNodes)
306 : Captured(false), SCCNodes(SCCNodes) {}
308 void tooManyUses() override { Captured = true; }
310 bool captured(const Use *U) override {
311 CallSite CS(U->getUser());
312 if (!CS.getInstruction()) {
317 Function *F = CS.getCalledFunction();
318 if (!F || F->isDeclaration() || F->mayBeOverridden() ||
319 !SCCNodes.count(F)) {
324 // Note: the callee and the two successor blocks *follow* the argument
325 // operands. This means there is no need to adjust UseIndex to account for
329 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
331 assert(UseIndex < CS.data_operands_size() &&
332 "Indirect function calls should have been filtered above!");
334 if (UseIndex >= CS.getNumArgOperands()) {
335 // Data operand, but not a argument operand -- must be a bundle operand
336 assert(CS.hasOperandBundles() && "Must be!");
338 // CaptureTracking told us that we're being captured by an operand bundle
339 // use. In this case it does not matter if the callee is within our SCC
340 // or not -- we've been captured in some unknown way, and we have to be
346 if (UseIndex >= F->arg_size()) {
347 assert(F->isVarArg() && "More params than args in non-varargs call");
352 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
356 bool Captured; // True only if certainly captured (used outside our SCC).
357 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
359 const SCCNodeSet &SCCNodes;
364 template <> struct GraphTraits<ArgumentGraphNode *> {
365 typedef ArgumentGraphNode NodeType;
366 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
368 static inline NodeType *getEntryNode(NodeType *A) { return A; }
369 static inline ChildIteratorType child_begin(NodeType *N) {
370 return N->Uses.begin();
372 static inline ChildIteratorType child_end(NodeType *N) {
373 return N->Uses.end();
377 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
378 static NodeType *getEntryNode(ArgumentGraph *AG) {
379 return AG->getEntryNode();
381 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
384 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
388 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
389 static Attribute::AttrKind
390 determinePointerReadAttrs(Argument *A,
391 const SmallPtrSet<Argument *, 8> &SCCNodes) {
393 SmallVector<Use *, 32> Worklist;
394 SmallSet<Use *, 32> Visited;
396 // inalloca arguments are always clobbered by the call.
397 if (A->hasInAllocaAttr())
398 return Attribute::None;
401 // We don't need to track IsWritten. If A is written to, return immediately.
403 for (Use &U : A->uses()) {
405 Worklist.push_back(&U);
408 while (!Worklist.empty()) {
409 Use *U = Worklist.pop_back_val();
410 Instruction *I = cast<Instruction>(U->getUser());
412 switch (I->getOpcode()) {
413 case Instruction::BitCast:
414 case Instruction::GetElementPtr:
415 case Instruction::PHI:
416 case Instruction::Select:
417 case Instruction::AddrSpaceCast:
418 // The original value is not read/written via this if the new value isn't.
419 for (Use &UU : I->uses())
420 if (Visited.insert(&UU).second)
421 Worklist.push_back(&UU);
424 case Instruction::Call:
425 case Instruction::Invoke: {
426 bool Captures = true;
428 if (I->getType()->isVoidTy())
431 auto AddUsersToWorklistIfCapturing = [&] {
433 for (Use &UU : I->uses())
434 if (Visited.insert(&UU).second)
435 Worklist.push_back(&UU);
439 if (CS.doesNotAccessMemory()) {
440 AddUsersToWorklistIfCapturing();
444 Function *F = CS.getCalledFunction();
446 if (CS.onlyReadsMemory()) {
448 AddUsersToWorklistIfCapturing();
451 return Attribute::None;
454 // Note: the callee and the two successor blocks *follow* the argument
455 // operands. This means there is no need to adjust UseIndex to account
458 unsigned UseIndex = std::distance(CS.arg_begin(), U);
460 assert(UseIndex < CS.data_operands_size() && "Non-argument use?");
462 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
464 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
465 assert(F->isVarArg() && "More params than args in non-varargs call");
466 return Attribute::None;
469 Captures &= !CS.doesNotCapture(UseIndex);
471 // Since the optimizer (by design) cannot see the data flow corresponding
472 // to a operand bundle use, these cannot participate in the optimistic SCC
473 // analysis. Instead, we model the operand bundle uses as arguments in
474 // call to a function external to the SCC.
475 if (!SCCNodes.count(std::next(F->arg_begin(), UseIndex)) ||
476 IsOperandBundleUse) {
478 // The accessors used on CallSite here do the right thing for calls and
479 // invokes with operand bundles.
481 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
482 return Attribute::None;
483 if (!CS.doesNotAccessMemory(UseIndex))
487 AddUsersToWorklistIfCapturing();
491 case Instruction::Load:
495 case Instruction::ICmp:
496 case Instruction::Ret:
500 return Attribute::None;
504 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
507 /// Deduce nocapture attributes for the SCC.
508 static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
509 bool Changed = false;
514 B.addAttribute(Attribute::NoCapture);
516 // Check each function in turn, determining which pointer arguments are not
518 for (Function *F : SCCNodes) {
519 // Definitions with weak linkage may be overridden at linktime with
520 // something that captures pointers, so treat them like declarations.
521 if (F->isDeclaration() || F->mayBeOverridden())
524 // Functions that are readonly (or readnone) and nounwind and don't return
525 // a value can't capture arguments. Don't analyze them.
526 if (F->onlyReadsMemory() && F->doesNotThrow() &&
527 F->getReturnType()->isVoidTy()) {
528 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
530 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
531 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
539 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
541 if (!A->getType()->isPointerTy())
543 bool HasNonLocalUses = false;
544 if (!A->hasNoCaptureAttr()) {
545 ArgumentUsesTracker Tracker(SCCNodes);
546 PointerMayBeCaptured(&*A, &Tracker);
547 if (!Tracker.Captured) {
548 if (Tracker.Uses.empty()) {
549 // If it's trivially not captured, mark it nocapture now.
551 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
555 // If it's not trivially captured and not trivially not captured,
556 // then it must be calling into another function in our SCC. Save
557 // its particulars for Argument-SCC analysis later.
558 ArgumentGraphNode *Node = AG[&*A];
559 for (SmallVectorImpl<Argument *>::iterator
560 UI = Tracker.Uses.begin(),
561 UE = Tracker.Uses.end();
563 Node->Uses.push_back(AG[*UI]);
565 HasNonLocalUses = true;
569 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
571 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
572 // Can we determine that it's readonly/readnone without doing an SCC?
573 // Note that we don't allow any calls at all here, or else our result
574 // will be dependent on the iteration order through the functions in the
576 SmallPtrSet<Argument *, 8> Self;
578 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
579 if (R != Attribute::None) {
582 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
584 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
590 // The graph we've collected is partial because we stopped scanning for
591 // argument uses once we solved the argument trivially. These partial nodes
592 // show up as ArgumentGraphNode objects with an empty Uses list, and for
593 // these nodes the final decision about whether they capture has already been
594 // made. If the definition doesn't have a 'nocapture' attribute by now, it
597 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
598 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
599 if (ArgumentSCC.size() == 1) {
600 if (!ArgumentSCC[0]->Definition)
601 continue; // synthetic root node
603 // eg. "void f(int* x) { if (...) f(x); }"
604 if (ArgumentSCC[0]->Uses.size() == 1 &&
605 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
606 Argument *A = ArgumentSCC[0]->Definition;
607 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
614 bool SCCCaptured = false;
615 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
616 I != E && !SCCCaptured; ++I) {
617 ArgumentGraphNode *Node = *I;
618 if (Node->Uses.empty()) {
619 if (!Node->Definition->hasNoCaptureAttr())
626 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
627 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
628 // quickly looking up whether a given Argument is in this ArgumentSCC.
629 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
630 ArgumentSCCNodes.insert((*I)->Definition);
633 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
634 I != E && !SCCCaptured; ++I) {
635 ArgumentGraphNode *N = *I;
636 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
639 Argument *A = (*UI)->Definition;
640 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
649 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
650 Argument *A = ArgumentSCC[i]->Definition;
651 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
656 // We also want to compute readonly/readnone. With a small number of false
657 // negatives, we can assume that any pointer which is captured isn't going
658 // to be provably readonly or readnone, since by definition we can't
659 // analyze all uses of a captured pointer.
661 // The false negatives happen when the pointer is captured by a function
662 // that promises readonly/readnone behaviour on the pointer, then the
663 // pointer's lifetime ends before anything that writes to arbitrary memory.
664 // Also, a readonly/readnone pointer may be returned, but returning a
665 // pointer is capturing it.
667 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
668 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
669 Argument *A = ArgumentSCC[i]->Definition;
670 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
671 if (K == Attribute::ReadNone)
673 if (K == Attribute::ReadOnly) {
674 ReadAttr = Attribute::ReadOnly;
681 if (ReadAttr != Attribute::None) {
683 B.addAttribute(ReadAttr);
684 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
685 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
686 Argument *A = ArgumentSCC[i]->Definition;
687 // Clear out existing readonly/readnone attributes
688 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
689 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
690 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
699 /// Tests whether a function is "malloc-like".
701 /// A function is "malloc-like" if it returns either null or a pointer that
702 /// doesn't alias any other pointer visible to the caller.
703 static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
704 SmallSetVector<Value *, 8> FlowsToReturn;
705 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
706 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
707 FlowsToReturn.insert(Ret->getReturnValue());
709 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
710 Value *RetVal = FlowsToReturn[i];
712 if (Constant *C = dyn_cast<Constant>(RetVal)) {
713 if (!C->isNullValue() && !isa<UndefValue>(C))
719 if (isa<Argument>(RetVal))
722 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
723 switch (RVI->getOpcode()) {
724 // Extend the analysis by looking upwards.
725 case Instruction::BitCast:
726 case Instruction::GetElementPtr:
727 case Instruction::AddrSpaceCast:
728 FlowsToReturn.insert(RVI->getOperand(0));
730 case Instruction::Select: {
731 SelectInst *SI = cast<SelectInst>(RVI);
732 FlowsToReturn.insert(SI->getTrueValue());
733 FlowsToReturn.insert(SI->getFalseValue());
736 case Instruction::PHI: {
737 PHINode *PN = cast<PHINode>(RVI);
738 for (Value *IncValue : PN->incoming_values())
739 FlowsToReturn.insert(IncValue);
743 // Check whether the pointer came from an allocation.
744 case Instruction::Alloca:
746 case Instruction::Call:
747 case Instruction::Invoke: {
749 if (CS.paramHasAttr(0, Attribute::NoAlias))
751 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
755 return false; // Did not come from an allocation.
758 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
765 /// Deduce noalias attributes for the SCC.
766 static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
767 // Check each function in turn, determining which functions return noalias
769 for (Function *F : SCCNodes) {
771 if (F->doesNotAlias(0))
774 // Definitions with weak linkage may be overridden at linktime, so
775 // treat them like declarations.
776 if (F->isDeclaration() || F->mayBeOverridden())
779 // We annotate noalias return values, which are only applicable to
781 if (!F->getReturnType()->isPointerTy())
784 if (!isFunctionMallocLike(F, SCCNodes))
788 bool MadeChange = false;
789 for (Function *F : SCCNodes) {
790 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
793 F->setDoesNotAlias(0);
801 /// Tests whether this function is known to not return null.
803 /// Requires that the function returns a pointer.
805 /// Returns true if it believes the function will not return a null, and sets
806 /// \p Speculative based on whether the returned conclusion is a speculative
807 /// conclusion due to SCC calls.
808 static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
809 const TargetLibraryInfo &TLI, bool &Speculative) {
810 assert(F->getReturnType()->isPointerTy() &&
811 "nonnull only meaningful on pointer types");
814 SmallSetVector<Value *, 8> FlowsToReturn;
815 for (BasicBlock &BB : *F)
816 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
817 FlowsToReturn.insert(Ret->getReturnValue());
819 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
820 Value *RetVal = FlowsToReturn[i];
822 // If this value is locally known to be non-null, we're good
823 if (isKnownNonNull(RetVal, &TLI))
826 // Otherwise, we need to look upwards since we can't make any local
828 Instruction *RVI = dyn_cast<Instruction>(RetVal);
831 switch (RVI->getOpcode()) {
832 // Extend the analysis by looking upwards.
833 case Instruction::BitCast:
834 case Instruction::GetElementPtr:
835 case Instruction::AddrSpaceCast:
836 FlowsToReturn.insert(RVI->getOperand(0));
838 case Instruction::Select: {
839 SelectInst *SI = cast<SelectInst>(RVI);
840 FlowsToReturn.insert(SI->getTrueValue());
841 FlowsToReturn.insert(SI->getFalseValue());
844 case Instruction::PHI: {
845 PHINode *PN = cast<PHINode>(RVI);
846 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
847 FlowsToReturn.insert(PN->getIncomingValue(i));
850 case Instruction::Call:
851 case Instruction::Invoke: {
853 Function *Callee = CS.getCalledFunction();
854 // A call to a node within the SCC is assumed to return null until
856 if (Callee && SCCNodes.count(Callee)) {
863 return false; // Unknown source, may be null
865 llvm_unreachable("should have either continued or returned");
871 /// Deduce nonnull attributes for the SCC.
872 static bool addNonNullAttrs(const SCCNodeSet &SCCNodes,
873 const TargetLibraryInfo &TLI) {
874 // Speculative that all functions in the SCC return only nonnull
875 // pointers. We may refute this as we analyze functions.
876 bool SCCReturnsNonNull = true;
878 bool MadeChange = false;
880 // Check each function in turn, determining which functions return nonnull
882 for (Function *F : SCCNodes) {
884 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
888 // Definitions with weak linkage may be overridden at linktime, so
889 // treat them like declarations.
890 if (F->isDeclaration() || F->mayBeOverridden())
893 // We annotate nonnull return values, which are only applicable to
895 if (!F->getReturnType()->isPointerTy())
898 bool Speculative = false;
899 if (isReturnNonNull(F, SCCNodes, TLI, Speculative)) {
901 // Mark the function eagerly since we may discover a function
902 // which prevents us from speculating about the entire SCC
903 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
904 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
910 // At least one function returns something which could be null, can't
911 // speculate any more.
912 SCCReturnsNonNull = false;
915 if (SCCReturnsNonNull) {
916 for (Function *F : SCCNodes) {
917 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
918 Attribute::NonNull) ||
919 !F->getReturnType()->isPointerTy())
922 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
923 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
932 static void setDoesNotAccessMemory(Function &F) {
933 if (!F.doesNotAccessMemory()) {
934 F.setDoesNotAccessMemory();
939 static void setOnlyReadsMemory(Function &F) {
940 if (!F.onlyReadsMemory()) {
941 F.setOnlyReadsMemory();
946 static void setDoesNotThrow(Function &F) {
947 if (!F.doesNotThrow()) {
953 static void setDoesNotCapture(Function &F, unsigned n) {
954 if (!F.doesNotCapture(n)) {
955 F.setDoesNotCapture(n);
960 static void setOnlyReadsMemory(Function &F, unsigned n) {
961 if (!F.onlyReadsMemory(n)) {
962 F.setOnlyReadsMemory(n);
967 static void setDoesNotAlias(Function &F, unsigned n) {
968 if (!F.doesNotAlias(n)) {
969 F.setDoesNotAlias(n);
974 /// Analyze the name and prototype of the given function and set any applicable
977 /// Returns true if any attributes were set and false otherwise.
978 static bool inferPrototypeAttributes(Function &F, const TargetLibraryInfo &TLI) {
979 if (F.hasFnAttribute(Attribute::OptimizeNone))
982 FunctionType *FTy = F.getFunctionType();
983 LibFunc::Func TheLibFunc;
984 if (!(TLI.getLibFunc(F.getName(), TheLibFunc) && TLI.has(TheLibFunc)))
987 switch (TheLibFunc) {
988 case LibFunc::strlen:
989 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
991 setOnlyReadsMemory(F);
993 setDoesNotCapture(F, 1);
995 case LibFunc::strchr:
996 case LibFunc::strrchr:
997 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
998 !FTy->getParamType(1)->isIntegerTy())
1000 setOnlyReadsMemory(F);
1003 case LibFunc::strtol:
1004 case LibFunc::strtod:
1005 case LibFunc::strtof:
1006 case LibFunc::strtoul:
1007 case LibFunc::strtoll:
1008 case LibFunc::strtold:
1009 case LibFunc::strtoull:
1010 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1013 setDoesNotCapture(F, 2);
1014 setOnlyReadsMemory(F, 1);
1016 case LibFunc::strcpy:
1017 case LibFunc::stpcpy:
1018 case LibFunc::strcat:
1019 case LibFunc::strncat:
1020 case LibFunc::strncpy:
1021 case LibFunc::stpncpy:
1022 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1025 setDoesNotCapture(F, 2);
1026 setOnlyReadsMemory(F, 2);
1028 case LibFunc::strxfrm:
1029 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1030 !FTy->getParamType(1)->isPointerTy())
1033 setDoesNotCapture(F, 1);
1034 setDoesNotCapture(F, 2);
1035 setOnlyReadsMemory(F, 2);
1037 case LibFunc::strcmp: // 0,1
1038 case LibFunc::strspn: // 0,1
1039 case LibFunc::strncmp: // 0,1
1040 case LibFunc::strcspn: // 0,1
1041 case LibFunc::strcoll: // 0,1
1042 case LibFunc::strcasecmp: // 0,1
1043 case LibFunc::strncasecmp: //
1044 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1045 !FTy->getParamType(1)->isPointerTy())
1047 setOnlyReadsMemory(F);
1049 setDoesNotCapture(F, 1);
1050 setDoesNotCapture(F, 2);
1052 case LibFunc::strstr:
1053 case LibFunc::strpbrk:
1054 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1056 setOnlyReadsMemory(F);
1058 setDoesNotCapture(F, 2);
1060 case LibFunc::strtok:
1061 case LibFunc::strtok_r:
1062 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1065 setDoesNotCapture(F, 2);
1066 setOnlyReadsMemory(F, 2);
1068 case LibFunc::scanf:
1069 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1072 setDoesNotCapture(F, 1);
1073 setOnlyReadsMemory(F, 1);
1075 case LibFunc::setbuf:
1076 case LibFunc::setvbuf:
1077 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1080 setDoesNotCapture(F, 1);
1082 case LibFunc::strdup:
1083 case LibFunc::strndup:
1084 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1085 !FTy->getParamType(0)->isPointerTy())
1088 setDoesNotAlias(F, 0);
1089 setDoesNotCapture(F, 1);
1090 setOnlyReadsMemory(F, 1);
1093 case LibFunc::statvfs:
1094 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1095 !FTy->getParamType(1)->isPointerTy())
1098 setDoesNotCapture(F, 1);
1099 setDoesNotCapture(F, 2);
1100 setOnlyReadsMemory(F, 1);
1102 case LibFunc::sscanf:
1103 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1104 !FTy->getParamType(1)->isPointerTy())
1107 setDoesNotCapture(F, 1);
1108 setDoesNotCapture(F, 2);
1109 setOnlyReadsMemory(F, 1);
1110 setOnlyReadsMemory(F, 2);
1112 case LibFunc::sprintf:
1113 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1114 !FTy->getParamType(1)->isPointerTy())
1117 setDoesNotCapture(F, 1);
1118 setDoesNotCapture(F, 2);
1119 setOnlyReadsMemory(F, 2);
1121 case LibFunc::snprintf:
1122 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1123 !FTy->getParamType(2)->isPointerTy())
1126 setDoesNotCapture(F, 1);
1127 setDoesNotCapture(F, 3);
1128 setOnlyReadsMemory(F, 3);
1130 case LibFunc::setitimer:
1131 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1132 !FTy->getParamType(2)->isPointerTy())
1135 setDoesNotCapture(F, 2);
1136 setDoesNotCapture(F, 3);
1137 setOnlyReadsMemory(F, 2);
1139 case LibFunc::system:
1140 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1142 // May throw; "system" is a valid pthread cancellation point.
1143 setDoesNotCapture(F, 1);
1144 setOnlyReadsMemory(F, 1);
1146 case LibFunc::malloc:
1147 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1150 setDoesNotAlias(F, 0);
1152 case LibFunc::memcmp:
1153 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1154 !FTy->getParamType(1)->isPointerTy())
1156 setOnlyReadsMemory(F);
1158 setDoesNotCapture(F, 1);
1159 setDoesNotCapture(F, 2);
1161 case LibFunc::memchr:
1162 case LibFunc::memrchr:
1163 if (FTy->getNumParams() != 3)
1165 setOnlyReadsMemory(F);
1169 case LibFunc::modff:
1170 case LibFunc::modfl:
1171 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1174 setDoesNotCapture(F, 2);
1176 case LibFunc::memcpy:
1177 case LibFunc::memccpy:
1178 case LibFunc::memmove:
1179 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1182 setDoesNotCapture(F, 2);
1183 setOnlyReadsMemory(F, 2);
1185 case LibFunc::memalign:
1186 if (!FTy->getReturnType()->isPointerTy())
1188 setDoesNotAlias(F, 0);
1190 case LibFunc::mkdir:
1191 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1194 setDoesNotCapture(F, 1);
1195 setOnlyReadsMemory(F, 1);
1197 case LibFunc::mktime:
1198 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1201 setDoesNotCapture(F, 1);
1203 case LibFunc::realloc:
1204 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1205 !FTy->getReturnType()->isPointerTy())
1208 setDoesNotAlias(F, 0);
1209 setDoesNotCapture(F, 1);
1212 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1214 // May throw; "read" is a valid pthread cancellation point.
1215 setDoesNotCapture(F, 2);
1217 case LibFunc::rewind:
1218 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1221 setDoesNotCapture(F, 1);
1223 case LibFunc::rmdir:
1224 case LibFunc::remove:
1225 case LibFunc::realpath:
1226 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1229 setDoesNotCapture(F, 1);
1230 setOnlyReadsMemory(F, 1);
1232 case LibFunc::rename:
1233 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1234 !FTy->getParamType(1)->isPointerTy())
1237 setDoesNotCapture(F, 1);
1238 setDoesNotCapture(F, 2);
1239 setOnlyReadsMemory(F, 1);
1240 setOnlyReadsMemory(F, 2);
1242 case LibFunc::readlink:
1243 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1244 !FTy->getParamType(1)->isPointerTy())
1247 setDoesNotCapture(F, 1);
1248 setDoesNotCapture(F, 2);
1249 setOnlyReadsMemory(F, 1);
1251 case LibFunc::write:
1252 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1254 // May throw; "write" is a valid pthread cancellation point.
1255 setDoesNotCapture(F, 2);
1256 setOnlyReadsMemory(F, 2);
1258 case LibFunc::bcopy:
1259 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1260 !FTy->getParamType(1)->isPointerTy())
1263 setDoesNotCapture(F, 1);
1264 setDoesNotCapture(F, 2);
1265 setOnlyReadsMemory(F, 1);
1268 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1269 !FTy->getParamType(1)->isPointerTy())
1272 setOnlyReadsMemory(F);
1273 setDoesNotCapture(F, 1);
1274 setDoesNotCapture(F, 2);
1276 case LibFunc::bzero:
1277 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1280 setDoesNotCapture(F, 1);
1282 case LibFunc::calloc:
1283 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1286 setDoesNotAlias(F, 0);
1288 case LibFunc::chmod:
1289 case LibFunc::chown:
1290 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1293 setDoesNotCapture(F, 1);
1294 setOnlyReadsMemory(F, 1);
1296 case LibFunc::ctermid:
1297 case LibFunc::clearerr:
1298 case LibFunc::closedir:
1299 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1302 setDoesNotCapture(F, 1);
1307 case LibFunc::atoll:
1308 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1311 setOnlyReadsMemory(F);
1312 setDoesNotCapture(F, 1);
1314 case LibFunc::access:
1315 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1318 setDoesNotCapture(F, 1);
1319 setOnlyReadsMemory(F, 1);
1321 case LibFunc::fopen:
1322 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1323 !FTy->getParamType(0)->isPointerTy() ||
1324 !FTy->getParamType(1)->isPointerTy())
1327 setDoesNotAlias(F, 0);
1328 setDoesNotCapture(F, 1);
1329 setDoesNotCapture(F, 2);
1330 setOnlyReadsMemory(F, 1);
1331 setOnlyReadsMemory(F, 2);
1333 case LibFunc::fdopen:
1334 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1335 !FTy->getParamType(1)->isPointerTy())
1338 setDoesNotAlias(F, 0);
1339 setDoesNotCapture(F, 2);
1340 setOnlyReadsMemory(F, 2);
1344 case LibFunc::fseek:
1345 case LibFunc::ftell:
1346 case LibFunc::fgetc:
1347 case LibFunc::fseeko:
1348 case LibFunc::ftello:
1349 case LibFunc::fileno:
1350 case LibFunc::fflush:
1351 case LibFunc::fclose:
1352 case LibFunc::fsetpos:
1353 case LibFunc::flockfile:
1354 case LibFunc::funlockfile:
1355 case LibFunc::ftrylockfile:
1356 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1359 setDoesNotCapture(F, 1);
1361 case LibFunc::ferror:
1362 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1365 setDoesNotCapture(F, 1);
1366 setOnlyReadsMemory(F);
1368 case LibFunc::fputc:
1369 case LibFunc::fstat:
1370 case LibFunc::frexp:
1371 case LibFunc::frexpf:
1372 case LibFunc::frexpl:
1373 case LibFunc::fstatvfs:
1374 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1377 setDoesNotCapture(F, 2);
1379 case LibFunc::fgets:
1380 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1381 !FTy->getParamType(2)->isPointerTy())
1384 setDoesNotCapture(F, 3);
1386 case LibFunc::fread:
1387 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1388 !FTy->getParamType(3)->isPointerTy())
1391 setDoesNotCapture(F, 1);
1392 setDoesNotCapture(F, 4);
1394 case LibFunc::fwrite:
1395 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1396 !FTy->getParamType(3)->isPointerTy())
1399 setDoesNotCapture(F, 1);
1400 setDoesNotCapture(F, 4);
1402 case LibFunc::fputs:
1403 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1404 !FTy->getParamType(1)->isPointerTy())
1407 setDoesNotCapture(F, 1);
1408 setDoesNotCapture(F, 2);
1409 setOnlyReadsMemory(F, 1);
1411 case LibFunc::fscanf:
1412 case LibFunc::fprintf:
1413 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1414 !FTy->getParamType(1)->isPointerTy())
1417 setDoesNotCapture(F, 1);
1418 setDoesNotCapture(F, 2);
1419 setOnlyReadsMemory(F, 2);
1421 case LibFunc::fgetpos:
1422 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1423 !FTy->getParamType(1)->isPointerTy())
1426 setDoesNotCapture(F, 1);
1427 setDoesNotCapture(F, 2);
1430 case LibFunc::getlogin_r:
1431 case LibFunc::getc_unlocked:
1432 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1435 setDoesNotCapture(F, 1);
1437 case LibFunc::getenv:
1438 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1441 setOnlyReadsMemory(F);
1442 setDoesNotCapture(F, 1);
1445 case LibFunc::getchar:
1448 case LibFunc::getitimer:
1449 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1452 setDoesNotCapture(F, 2);
1454 case LibFunc::getpwnam:
1455 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1458 setDoesNotCapture(F, 1);
1459 setOnlyReadsMemory(F, 1);
1461 case LibFunc::ungetc:
1462 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1465 setDoesNotCapture(F, 2);
1467 case LibFunc::uname:
1468 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1471 setDoesNotCapture(F, 1);
1473 case LibFunc::unlink:
1474 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1477 setDoesNotCapture(F, 1);
1478 setOnlyReadsMemory(F, 1);
1480 case LibFunc::unsetenv:
1481 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1484 setDoesNotCapture(F, 1);
1485 setOnlyReadsMemory(F, 1);
1487 case LibFunc::utime:
1488 case LibFunc::utimes:
1489 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1490 !FTy->getParamType(1)->isPointerTy())
1493 setDoesNotCapture(F, 1);
1494 setDoesNotCapture(F, 2);
1495 setOnlyReadsMemory(F, 1);
1496 setOnlyReadsMemory(F, 2);
1499 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1502 setDoesNotCapture(F, 2);
1505 case LibFunc::printf:
1506 case LibFunc::perror:
1507 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1510 setDoesNotCapture(F, 1);
1511 setOnlyReadsMemory(F, 1);
1513 case LibFunc::pread:
1514 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1516 // May throw; "pread" is a valid pthread cancellation point.
1517 setDoesNotCapture(F, 2);
1519 case LibFunc::pwrite:
1520 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1522 // May throw; "pwrite" is a valid pthread cancellation point.
1523 setDoesNotCapture(F, 2);
1524 setOnlyReadsMemory(F, 2);
1526 case LibFunc::putchar:
1529 case LibFunc::popen:
1530 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1531 !FTy->getParamType(0)->isPointerTy() ||
1532 !FTy->getParamType(1)->isPointerTy())
1535 setDoesNotAlias(F, 0);
1536 setDoesNotCapture(F, 1);
1537 setDoesNotCapture(F, 2);
1538 setOnlyReadsMemory(F, 1);
1539 setOnlyReadsMemory(F, 2);
1541 case LibFunc::pclose:
1542 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1545 setDoesNotCapture(F, 1);
1547 case LibFunc::vscanf:
1548 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1551 setDoesNotCapture(F, 1);
1552 setOnlyReadsMemory(F, 1);
1554 case LibFunc::vsscanf:
1555 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1556 !FTy->getParamType(2)->isPointerTy())
1559 setDoesNotCapture(F, 1);
1560 setDoesNotCapture(F, 2);
1561 setOnlyReadsMemory(F, 1);
1562 setOnlyReadsMemory(F, 2);
1564 case LibFunc::vfscanf:
1565 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1566 !FTy->getParamType(2)->isPointerTy())
1569 setDoesNotCapture(F, 1);
1570 setDoesNotCapture(F, 2);
1571 setOnlyReadsMemory(F, 2);
1573 case LibFunc::valloc:
1574 if (!FTy->getReturnType()->isPointerTy())
1577 setDoesNotAlias(F, 0);
1579 case LibFunc::vprintf:
1580 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1583 setDoesNotCapture(F, 1);
1584 setOnlyReadsMemory(F, 1);
1586 case LibFunc::vfprintf:
1587 case LibFunc::vsprintf:
1588 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1589 !FTy->getParamType(1)->isPointerTy())
1592 setDoesNotCapture(F, 1);
1593 setDoesNotCapture(F, 2);
1594 setOnlyReadsMemory(F, 2);
1596 case LibFunc::vsnprintf:
1597 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1598 !FTy->getParamType(2)->isPointerTy())
1601 setDoesNotCapture(F, 1);
1602 setDoesNotCapture(F, 3);
1603 setOnlyReadsMemory(F, 3);
1606 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1608 // May throw; "open" is a valid pthread cancellation point.
1609 setDoesNotCapture(F, 1);
1610 setOnlyReadsMemory(F, 1);
1612 case LibFunc::opendir:
1613 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1614 !FTy->getParamType(0)->isPointerTy())
1617 setDoesNotAlias(F, 0);
1618 setDoesNotCapture(F, 1);
1619 setOnlyReadsMemory(F, 1);
1621 case LibFunc::tmpfile:
1622 if (!FTy->getReturnType()->isPointerTy())
1625 setDoesNotAlias(F, 0);
1627 case LibFunc::times:
1628 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1631 setDoesNotCapture(F, 1);
1633 case LibFunc::htonl:
1634 case LibFunc::htons:
1635 case LibFunc::ntohl:
1636 case LibFunc::ntohs:
1638 setDoesNotAccessMemory(F);
1640 case LibFunc::lstat:
1641 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1642 !FTy->getParamType(1)->isPointerTy())
1645 setDoesNotCapture(F, 1);
1646 setDoesNotCapture(F, 2);
1647 setOnlyReadsMemory(F, 1);
1649 case LibFunc::lchown:
1650 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1653 setDoesNotCapture(F, 1);
1654 setOnlyReadsMemory(F, 1);
1656 case LibFunc::qsort:
1657 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1659 // May throw; places call through function pointer.
1660 setDoesNotCapture(F, 4);
1662 case LibFunc::dunder_strdup:
1663 case LibFunc::dunder_strndup:
1664 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1665 !FTy->getParamType(0)->isPointerTy())
1668 setDoesNotAlias(F, 0);
1669 setDoesNotCapture(F, 1);
1670 setOnlyReadsMemory(F, 1);
1672 case LibFunc::dunder_strtok_r:
1673 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1676 setDoesNotCapture(F, 2);
1677 setOnlyReadsMemory(F, 2);
1679 case LibFunc::under_IO_getc:
1680 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1683 setDoesNotCapture(F, 1);
1685 case LibFunc::under_IO_putc:
1686 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1689 setDoesNotCapture(F, 2);
1691 case LibFunc::dunder_isoc99_scanf:
1692 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1695 setDoesNotCapture(F, 1);
1696 setOnlyReadsMemory(F, 1);
1698 case LibFunc::stat64:
1699 case LibFunc::lstat64:
1700 case LibFunc::statvfs64:
1701 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1702 !FTy->getParamType(1)->isPointerTy())
1705 setDoesNotCapture(F, 1);
1706 setDoesNotCapture(F, 2);
1707 setOnlyReadsMemory(F, 1);
1709 case LibFunc::dunder_isoc99_sscanf:
1710 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1711 !FTy->getParamType(1)->isPointerTy())
1714 setDoesNotCapture(F, 1);
1715 setDoesNotCapture(F, 2);
1716 setOnlyReadsMemory(F, 1);
1717 setOnlyReadsMemory(F, 2);
1719 case LibFunc::fopen64:
1720 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1721 !FTy->getParamType(0)->isPointerTy() ||
1722 !FTy->getParamType(1)->isPointerTy())
1725 setDoesNotAlias(F, 0);
1726 setDoesNotCapture(F, 1);
1727 setDoesNotCapture(F, 2);
1728 setOnlyReadsMemory(F, 1);
1729 setOnlyReadsMemory(F, 2);
1731 case LibFunc::fseeko64:
1732 case LibFunc::ftello64:
1733 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1736 setDoesNotCapture(F, 1);
1738 case LibFunc::tmpfile64:
1739 if (!FTy->getReturnType()->isPointerTy())
1742 setDoesNotAlias(F, 0);
1744 case LibFunc::fstat64:
1745 case LibFunc::fstatvfs64:
1746 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1749 setDoesNotCapture(F, 2);
1751 case LibFunc::open64:
1752 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1754 // May throw; "open" is a valid pthread cancellation point.
1755 setDoesNotCapture(F, 1);
1756 setOnlyReadsMemory(F, 1);
1758 case LibFunc::gettimeofday:
1759 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1760 !FTy->getParamType(1)->isPointerTy())
1762 // Currently some platforms have the restrict keyword on the arguments to
1763 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1766 setDoesNotCapture(F, 1);
1767 setDoesNotCapture(F, 2);
1770 // Didn't mark any attributes.
1777 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1778 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1779 bool Changed = false;
1781 // We compute dedicated AA results for each function in the SCC as needed. We
1782 // use a lambda referencing external objects so that they live long enough to
1783 // be queried, but we re-use them each time.
1784 Optional<BasicAAResult> BAR;
1785 Optional<AAResults> AAR;
1786 auto AARGetter = [&](Function &F) -> AAResults & {
1787 BAR.emplace(createLegacyPMBasicAAResult(*this, F));
1788 AAR.emplace(createLegacyPMAAResults(*this, F, *BAR));
1792 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1793 // whether a given CallGraphNode is in this SCC. Also track whether there are
1794 // any external or opt-none nodes that will prevent us from optimizing any
1796 SCCNodeSet SCCNodes;
1797 bool ExternalNode = false;
1798 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1799 Function *F = (*I)->getFunction();
1800 if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
1801 // External node or function we're trying not to optimize - we both avoid
1802 // transform them and avoid leveraging information they provide.
1803 ExternalNode = true;
1807 // When initially processing functions, also infer their prototype
1808 // attributes if they are declarations.
1809 if (F->isDeclaration())
1810 Changed |= inferPrototypeAttributes(*F, *TLI);
1815 Changed |= addReadAttrs(SCCNodes, AARGetter);
1816 Changed |= addArgumentAttrs(SCCNodes);
1818 // If we have no external nodes participating in the SCC, we can infer some
1819 // more precise attributes as well.
1820 if (!ExternalNode) {
1821 Changed |= addNoAliasAttrs(SCCNodes);
1822 Changed |= addNonNullAttrs(SCCNodes, *TLI);