LLVM 24.0.0git
FunctionAttrs.cpp
Go to the documentation of this file.
1//===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This file implements interprocedural passes which walk the
11/// call-graph deducing and/or propagating function attributes.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/Statistic.h"
27#include "llvm/Analysis/CFG.h"
34#include "llvm/IR/Argument.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/BasicBlock.h"
37#include "llvm/IR/Constant.h"
39#include "llvm/IR/Constants.h"
40#include "llvm/IR/Function.h"
42#include "llvm/IR/InstrTypes.h"
43#include "llvm/IR/Instruction.h"
46#include "llvm/IR/Metadata.h"
48#include "llvm/IR/PassManager.h"
50#include "llvm/IR/Type.h"
51#include "llvm/IR/Use.h"
52#include "llvm/IR/User.h"
53#include "llvm/IR/Value.h"
57#include "llvm/Support/Debug.h"
61#include "llvm/Transforms/IPO.h"
63#include <cassert>
64#include <iterator>
65#include <map>
66#include <optional>
67#include <vector>
68
69using namespace llvm;
70using namespace llvm::PatternMatch;
71
72#define DEBUG_TYPE "function-attrs"
73
74STATISTIC(NumMemoryAttr, "Number of functions with improved memory attribute");
75STATISTIC(NumCapturesNone, "Number of arguments marked captures(none)");
76STATISTIC(NumCapturesPartial, "Number of arguments marked with captures "
77 "attribute other than captures(none)");
78STATISTIC(NumReturned, "Number of arguments marked returned");
79STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
80STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
81STATISTIC(NumWriteOnlyArg, "Number of arguments marked writeonly");
82STATISTIC(NumNoAlias, "Number of function returns marked noalias");
83STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
84STATISTIC(NumNoUndefReturn, "Number of function returns marked noundef");
85STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
86STATISTIC(NumNoUnwind, "Number of functions marked as nounwind");
87STATISTIC(NumNoFree, "Number of functions marked as nofree");
88STATISTIC(NumNoFreeArg, "Number of arguments marked as nofree");
89STATISTIC(NumWillReturn, "Number of functions marked as willreturn");
90STATISTIC(NumNoSync, "Number of functions marked as nosync");
91STATISTIC(NumCold, "Number of functions marked as cold");
92
93STATISTIC(NumThinLinkNoRecurse,
94 "Number of functions marked as norecurse during thinlink");
95STATISTIC(NumThinLinkNoUnwind,
96 "Number of functions marked as nounwind during thinlink");
97
99 "enable-poison-arg-attr-prop", cl::init(true), cl::Hidden,
100 cl::desc("Try to propagate nonnull and nofpclass argument attributes from "
101 "callsites to caller functions."));
102
104 "disable-nounwind-inference", cl::Hidden,
105 cl::desc("Stop inferring nounwind attribute during function-attrs pass"));
106
108 "disable-nofree-inference", cl::Hidden,
109 cl::desc("Stop inferring nofree attribute during function-attrs pass"));
110
112 "disable-thinlto-funcattrs", cl::init(true), cl::Hidden,
113 cl::desc("Don't propagate function-attrs in thinLTO"));
114
116 if (capturesNothing(CI))
117 ++NumCapturesNone;
118 else
119 ++NumCapturesPartial;
120}
121
122namespace {
123
124using SCCNodeSet = SmallSetVector<Function *, 8>;
125
126} // end anonymous namespace
127
129 ModRefInfo MR, AAResults &AAR) {
130 // Ignore accesses to known-invariant or local memory.
131 MR &= AAR.getModRefInfoMask(Loc, /*IgnoreLocal=*/true);
132 if (isNoModRef(MR))
133 return;
134
135 const Value *UO = getUnderlyingObjectAggressive(Loc.Ptr);
136 if (isa<AllocaInst>(UO))
137 return;
138 if (isa<Argument>(UO)) {
140 return;
141 }
142
143 // If it's not an identified object, it might be an argument.
144 if (!isIdentifiedObject(UO))
148}
149
150static void addArgLocs(MemoryEffects &ME, const CallBase *Call,
151 ModRefInfo ArgMR, AAResults &AAR) {
152 for (const Value *Arg : Call->args()) {
153 if (!Arg->getType()->isPtrOrPtrVectorTy())
154 continue;
155
156 addLocAccess(ME,
157 MemoryLocation::getBeforeOrAfter(Arg, Call->getAAMetadata()),
158 ArgMR, AAR);
159 }
160}
161
162/// Returns the memory access attribute for function F using AAR for AA results,
163/// where SCCNodes is the current SCC.
164///
165/// If ThisBody is true, this function may examine the function body and will
166/// return a result pertaining to this copy of the function. If it is false, the
167/// result will be based only on AA results for the function declaration; it
168/// will be assumed that some other (perhaps less optimized) version of the
169/// function may be selected at link time.
170///
171/// The return value is split into two parts: Memory effects that always apply,
172/// and additional memory effects that apply if any of the functions in the SCC
173/// can access argmem.
174static std::pair<MemoryEffects, MemoryEffects>
176 const SCCNodeSet &SCCNodes) {
177 MemoryEffects OrigME = AAR.getMemoryEffects(&F);
178 if (OrigME.doesNotAccessMemory())
179 // Already perfect!
180 return {OrigME, MemoryEffects::none()};
181
182 if (!ThisBody)
183 return {OrigME, MemoryEffects::none()};
184
186 // Additional locations accessed if the SCC accesses argmem.
187 MemoryEffects RecursiveArgME = MemoryEffects::none();
188
189 auto AddNonArgMemoryEffects = [&ME](MemoryEffects InstME) {
190 // Merge instruction memory effects, including inaccessible and errno
191 // memory, but excluding argument memory, which is handled separately.
193
194 // If the instruction accesses captured memory (currently part of "other")
195 // and an argument is captured (currently not tracked), then it may also
196 // access argument memory.
197 ModRefInfo OtherMR = InstME.getModRef(IRMemLocation::Other);
198 ME |= MemoryEffects::argMemOnly(OtherMR);
199 };
200
201 // Inalloca and preallocated arguments are always clobbered by the call.
202 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
203 F.getAttributes().hasAttrSomewhere(Attribute::Preallocated))
205
206 // Scan the function body for instructions that may read or write memory.
207 for (Instruction &I : instructions(F)) {
208 // Some instructions can be ignored even if they read or write memory.
209 // Detect these now, skipping to the next instruction if one is found.
210 // We can optimistically ignore calls to functions in the same SCC, with
211 // two caveats:
212 // * Calls with operand bundles may have additional effects.
213 // * Argument memory accesses may imply additional effects depending on
214 // what the argument location is.
215 auto *Call = dyn_cast<CallBase>(&I);
216 if (Call && !Call->hasOperandBundles() && Call->getCalledFunction() &&
217 SCCNodes.count(Call->getCalledFunction())) {
218 // Keep track of which additional locations are accessed if the SCC
219 // turns out to access argmem.
220 addArgLocs(RecursiveArgME, Call, ModRefInfo::ModRef, AAR);
221 continue;
222 }
223
224 // Once ME covers OrigME, the returned effects are final.
225 if ((ME & OrigME) == OrigME)
226 continue;
227
228 if (Call) {
229 MemoryEffects CallME = AAR.getMemoryEffects(Call);
230
231 // If the call doesn't access memory, we're done.
232 if (CallME.doesNotAccessMemory())
233 continue;
234
235 // A pseudo probe call shouldn't change any function attribute since it
236 // doesn't translate to a real instruction. It comes with a memory access
237 // tag to prevent itself being removed by optimizations and not block
238 // other instructions being optimized.
240 continue;
241
242 AddNonArgMemoryEffects(CallME);
243
244 // Check whether all pointer arguments point to local memory, and
245 // ignore calls that only access local memory.
247 if (ArgMR != ModRefInfo::NoModRef)
248 addArgLocs(ME, Call, ArgMR, AAR);
249 continue;
250 }
251
252 MemoryEffects InstME = I.getMemoryEffects();
253 if (InstME.doesNotAccessMemory())
254 continue;
255
256 std::optional<MemoryLocation> Loc = MemoryLocation::getOrNone(&I);
257 if (!Loc) {
258 // If no location is known, conservatively assume anything can be
259 // accessed.
260 ME |= MemoryEffects(InstME.getModRef());
261 continue;
262 }
263
264 AddNonArgMemoryEffects(InstME);
266 }
267
268 return {OrigME & ME, RecursiveArgME};
269}
270
272 AAResults &AAR) {
273 return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {}).first;
274}
275
276/// Deduce readonly/readnone/writeonly attributes for the SCC.
277template <typename AARGetterT>
278static void addMemoryAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter,
281 MemoryEffects RecursiveArgME = MemoryEffects::none();
282 for (Function *F : SCCNodes) {
283 // Call the callable parameter to look up AA results for this function.
284 AAResults &AAR = AARGetter(*F);
285 // Non-exact function definitions may not be selected at link time, and an
286 // alternative version that writes to memory may be selected. See the
287 // comment on GlobalValue::isDefinitionExact for more details.
288 auto [FnME, FnRecursiveArgME] =
289 checkFunctionMemoryAccess(*F, F->hasExactDefinition(), AAR, SCCNodes);
290 ME |= FnME;
291 RecursiveArgME |= FnRecursiveArgME;
292 // Reached bottom of the lattice, we will not be able to improve the result.
293 if (ME == MemoryEffects::unknown())
294 return;
295 }
296
297 // If the SCC accesses argmem, add recursive accesses resulting from that.
299 if (ArgMR != ModRefInfo::NoModRef)
300 ME |= RecursiveArgME & MemoryEffects(ArgMR);
301
302 for (Function *F : SCCNodes) {
303 MemoryEffects OldME = F->getMemoryEffects();
304 MemoryEffects NewME = ME & OldME;
305 if (NewME != OldME) {
306 ++NumMemoryAttr;
307 F->setMemoryEffects(NewME);
308 // Remove conflicting writable attributes.
310 for (Argument &A : F->args())
311 A.removeAttr(Attribute::Writable);
312 Changed.insert(F);
313 }
314 }
315}
316
317// Compute definitive function attributes for a function taking into account
318// prevailing definitions and linkage types
320 ValueInfo VI,
321 DenseMap<ValueInfo, FunctionSummary *> &CachedPrevailingSummary,
323 IsPrevailing) {
324
325 auto [It, Inserted] = CachedPrevailingSummary.try_emplace(VI);
326 if (!Inserted)
327 return It->second;
328
329 /// At this point, prevailing symbols have been resolved. The following leads
330 /// to returning a conservative result:
331 /// - Multiple instances with local linkage. Normally local linkage would be
332 /// unique per module
333 /// as the GUID includes the module path. We could have a guid alias if
334 /// there wasn't any distinguishing path when each file was compiled, but
335 /// that should be rare so we'll punt on those.
336
337 /// These next 2 cases should not happen and will assert:
338 /// - Multiple instances with external linkage. This should be caught in
339 /// symbol resolution
340 /// - Non-existent FunctionSummary for Aliasee. This presents a hole in our
341 /// knowledge meaning we have to go conservative.
342
343 /// Otherwise, we calculate attributes for a function as:
344 /// 1. If we have a local linkage, take its attributes. If there's somehow
345 /// multiple, bail and go conservative.
346 /// 2. If we have an external/WeakODR/LinkOnceODR linkage check that it is
347 /// prevailing, take its attributes.
348 /// 3. If we have a Weak/LinkOnce linkage the copies can have semantic
349 /// differences. However, if the prevailing copy is known it will be used
350 /// so take its attributes. If the prevailing copy is in a native file
351 /// all IR copies will be dead and propagation will go conservative.
352 /// 4. AvailableExternally summaries without a prevailing copy are known to
353 /// occur in a couple of circumstances:
354 /// a. An internal function gets imported due to its caller getting
355 /// imported, it becomes AvailableExternally but no prevailing
356 /// definition exists. Because it has to get imported along with its
357 /// caller the attributes will be captured by propagating on its
358 /// caller.
359 /// b. C++11 [temp.explicit]p10 can generate AvailableExternally
360 /// definitions of explicitly instanced template declarations
361 /// for inlining which are ultimately dropped from the TU. Since this
362 /// is localized to the TU the attributes will have already made it to
363 /// the callers.
364 /// These are edge cases and already captured by their callers so we
365 /// ignore these for now. If they become relevant to optimize in the
366 /// future this can be revisited.
367 /// 5. Otherwise, go conservative.
368
369 FunctionSummary *Local = nullptr;
370 FunctionSummary *Prevailing = nullptr;
371
372 for (const auto &GVS : VI.getSummaryList()) {
373 if (!GVS->isLive())
374 continue;
375
376 FunctionSummary *FS = dyn_cast<FunctionSummary>(GVS->getBaseObject());
377 // Virtual and Unknown (e.g. indirect) calls require going conservative
378 if (!FS || FS->fflags().HasUnknownCall)
379 return nullptr;
380
381 const auto &Linkage = GVS->linkage();
383 if (Local) {
385 dbgs()
386 << "ThinLTO FunctionAttrs: Multiple Local Linkage, bailing on "
387 "function "
388 << VI.name() << " from " << FS->modulePath() << ". Previous module "
389 << Local->modulePath() << "\n");
390 return nullptr;
391 }
392 Local = FS;
394 assert(IsPrevailing(VI.getGUID(), GVS.get()) || GVS->wasPromoted());
395 Prevailing = FS;
396 break;
401 if (IsPrevailing(VI.getGUID(), GVS.get())) {
402 Prevailing = FS;
403 break;
404 }
406 // TODO: Handle these cases if they become meaningful
407 continue;
408 }
409 }
410
411 auto &CPS = CachedPrevailingSummary[VI];
412 if (Local) {
413 assert(!Prevailing);
414 CPS = Local;
415 } else if (Prevailing) {
416 assert(!Local);
417 CPS = Prevailing;
418 }
419
420 return CPS;
421}
422
424 ModuleSummaryIndex &Index,
426 IsPrevailing) {
427 // TODO: implement addNoAliasAttrs once
428 // there's more information about the return type in the summary
430 return false;
431
432 DenseMap<ValueInfo, FunctionSummary *> CachedPrevailingSummary;
433 bool Changed = false;
434
435 auto PropagateAttributes = [&](std::vector<ValueInfo> &SCCNodes) {
436 // Assume we can propagate unless we discover otherwise
437 FunctionSummary::FFlags InferredFlags;
438 InferredFlags.NoRecurse = (SCCNodes.size() == 1);
439 InferredFlags.NoUnwind = true;
440
441 for (auto &V : SCCNodes) {
442 FunctionSummary *CallerSummary =
443 calculatePrevailingSummary(V, CachedPrevailingSummary, IsPrevailing);
444
445 // Function summaries can fail to contain information such as declarations
446 if (!CallerSummary)
447 return;
448
449 if (CallerSummary->fflags().MayThrow)
450 InferredFlags.NoUnwind = false;
451
452 for (const auto &Callee : CallerSummary->calls()) {
454 Callee.first, CachedPrevailingSummary, IsPrevailing);
455
456 if (!CalleeSummary)
457 return;
458
459 if (!CalleeSummary->fflags().NoRecurse)
460 InferredFlags.NoRecurse = false;
461
462 if (!CalleeSummary->fflags().NoUnwind)
463 InferredFlags.NoUnwind = false;
464
465 if (!InferredFlags.NoUnwind && !InferredFlags.NoRecurse)
466 break;
467 }
468 }
469
470 if (InferredFlags.NoUnwind || InferredFlags.NoRecurse) {
471 Changed = true;
472 for (auto &V : SCCNodes) {
473 if (InferredFlags.NoRecurse) {
474 LLVM_DEBUG(dbgs() << "ThinLTO FunctionAttrs: Propagated NoRecurse to "
475 << V.name() << "\n");
476 ++NumThinLinkNoRecurse;
477 }
478
479 if (InferredFlags.NoUnwind) {
480 LLVM_DEBUG(dbgs() << "ThinLTO FunctionAttrs: Propagated NoUnwind to "
481 << V.name() << "\n");
482 ++NumThinLinkNoUnwind;
483 }
484
485 for (const auto &S : V.getSummaryList()) {
486 if (auto *FS = dyn_cast<FunctionSummary>(S.get())) {
487 if (InferredFlags.NoRecurse)
488 FS->setNoRecurse();
489
490 if (InferredFlags.NoUnwind)
491 FS->setNoUnwind();
492 }
493 }
494 }
495 }
496 };
497
498 // Call propagation functions on each SCC in the Index
499 for (scc_iterator<ModuleSummaryIndex *> I = scc_begin(&Index); !I.isAtEnd();
500 ++I) {
501 std::vector<ValueInfo> Nodes(*I);
502 PropagateAttributes(Nodes);
503 }
504 return Changed;
505}
506
507namespace {
508
509/// For a given pointer Argument, this retains a list of Arguments of functions
510/// in the same SCC that the pointer data flows into. We use this to build an
511/// SCC of the arguments.
512struct ArgumentGraphNode {
513 Argument *Definition;
514 /// CaptureComponents for this argument, excluding captures via Uses.
515 /// We don't distinguish between other/return captures here.
518};
519
520class ArgumentGraph {
521 // We store pointers to ArgumentGraphNode objects, so it's important that
522 // that they not move around upon insert.
523 using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
524
525 ArgumentMapTy ArgumentMap;
526
527 // There is no root node for the argument graph, in fact:
528 // void f(int *x, int *y) { if (...) f(x, y); }
529 // is an example where the graph is disconnected. The SCCIterator requires a
530 // single entry point, so we maintain a fake ("synthetic") root node that
531 // uses every node. Because the graph is directed and nothing points into
532 // the root, it will not participate in any SCCs (except for its own).
533 ArgumentGraphNode SyntheticRoot;
534
535public:
536 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
537
539
540 iterator begin() { return SyntheticRoot.Uses.begin(); }
541 iterator end() { return SyntheticRoot.Uses.end(); }
542 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
543
544 ArgumentGraphNode *operator[](Argument *A) {
545 ArgumentGraphNode &Node = ArgumentMap[A];
546 Node.Definition = A;
547 SyntheticRoot.Uses.push_back(&Node);
548 return &Node;
549 }
550};
551
552/// This tracker checks whether callees are in the SCC, and if so it does not
553/// consider that a capture, instead adding it to the "Uses" list and
554/// continuing with the analysis.
555struct ArgumentUsesTracker : public CaptureTracker {
556 ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
557
558 void tooManyUses() override { CI = CaptureInfo::all(); }
559
560 Action captured(const Use *U, UseCaptureInfo UseCI) override {
561 if (updateCaptureInfo(U, UseCI.UseCC)) {
562 // Don't bother continuing if we already capture everything.
563 if (capturesAll(CI.getOtherComponents()))
564 return Stop;
565 return Continue;
566 }
567
568 // For SCC argument tracking, we're not going to analyze other/ret
569 // components separately, so don't follow the return value.
570 return ContinueIgnoringReturn;
571 }
572
573 bool updateCaptureInfo(const Use *U, CaptureComponents CC) {
574 CallBase *CB = dyn_cast<CallBase>(U->getUser());
575 if (!CB) {
576 if (isa<ReturnInst>(U->getUser()))
578 else
579 // Conservatively assume that the captured value might make its way
580 // into the return value as well. This could be made more precise.
581 CI |= CaptureInfo(CC);
582 return true;
583 }
584
586 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
587 CI |= CaptureInfo(CC);
588 return true;
589 }
590
591 assert(!CB->isCallee(U) && "callee operand reported captured?");
592 const unsigned UseIndex = CB->getDataOperandNo(U);
593 if (UseIndex >= CB->arg_size()) {
594 // Data operand, but not a argument operand -- must be a bundle operand
595 assert(CB->hasOperandBundles() && "Must be!");
596
597 // CaptureTracking told us that we're being captured by an operand bundle
598 // use. In this case it does not matter if the callee is within our SCC
599 // or not -- we've been captured in some unknown way, and we have to be
600 // conservative.
601 CI |= CaptureInfo(CC);
602 return true;
603 }
604
605 if (UseIndex >= F->arg_size()) {
606 assert(F->isVarArg() && "More params than args in non-varargs call");
607 CI |= CaptureInfo(CC);
608 return true;
609 }
610
611 // TODO(captures): Could improve precision by remembering maximum
612 // capture components for the argument.
613 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
614 return false;
615 }
616
617 // Does not include potential captures via Uses in the SCC.
618 CaptureInfo CI = CaptureInfo::none();
619
620 // Uses within our SCC.
622
623 const SCCNodeSet &SCCNodes;
624};
625
626/// A struct of argument use: a Use and the offset it accesses. This struct
627/// is to track uses inside function via GEP. If GEP has a non-constant index,
628/// the Offset field is nullopt.
629struct ArgumentUse {
630 Use *U;
631 std::optional<int64_t> Offset;
632};
633
634/// A struct of argument access info. "Unknown" accesses are the cases like
635/// unrecognized instructions, instructions that have more than one use of
636/// the argument, or volatile memory accesses. "WriteWithSideEffect" are call
637/// instructions that not only write an argument but also capture it.
638struct ArgumentAccessInfo {
639 enum class AccessType : uint8_t { Write, WriteWithSideEffect, Read, Unknown };
640 AccessType ArgAccessType;
641 ConstantRangeList AccessRanges;
642};
643
644/// A struct to wrap the argument use info per block.
645struct UsesPerBlockInfo {
646 SmallDenseMap<Instruction *, ArgumentAccessInfo, 4> Insts;
647 bool HasWrites = false;
648 bool HasUnknownAccess = false;
649};
650
651/// A struct to summarize the argument use info in a function.
652struct ArgumentUsesSummary {
653 bool HasAnyWrite = false;
654 bool HasWriteOutsideEntryBB = false;
655 SmallDenseMap<const BasicBlock *, UsesPerBlockInfo, 16> UsesPerBlock;
656};
657
658ArgumentAccessInfo getArgumentAccessInfo(const Instruction *I,
659 const ArgumentUse &ArgUse,
660 const DataLayout &DL) {
661 auto GetTypeAccessRange =
662 [&DL](Type *Ty,
663 std::optional<int64_t> Offset) -> std::optional<ConstantRange> {
664 auto TypeSize = DL.getTypeStoreSize(Ty);
665 if (!TypeSize.isScalable() && Offset) {
666 int64_t Size = TypeSize.getFixedValue();
667 APInt Low(64, *Offset, true);
668 bool Overflow;
669 APInt High = Low.sadd_ov(APInt(64, Size, true), Overflow);
670 // Bail if the range overflows signed 64-bit int.
671 if (Overflow)
672 return std::nullopt;
673 return ConstantRange(Low, High);
674 }
675 return std::nullopt;
676 };
677 auto GetConstantIntRange =
678 [](Value *Length,
679 std::optional<int64_t> Offset) -> std::optional<ConstantRange> {
680 auto *ConstantLength = dyn_cast<ConstantInt>(Length);
681 if (ConstantLength && Offset) {
682 int64_t Len = ConstantLength->getSExtValue();
683
684 // Reject zero or negative lengths
685 if (Len <= 0)
686 return std::nullopt;
687
688 APInt Low(64, *Offset, true);
689 bool Overflow;
690 APInt High = Low.sadd_ov(APInt(64, Len, true), Overflow);
691 if (Overflow)
692 return std::nullopt;
693
694 return ConstantRange(Low, High);
695 }
696 return std::nullopt;
697 };
698
699 if (auto *SI = dyn_cast<StoreInst>(I)) {
700 if (SI->isSimple() && &SI->getOperandUse(1) == ArgUse.U) {
701 // Get the fixed type size of "SI". Since the access range of a write
702 // will be unioned, if "SI" doesn't have a fixed type size, we just set
703 // the access range to empty.
704 ConstantRangeList AccessRanges;
705 if (auto TypeAccessRange =
706 GetTypeAccessRange(SI->getAccessType(), ArgUse.Offset))
707 AccessRanges.insert(*TypeAccessRange);
708 return {ArgumentAccessInfo::AccessType::Write, std::move(AccessRanges)};
709 }
710 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
711 if (LI->isSimple()) {
712 assert(&LI->getOperandUse(0) == ArgUse.U);
713 // Get the fixed type size of "LI". Different from Write, if "LI"
714 // doesn't have a fixed type size, we conservatively set as a clobber
715 // with an empty access range.
716 if (auto TypeAccessRange =
717 GetTypeAccessRange(LI->getAccessType(), ArgUse.Offset))
718 return {ArgumentAccessInfo::AccessType::Read, {*TypeAccessRange}};
719 }
720 } else if (auto *MemSet = dyn_cast<MemSetInst>(I)) {
721 if (!MemSet->isVolatile()) {
722 ConstantRangeList AccessRanges;
723 if (auto AccessRange =
724 GetConstantIntRange(MemSet->getLength(), ArgUse.Offset))
725 AccessRanges.insert(*AccessRange);
726 return {ArgumentAccessInfo::AccessType::Write, AccessRanges};
727 }
728 } else if (auto *MTI = dyn_cast<MemTransferInst>(I)) {
729 if (!MTI->isVolatile()) {
730 if (&MTI->getOperandUse(0) == ArgUse.U) {
731 ConstantRangeList AccessRanges;
732 if (auto AccessRange =
733 GetConstantIntRange(MTI->getLength(), ArgUse.Offset))
734 AccessRanges.insert(*AccessRange);
735 return {ArgumentAccessInfo::AccessType::Write, AccessRanges};
736 } else if (&MTI->getOperandUse(1) == ArgUse.U) {
737 if (auto AccessRange =
738 GetConstantIntRange(MTI->getLength(), ArgUse.Offset))
739 return {ArgumentAccessInfo::AccessType::Read, {*AccessRange}};
740 }
741 }
742 } else if (auto *CB = dyn_cast<CallBase>(I)) {
743 if (CB->isArgOperand(ArgUse.U) &&
744 !CB->isByValArgument(CB->getArgOperandNo(ArgUse.U))) {
745 unsigned ArgNo = CB->getArgOperandNo(ArgUse.U);
746 bool IsInitialize = CB->paramHasAttr(ArgNo, Attribute::Initializes);
747 if (IsInitialize && ArgUse.Offset) {
748 // Argument is a Write when parameter is writeonly/readnone
749 // and nocapture. Otherwise, it's a WriteWithSideEffect.
750 auto Access = CB->onlyWritesMemory(ArgNo) && CB->doesNotCapture(ArgNo)
751 ? ArgumentAccessInfo::AccessType::Write
752 : ArgumentAccessInfo::AccessType::WriteWithSideEffect;
753 ConstantRangeList AccessRanges;
754 Attribute Attr = CB->getParamAttr(ArgNo, Attribute::Initializes);
756 for (ConstantRange &CR : CBCRL)
757 AccessRanges.insert(ConstantRange(CR.getLower() + *ArgUse.Offset,
758 CR.getUpper() + *ArgUse.Offset));
759 return {Access, AccessRanges};
760 }
761 }
762 }
763 // Other unrecognized instructions are considered as unknown.
764 return {ArgumentAccessInfo::AccessType::Unknown, {}};
765}
766
767// Collect the uses of argument "A" in "F".
768ArgumentUsesSummary collectArgumentUsesPerBlock(Argument &A, Function &F) {
769 auto &DL = F.getDataLayout();
770 unsigned PointerSize =
771 DL.getIndexSizeInBits(A.getType()->getPointerAddressSpace());
772 ArgumentUsesSummary Result;
773
774 BasicBlock &EntryBB = F.getEntryBlock();
776 for (Use &U : A.uses())
777 Worklist.push_back({&U, 0});
778
779 // Update "UsesPerBlock" with the block of "I" as key and "Info" as value.
780 // Return true if the block of "I" has write accesses after updating.
781 auto UpdateUseInfo = [&Result](Instruction *I, ArgumentAccessInfo Info) {
782 auto *BB = I->getParent();
783 auto &BBInfo = Result.UsesPerBlock[BB];
784 auto [It, Inserted] = BBInfo.Insts.try_emplace(I);
785 auto &IInfo = It->second;
786
787 // Instructions that have more than one use of the argument are considered
788 // as clobbers.
789 if (!Inserted) {
790 IInfo = {ArgumentAccessInfo::AccessType::Unknown, {}};
791 BBInfo.HasUnknownAccess = true;
792 return false;
793 }
794
795 IInfo = std::move(Info);
796 BBInfo.HasUnknownAccess |=
797 IInfo.ArgAccessType == ArgumentAccessInfo::AccessType::Unknown;
798 bool InfoHasWrites =
799 (IInfo.ArgAccessType == ArgumentAccessInfo::AccessType::Write ||
800 IInfo.ArgAccessType ==
801 ArgumentAccessInfo::AccessType::WriteWithSideEffect) &&
802 !IInfo.AccessRanges.empty();
803 BBInfo.HasWrites |= InfoHasWrites;
804 return InfoHasWrites;
805 };
806
807 // No need for a visited set because we don't look through phis, so there are
808 // no cycles.
809 while (!Worklist.empty()) {
810 ArgumentUse ArgUse = Worklist.pop_back_val();
811 User *U = ArgUse.U->getUser();
812 // Add GEP uses to worklist.
813 // If the GEP is not a constant GEP, set the ArgumentUse::Offset to nullopt.
814 if (auto *GEP = dyn_cast<GEPOperator>(U)) {
815 std::optional<int64_t> NewOffset = std::nullopt;
816 if (ArgUse.Offset) {
817 APInt Offset(PointerSize, 0);
818 if (GEP->accumulateConstantOffset(DL, Offset))
819 NewOffset = *ArgUse.Offset + Offset.getSExtValue();
820 }
821 for (Use &U : GEP->uses())
822 Worklist.push_back({&U, NewOffset});
823 continue;
824 }
825
826 auto *I = cast<Instruction>(U);
827 bool HasWrite = UpdateUseInfo(I, getArgumentAccessInfo(I, ArgUse, DL));
828
829 Result.HasAnyWrite |= HasWrite;
830
831 if (HasWrite && I->getParent() != &EntryBB)
832 Result.HasWriteOutsideEntryBB = true;
833 }
834 return Result;
835}
836
837} // end anonymous namespace
838
839namespace llvm {
840
841template <> struct GraphTraits<ArgumentGraphNode *> {
842 using NodeRef = ArgumentGraphNode *;
844
845 static NodeRef getEntryNode(NodeRef A) { return A; }
846 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
847 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
848};
849
850template <>
851struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
852 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
853
854 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
855 return AG->begin();
856 }
857
858 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
859};
860
862 bool IsRead = false;
863 bool IsWrite = false;
864 bool IsFree = false;
865
866 static ArgAccessProperties all() { return {true, true, true}; }
867
868 bool hasAll() const { return IsRead && IsWrite && IsFree; }
869
871 IsRead |= Other.IsRead;
872 IsWrite |= Other.IsWrite;
873 IsFree |= Other.IsFree;
874 return *this;
875 }
876};
877
878} // end namespace llvm
879
880/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
883 const SmallPtrSet<Argument *, 8> &SCCNodes) {
884 SmallVector<Use *, 32> Worklist;
886
887 // inalloca arguments are always clobbered by the call.
888 if (A->hasInAllocaAttr() || A->hasPreallocatedAttr())
890
892
893 for (Use &U : A->uses()) {
894 Visited.insert(&U);
895 Worklist.push_back(&U);
896 }
897
898 while (!Worklist.empty()) {
899 if (Props.hasAll())
900 // No point in searching further..
901 return Props;
902
903 Use *U = Worklist.pop_back_val();
904 Instruction *I = cast<Instruction>(U->getUser());
905 if (isa<ReturnInst>(I))
906 continue;
907
909
910 // FIXME: This should really be part of CaptureTracking, but keep it here
911 // for now due to interference with isEscapeSource().
912 if (auto *CB = dyn_cast<CallBase>(I))
913 if (CB->onlyReadsMemory())
914 Info.UseCC &= CaptureComponents::Address;
915
916 if (capturesAnyProvenance(Info.UseCC)) {
917 // Handle indirect access via captured provenance.
918 if (!capturesReadProvenanceOnly(Info.UseCC))
920 Props.IsRead = true;
921 }
922
923 if (capturesAnyProvenance(Info.ResultCC)) {
924 for (Use &UU : I->uses())
925 if (Visited.insert(&UU).second)
926 Worklist.push_back(&UU);
927 }
928
929 if (auto *CB = dyn_cast<CallBase>(I)) {
930 if (CB->isCallee(U)) {
931 Props.IsRead = true;
932 continue;
933 }
934
935 // Given we've explicitly handled the callee operand above, what's left
936 // must be a data operand (e.g. argument or operand bundle)
937 const unsigned UseIndex = CB->getDataOperandNo(U);
938
939 ModRefInfo ArgMR =
941 if (isNoModRef(ArgMR))
942 continue;
943
944 if (Function *F = CB->getCalledFunction())
945 if (CB->isArgOperand(U) && UseIndex < F->arg_size() &&
946 SCCNodes.count(F->getArg(UseIndex)))
947 // This is an argument which is part of the speculative SCC. Note
948 // that only operands corresponding to formal arguments of the callee
949 // can participate in the speculation.
950 continue;
951
952 // The accessors used on call site here do the right thing for calls and
953 // invokes with operand bundles.
954 if (isRefSet(ArgMR) && !CB->onlyWritesMemory(UseIndex))
955 Props.IsRead = true;
956 if (isModSet(ArgMR) && !CB->onlyReadsMemory(UseIndex)) {
957 Props.IsWrite = true;
958 if (CB->isArgOperand(U) && !CB->hasFnAttr(Attribute::NoFree) &&
959 !CB->paramHasAttr(UseIndex, Attribute::NoFree) &&
960 !CB->paramHasAttr(UseIndex, Attribute::NoFreeObj))
961 Props.IsFree = true;
962 }
963 } else {
964 // Ignore value operand for stores.
965 if (isa<StoreInst>(I) &&
966 StoreInst::getPointerOperandIndex() != U->getOperandNo())
967 continue;
968
969 Props.IsRead |= I->mayReadFromMemory();
970 Props.IsWrite |= I->mayWriteToMemory();
971 }
972 }
973
974 return Props;
975}
976
977/// Deduce returned attributes for the SCC.
978static void addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes,
980 // Check each function in turn, determining if an argument is always returned.
981 for (Function *F : SCCNodes) {
982 // We can infer and propagate function attributes only when we know that the
983 // definition we'll get at link time is *exactly* the definition we see now.
984 // For more details, see GlobalValue::mayBeDerefined.
985 if (!F->hasExactDefinition())
986 continue;
987
988 if (F->getReturnType()->isVoidTy())
989 continue;
990
991 // There is nothing to do if an argument is already marked as 'returned'.
992 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned))
993 continue;
994
995 auto FindRetArg = [&]() -> Argument * {
996 Argument *RetArg = nullptr;
997 for (BasicBlock &BB : *F)
998 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
999 // Note that stripPointerCasts should look through functions with
1000 // returned arguments.
1001 auto *RetVal =
1002 dyn_cast<Argument>(Ret->getReturnValue()->stripPointerCasts());
1003 if (!RetVal || RetVal->getType() != F->getReturnType())
1004 return nullptr;
1005
1006 if (!RetArg)
1007 RetArg = RetVal;
1008 else if (RetArg != RetVal)
1009 return nullptr;
1010 }
1011
1012 return RetArg;
1013 };
1014
1015 if (Argument *RetArg = FindRetArg()) {
1016 RetArg->addAttr(Attribute::Returned);
1017 ++NumReturned;
1018 Changed.insert(F);
1019 }
1020 }
1021}
1022
1023/// If a callsite has arguments that are also arguments to the parent function,
1024/// try to propagate attributes from the callsite's arguments to the parent's
1025/// arguments. This may be important because inlining can cause information loss
1026/// when attribute knowledge disappears with the inlined call.
1029 return false;
1030
1031 bool Changed = false;
1032
1033 // For an argument attribute to transfer from a callsite to the parent, the
1034 // call must be guaranteed to execute every time the parent is called.
1035 // Conservatively, just check for calls in the entry block that are guaranteed
1036 // to execute.
1037 // TODO: This could be enhanced by testing if the callsite post-dominates the
1038 // entry block or by doing simple forward walks or backward walks to the
1039 // callsite.
1040 BasicBlock &Entry = F.getEntryBlock();
1041 for (Instruction &I : Entry) {
1042 if (auto *CB = dyn_cast<CallBase>(&I)) {
1043 if (auto *CalledFunc = CB->getCalledFunction()) {
1044 for (auto &CSArg : CalledFunc->args()) {
1045 unsigned ArgNo = CSArg.getArgNo();
1046 auto *FArg = dyn_cast<Argument>(CB->getArgOperand(ArgNo));
1047 if (!FArg)
1048 continue;
1049
1050 if (CSArg.hasNonNullAttr(/*AllowUndefOrPoison=*/false)) {
1051 // If the non-null callsite argument operand is an argument to 'F'
1052 // (the caller) and the call is guaranteed to execute, then the
1053 // value must be non-null throughout 'F'.
1054 if (!FArg->hasNonNullAttr()) {
1055 FArg->addAttr(Attribute::NonNull);
1056 Changed = true;
1057 }
1058 } else if (FPClassTest CSNoFPClass = CB->getParamNoFPClass(ArgNo);
1059 CSNoFPClass != fcNone &&
1060 CB->paramHasAttr(ArgNo, Attribute::NoUndef)) {
1061 FPClassTest ArgNoFPClass = FArg->getNoFPClass();
1062
1063 if ((CSNoFPClass | ArgNoFPClass) != ArgNoFPClass) {
1064 FArg->addAttr(Attribute::getWithNoFPClass(
1065 FArg->getContext(), CSNoFPClass | ArgNoFPClass));
1066 Changed = true;
1067 }
1068 }
1069 }
1070 }
1071 }
1073 break;
1074 }
1075
1076 return Changed;
1077}
1078
1080 assert(A && "Argument must not be null.");
1081
1082 bool Changed = false;
1083 if (!Props.IsFree && !A->hasAttribute(Attribute::NoFree) &&
1084 !A->hasAttribute(Attribute::NoFreeObj)) {
1085 ++NumNoFreeArg;
1086 A->addAttr(Attribute::NoFree);
1087 Changed = true;
1088 }
1089
1090 if (Props.IsRead && Props.IsWrite)
1091 return Changed;
1092
1094 if (Props.IsRead)
1095 Attr = Attribute::ReadOnly;
1096 else if (Props.IsWrite)
1097 Attr = Attribute::WriteOnly;
1098 else
1099 Attr = Attribute::ReadNone;
1100
1101 // If the argument already has the attribute, nothing needs to be done.
1102 if (A->hasAttribute(Attr))
1103 return false;
1104
1105 // Otherwise, remove potentially conflicting attribute, add the new one,
1106 // and update statistics.
1107 A->removeAttr(Attribute::WriteOnly);
1108 A->removeAttr(Attribute::ReadOnly);
1109 A->removeAttr(Attribute::ReadNone);
1110 // Remove conflicting writable attribute.
1111 if (Attr == Attribute::ReadNone || Attr == Attribute::ReadOnly)
1112 A->removeAttr(Attribute::Writable);
1113 A->addAttr(Attr);
1114 if (Attr == Attribute::ReadOnly)
1115 ++NumReadOnlyArg;
1116 else if (Attr == Attribute::WriteOnly)
1117 ++NumWriteOnlyArg;
1118 else
1119 ++NumReadNoneArg;
1120 return true;
1121}
1122
1124 auto ArgumentUses = collectArgumentUsesPerBlock(A, F);
1125 // No write anywhere in the function, bail.
1126 if (!ArgumentUses.HasAnyWrite)
1127 return false;
1128
1129 auto &UsesPerBlock = ArgumentUses.UsesPerBlock;
1130 BasicBlock &EntryBB = F.getEntryBlock();
1131 // A map to store the argument ranges initialized by a BasicBlock (including
1132 // its successors).
1134 // Visit the successors of "BB" block and the instructions in BB (post-order)
1135 // to get the argument ranges initialized by "BB" (including its successors).
1136 // The result will be cached in "Initialized".
1137 auto VisitBlock = [&](const BasicBlock *BB) -> ConstantRangeList {
1138 auto UPB = UsesPerBlock.find(BB);
1140
1141 // Start with intersection of successors.
1142 // If this block has any clobbering use, we're going to clear out the
1143 // ranges at some point in this block anyway, so don't bother looking at
1144 // successors.
1145 if (UPB == UsesPerBlock.end() || !UPB->second.HasUnknownAccess) {
1146 bool HasAddedSuccessor = false;
1147 for (auto *Succ : successors(BB)) {
1148 if (auto SuccI = Initialized.find(Succ); SuccI != Initialized.end()) {
1149 if (HasAddedSuccessor) {
1150 CRL = CRL.intersectWith(SuccI->second);
1151 } else {
1152 CRL = SuccI->second;
1153 HasAddedSuccessor = true;
1154 }
1155 } else {
1156 CRL = ConstantRangeList();
1157 break;
1158 }
1159 }
1160 }
1161
1162 if (UPB != UsesPerBlock.end()) {
1163 // Sort uses in this block by instruction order.
1165 append_range(Insts, UPB->second.Insts);
1166 sort(Insts, [](std::pair<Instruction *, ArgumentAccessInfo> &LHS,
1167 std::pair<Instruction *, ArgumentAccessInfo> &RHS) {
1168 return LHS.first->comesBefore(RHS.first);
1169 });
1170
1171 // From the end of the block to the beginning of the block, set
1172 // initializes ranges.
1173 for (auto &[_, Info] : reverse(Insts)) {
1174 if (Info.ArgAccessType == ArgumentAccessInfo::AccessType::Unknown ||
1175 Info.ArgAccessType ==
1176 ArgumentAccessInfo::AccessType::WriteWithSideEffect)
1177 CRL = ConstantRangeList();
1178 if (!Info.AccessRanges.empty()) {
1179 if (Info.ArgAccessType == ArgumentAccessInfo::AccessType::Write ||
1180 Info.ArgAccessType ==
1181 ArgumentAccessInfo::AccessType::WriteWithSideEffect) {
1182 CRL = CRL.unionWith(Info.AccessRanges);
1183 } else {
1184 assert(Info.ArgAccessType == ArgumentAccessInfo::AccessType::Read);
1185 for (const auto &ReadRange : Info.AccessRanges)
1186 CRL.subtract(ReadRange);
1187 }
1188 }
1189 }
1190 }
1191 return CRL;
1192 };
1193
1194 ConstantRangeList EntryCRL;
1195 // If all write instructions are in the EntryBB, or if the EntryBB has
1196 // a clobbering use, we only need to look at EntryBB.
1197 bool OnlyScanEntryBlock = !ArgumentUses.HasWriteOutsideEntryBB;
1198 if (!OnlyScanEntryBlock)
1199 if (auto EntryUPB = UsesPerBlock.find(&EntryBB);
1200 EntryUPB != UsesPerBlock.end())
1201 OnlyScanEntryBlock = EntryUPB->second.HasUnknownAccess;
1202 if (OnlyScanEntryBlock) {
1203 EntryCRL = VisitBlock(&EntryBB);
1204 if (EntryCRL.empty())
1205 return false;
1206 } else {
1207 // Now we have to go through CFG to get the initialized argument ranges
1208 // across blocks. With dominance and post-dominance, the initialized ranges
1209 // by a block include both accesses inside this block and accesses in its
1210 // (transitive) successors. So visit successors before predecessors with a
1211 // post-order walk of the blocks and memorize the results in "Initialized".
1212 for (const BasicBlock *BB : post_order(&F)) {
1213 ConstantRangeList CRL = VisitBlock(BB);
1214 if (!CRL.empty())
1215 Initialized[BB] = CRL;
1216 }
1217
1218 auto EntryCRLI = Initialized.find(&EntryBB);
1219 if (EntryCRLI == Initialized.end())
1220 return false;
1221
1222 EntryCRL = EntryCRLI->second;
1223 }
1224
1225 assert(!EntryCRL.empty() &&
1226 "should have bailed already if EntryCRL is empty");
1227
1228 if (A.hasAttribute(Attribute::Initializes)) {
1229 ConstantRangeList PreviousCRL =
1230 A.getAttribute(Attribute::Initializes).getValueAsConstantRangeList();
1231 if (PreviousCRL == EntryCRL)
1232 return false;
1233 EntryCRL = EntryCRL.unionWith(PreviousCRL);
1234 }
1235
1236 A.addAttr(Attribute::get(A.getContext(), Attribute::Initializes,
1237 EntryCRL.rangesRef()));
1238
1239 return true;
1240}
1241
1242/// Deduce nocapture attributes for the SCC.
1243static void addArgumentAttrs(const SCCNodeSet &SCCNodes,
1245 bool SkipInitializes) {
1246 ArgumentGraph AG;
1247
1248 auto DetermineAccessAttrsForSingleton = [](Argument *A) {
1250 Self.insert(A);
1252 };
1253
1254 // Check each function in turn, determining which pointer arguments are not
1255 // captured.
1256 for (Function *F : SCCNodes) {
1257 // We can infer and propagate function attributes only when we know that the
1258 // definition we'll get at link time is *exactly* the definition we see now.
1259 // For more details, see GlobalValue::mayBeDerefined.
1260 if (!F->hasExactDefinition())
1261 continue;
1262
1264 Changed.insert(F);
1265
1266 // Functions that are readonly (or readnone) and nounwind and don't return
1267 // a value can't capture arguments. Don't analyze them.
1268 if (F->onlyReadsMemory() && F->doesNotThrow() && F->willReturn() &&
1269 F->getReturnType()->isVoidTy()) {
1270 for (Argument &A : F->args()) {
1271 if (A.getType()->isPointerTy() && !A.hasNoCaptureAttr()) {
1272 A.addAttr(Attribute::getWithCaptureInfo(A.getContext(),
1274 ++NumCapturesNone;
1275 Changed.insert(F);
1276 }
1277 }
1278 continue;
1279 }
1280
1281 for (Argument &A : F->args()) {
1282 if (!A.getType()->isPointerTy())
1283 continue;
1284 bool HasNonLocalUses = false;
1285 CaptureInfo OrigCI = A.getAttributes().getCaptureInfo();
1286 if (!capturesNothing(OrigCI)) {
1287 ArgumentUsesTracker Tracker(SCCNodes);
1288 PointerMayBeCaptured(&A, &Tracker);
1289 CaptureInfo NewCI = Tracker.CI & OrigCI;
1290 if (NewCI != OrigCI) {
1291 if (Tracker.Uses.empty()) {
1292 // If the information is complete, add the attribute now.
1293 A.addAttr(Attribute::getWithCaptureInfo(A.getContext(), NewCI));
1294 addCapturesStat(NewCI);
1295 Changed.insert(F);
1296 } else {
1297 // If it's not trivially captured and not trivially not captured,
1298 // then it must be calling into another function in our SCC. Save
1299 // its particulars for Argument-SCC analysis later.
1300 ArgumentGraphNode *Node = AG[&A];
1301 Node->CC = CaptureComponents(NewCI);
1302 for (Argument *Use : Tracker.Uses) {
1303 Node->Uses.push_back(AG[Use]);
1304 if (Use != &A)
1305 HasNonLocalUses = true;
1306 }
1307 }
1308 }
1309 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
1310 }
1311 if (!HasNonLocalUses && !A.onlyReadsMemory()) {
1312 // Can we determine that it's readonly/readnone/writeonly without doing
1313 // an SCC? Note that we don't allow any calls at all here, or else our
1314 // result will be dependent on the iteration order through the
1315 // functions in the SCC.
1316 if (DetermineAccessAttrsForSingleton(&A))
1317 Changed.insert(F);
1318 }
1319 if (!SkipInitializes && !A.onlyReadsMemory()) {
1320 if (inferInitializes(A, *F))
1321 Changed.insert(F);
1322 }
1323 }
1324 }
1325
1326 // The graph we've collected is partial because we stopped scanning for
1327 // argument uses once we solved the argument trivially. These partial nodes
1328 // show up as ArgumentGraphNode objects with an empty Uses list, and for
1329 // these nodes the final decision about whether they capture has already been
1330 // made. If the definition doesn't have a 'nocapture' attribute by now, it
1331 // captures.
1332
1333 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
1334 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
1335 if (ArgumentSCC.size() == 1) {
1336 if (!ArgumentSCC[0]->Definition)
1337 continue; // synthetic root node
1338
1339 // eg. "void f(int* x) { if (...) f(x); }"
1340 if (ArgumentSCC[0]->Uses.size() == 1 &&
1341 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
1342 Argument *A = ArgumentSCC[0]->Definition;
1343 CaptureInfo OrigCI = A->getAttributes().getCaptureInfo();
1344 CaptureInfo NewCI = CaptureInfo(ArgumentSCC[0]->CC) & OrigCI;
1345 if (NewCI != OrigCI) {
1346 A->addAttr(Attribute::getWithCaptureInfo(A->getContext(), NewCI));
1347 addCapturesStat(NewCI);
1348 Changed.insert(A->getParent());
1349 }
1350
1351 // Infer the access attributes given the new captures one
1352 if (DetermineAccessAttrsForSingleton(A))
1353 Changed.insert(A->getParent());
1354 }
1355 continue;
1356 }
1357
1358 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
1359 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
1360 // quickly looking up whether a given Argument is in this ArgumentSCC.
1361 for (ArgumentGraphNode *I : ArgumentSCC) {
1362 ArgumentSCCNodes.insert(I->Definition);
1363 }
1364
1365 // At the SCC level, only track merged CaptureComponents. We're not
1366 // currently prepared to handle propagation of return-only captures across
1367 // the SCC.
1369 for (ArgumentGraphNode *N : ArgumentSCC) {
1370 for (ArgumentGraphNode *Use : N->Uses) {
1371 Argument *A = Use->Definition;
1372 if (ArgumentSCCNodes.count(A))
1373 CC |= Use->CC;
1374 else
1375 CC |= CaptureComponents(A->getAttributes().getCaptureInfo());
1376 }
1377 if (capturesAll(CC))
1378 break;
1379 }
1380
1381 if (!capturesAll(CC)) {
1382 for (ArgumentGraphNode *N : ArgumentSCC) {
1383 Argument *A = N->Definition;
1384 CaptureInfo OrigCI = A->getAttributes().getCaptureInfo();
1385 CaptureInfo NewCI = CaptureInfo(N->CC | CC) & OrigCI;
1386 if (NewCI != OrigCI) {
1387 A->addAttr(Attribute::getWithCaptureInfo(A->getContext(), NewCI));
1388 addCapturesStat(NewCI);
1389 Changed.insert(A->getParent());
1390 }
1391 }
1392 }
1393
1395 // As the pointer provenance may be captured, determine the pointer
1396 // attributes looking at each argument individually.
1397 for (ArgumentGraphNode *N : ArgumentSCC) {
1398 if (DetermineAccessAttrsForSingleton(N->Definition))
1399 Changed.insert(N->Definition->getParent());
1400 }
1401 continue;
1402 }
1403
1404 // We also want to compute readonly/readnone/writeonly. With a small number
1405 // of false negatives, we can assume that any pointer which is captured
1406 // isn't going to be provably readonly or readnone, since by definition
1407 // we can't analyze all uses of a captured pointer.
1408 //
1409 // The false negatives happen when the pointer is captured by a function
1410 // that promises readonly/readnone behaviour on the pointer, then the
1411 // pointer's lifetime ends before anything that writes to arbitrary memory.
1412 // Also, a readonly/readnone pointer may be returned, but returning a
1413 // pointer is capturing it.
1414
1415 ArgAccessProperties Props;
1416 for (ArgumentGraphNode *N : ArgumentSCC) {
1417 Argument *A = N->Definition;
1418 Props |= determinePointerAccessAttrs(A, ArgumentSCCNodes);
1419 if (Props.hasAll())
1420 break;
1421 }
1422
1423 if (!Props.hasAll()) {
1424 for (ArgumentGraphNode *N : ArgumentSCC) {
1425 Argument *A = N->Definition;
1426 if (addAccessAttrs(A, Props))
1427 Changed.insert(A->getParent());
1428 }
1429 }
1430 }
1431}
1432
1433/// Tests whether a function is "malloc-like".
1434///
1435/// A function is "malloc-like" if it returns either null or a pointer that
1436/// doesn't alias any other pointer visible to the caller.
1437static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
1438 SmallSetVector<Value *, 8> FlowsToReturn;
1439 for (BasicBlock &BB : *F)
1440 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
1441 FlowsToReturn.insert(Ret->getReturnValue());
1442
1443 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
1444 Value *RetVal = FlowsToReturn[i];
1445
1446 if (Constant *C = dyn_cast<Constant>(RetVal)) {
1447 if (!C->isNullValue() && !isa<UndefValue>(C))
1448 return false;
1449
1450 continue;
1451 }
1452
1453 if (isa<Argument>(RetVal))
1454 return false;
1455
1456 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
1457 switch (RVI->getOpcode()) {
1458 // Extend the analysis by looking upwards.
1459 case Instruction::BitCast:
1460 case Instruction::GetElementPtr:
1461 case Instruction::AddrSpaceCast:
1462 FlowsToReturn.insert(RVI->getOperand(0));
1463 continue;
1464 case Instruction::Select: {
1466 FlowsToReturn.insert(SI->getTrueValue());
1467 FlowsToReturn.insert(SI->getFalseValue());
1468 continue;
1469 }
1470 case Instruction::PHI: {
1471 PHINode *PN = cast<PHINode>(RVI);
1472 FlowsToReturn.insert_range(PN->incoming_values());
1473 continue;
1474 }
1475
1476 // Check whether the pointer came from an allocation.
1477 case Instruction::Alloca:
1478 break;
1479 case Instruction::Call:
1480 case Instruction::Invoke: {
1481 CallBase &CB = cast<CallBase>(*RVI);
1482 if (CB.hasRetAttr(Attribute::NoAlias))
1483 break;
1484 if (CB.getCalledFunction() && SCCNodes.count(CB.getCalledFunction()))
1485 break;
1486 [[fallthrough]];
1487 }
1488 default:
1489 return false; // Did not come from an allocation.
1490 }
1491
1492 // Only capturing the provenance of the result prevents it from being
1493 // noalias.
1494 if (capturesAnything(
1496 .WithoutRet))
1497 return false;
1498 }
1499
1500 return true;
1501}
1502
1503/// Deduce noalias attributes for the SCC.
1504static void addNoAliasAttrs(const SCCNodeSet &SCCNodes,
1506 // Check each function in turn, determining which functions return noalias
1507 // pointers.
1508 for (Function *F : SCCNodes) {
1509 // Already noalias.
1510 if (F->returnDoesNotAlias())
1511 continue;
1512
1513 // We can infer and propagate function attributes only when we know that the
1514 // definition we'll get at link time is *exactly* the definition we see now.
1515 // For more details, see GlobalValue::mayBeDerefined.
1516 if (!F->hasExactDefinition())
1517 return;
1518
1519 // We annotate noalias return values, which are only applicable to
1520 // pointer types.
1521 if (!F->getReturnType()->isPointerTy())
1522 continue;
1523
1524 if (!isFunctionMallocLike(F, SCCNodes))
1525 return;
1526 }
1527
1528 for (Function *F : SCCNodes) {
1529 if (F->returnDoesNotAlias() ||
1530 !F->getReturnType()->isPointerTy())
1531 continue;
1532
1533 F->setReturnDoesNotAlias();
1534 ++NumNoAlias;
1535 Changed.insert(F);
1536 }
1537}
1538
1539/// Tests whether this function is known to not return null.
1540///
1541/// Requires that the function returns a pointer.
1542///
1543/// Returns true if it believes the function will not return a null, and sets
1544/// \p Speculative based on whether the returned conclusion is a speculative
1545/// conclusion due to SCC calls.
1546static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
1547 bool &Speculative) {
1548 assert(F->getReturnType()->isPointerTy() &&
1549 "nonnull only meaningful on pointer types");
1550 Speculative = false;
1551
1552 SmallSetVector<Value *, 8> FlowsToReturn;
1553 for (BasicBlock &BB : *F)
1554 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
1555 FlowsToReturn.insert(Ret->getReturnValue());
1556
1557 auto &DL = F->getDataLayout();
1558
1559 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
1560 Value *RetVal = FlowsToReturn[i];
1561
1562 // If this value is locally known to be non-null, we're good
1563 if (isKnownNonZero(RetVal, DL))
1564 continue;
1565
1566 // Otherwise, we need to look upwards since we can't make any local
1567 // conclusions.
1568 Instruction *RVI = dyn_cast<Instruction>(RetVal);
1569 if (!RVI)
1570 return false;
1571 switch (RVI->getOpcode()) {
1572 // Extend the analysis by looking upwards.
1573 case Instruction::BitCast:
1574 case Instruction::AddrSpaceCast:
1575 FlowsToReturn.insert(RVI->getOperand(0));
1576 continue;
1577 case Instruction::GetElementPtr:
1578 if (cast<GEPOperator>(RVI)->isInBounds()) {
1579 FlowsToReturn.insert(RVI->getOperand(0));
1580 continue;
1581 }
1582 return false;
1583 case Instruction::Select: {
1585 FlowsToReturn.insert(SI->getTrueValue());
1586 FlowsToReturn.insert(SI->getFalseValue());
1587 continue;
1588 }
1589 case Instruction::PHI: {
1590 PHINode *PN = cast<PHINode>(RVI);
1591 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1592 FlowsToReturn.insert(PN->getIncomingValue(i));
1593 continue;
1594 }
1595 case Instruction::Call:
1596 case Instruction::Invoke: {
1597 CallBase &CB = cast<CallBase>(*RVI);
1598 Function *Callee = CB.getCalledFunction();
1599 // A call to a node within the SCC is assumed to return null until
1600 // proven otherwise
1601 if (Callee && SCCNodes.count(Callee)) {
1602 Speculative = true;
1603 continue;
1604 }
1605 return false;
1606 }
1607 default:
1608 return false; // Unknown source, may be null
1609 };
1610 llvm_unreachable("should have either continued or returned");
1611 }
1612
1613 return true;
1614}
1615
1616/// Deduce nonnull attributes for the SCC.
1617static void addNonNullAttrs(const SCCNodeSet &SCCNodes,
1619 // Speculative that all functions in the SCC return only nonnull
1620 // pointers. We may refute this as we analyze functions.
1621 bool SCCReturnsNonNull = true;
1622
1623 // Check each function in turn, determining which functions return nonnull
1624 // pointers.
1625 for (Function *F : SCCNodes) {
1626 // Already nonnull.
1627 if (F->getAttributes().hasRetAttr(Attribute::NonNull))
1628 continue;
1629
1630 // We can infer and propagate function attributes only when we know that the
1631 // definition we'll get at link time is *exactly* the definition we see now.
1632 // For more details, see GlobalValue::mayBeDerefined.
1633 if (!F->hasExactDefinition())
1634 return;
1635
1636 // We annotate nonnull return values, which are only applicable to
1637 // pointer types.
1638 if (!F->getReturnType()->isPointerTy())
1639 continue;
1640
1641 bool Speculative = false;
1642 if (isReturnNonNull(F, SCCNodes, Speculative)) {
1643 if (!Speculative) {
1644 // Mark the function eagerly since we may discover a function
1645 // which prevents us from speculating about the entire SCC
1646 LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1647 << " as nonnull\n");
1648 F->addRetAttr(Attribute::NonNull);
1649 ++NumNonNullReturn;
1650 Changed.insert(F);
1651 }
1652 continue;
1653 }
1654 // At least one function returns something which could be null, can't
1655 // speculate any more.
1656 SCCReturnsNonNull = false;
1657 }
1658
1659 if (SCCReturnsNonNull) {
1660 for (Function *F : SCCNodes) {
1661 if (F->getAttributes().hasRetAttr(Attribute::NonNull) ||
1662 !F->getReturnType()->isPointerTy())
1663 continue;
1664
1665 LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
1666 F->addRetAttr(Attribute::NonNull);
1667 ++NumNonNullReturn;
1668 Changed.insert(F);
1669 }
1670 }
1671}
1672
1673/// Deduce noundef attributes for the SCC.
1674static void addNoUndefAttrs(const SCCNodeSet &SCCNodes,
1676 // Check each function in turn, determining which functions return noundef
1677 // values.
1678 for (Function *F : SCCNodes) {
1679 // Already noundef.
1680 AttributeList Attrs = F->getAttributes();
1681 if (Attrs.hasRetAttr(Attribute::NoUndef))
1682 continue;
1683
1684 // We can infer and propagate function attributes only when we know that the
1685 // definition we'll get at link time is *exactly* the definition we see now.
1686 // For more details, see GlobalValue::mayBeDerefined.
1687 if (!F->hasExactDefinition())
1688 return;
1689
1690 // MemorySanitizer assumes that the definition and declaration of a
1691 // function will be consistent. A function with sanitize_memory attribute
1692 // should be skipped from inference.
1693 if (F->hasFnAttribute(Attribute::SanitizeMemory))
1694 continue;
1695
1696 if (F->getReturnType()->isVoidTy())
1697 continue;
1698
1699 const DataLayout &DL = F->getDataLayout();
1700 if (all_of(*F, [&](BasicBlock &BB) {
1701 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
1702 // TODO: perform context-sensitive analysis?
1703 Value *RetVal = Ret->getReturnValue();
1705 return false;
1706
1707 // We know the original return value is not poison now, but it
1708 // could still be converted to poison by another return attribute.
1709 // Try to explicitly re-prove the relevant attributes.
1710 if (Attrs.hasRetAttr(Attribute::NonNull) &&
1711 !isKnownNonZero(RetVal, DL))
1712 return false;
1713
1714 if (MaybeAlign Align = Attrs.getRetAlignment())
1715 if (RetVal->getPointerAlignment(DL) < *Align)
1716 return false;
1717
1718 Attribute Attr = Attrs.getRetAttr(Attribute::Range);
1719 if (Attr.isValid() &&
1720 !Attr.getRange().contains(
1721 computeConstantRange(RetVal, /*ForSigned=*/false,
1722 SimplifyQuery(F->getDataLayout()))))
1723 return false;
1724
1725 FPClassTest AttrFPClass = Attrs.getRetNoFPClass();
1726 if (AttrFPClass != fcNone) {
1727 KnownFPClass ComputedFPClass = computeKnownFPClass(RetVal, DL);
1728 if (!ComputedFPClass.isKnownNever(AttrFPClass))
1729 return false;
1730 }
1731 }
1732 return true;
1733 })) {
1734 F->addRetAttr(Attribute::NoUndef);
1735 ++NumNoUndefReturn;
1736 Changed.insert(F);
1737 }
1738 }
1739}
1740
1741namespace {
1742
1743/// Collects a set of attribute inference requests and performs them all in one
1744/// go on a single SCC Node. Inference involves scanning function bodies
1745/// looking for instructions that violate attribute assumptions.
1746/// As soon as all the bodies are fine we are free to set the attribute.
1747/// Customization of inference for individual attributes is performed by
1748/// providing a handful of predicates for each attribute.
1749class AttributeInferer {
1750public:
1751 /// Describes a request for inference of a single attribute.
1752 struct InferenceDescriptor {
1753
1754 /// Returns true if this function does not have to be handled.
1755 /// General intent for this predicate is to provide an optimization
1756 /// for functions that do not need this attribute inference at all
1757 /// (say, for functions that already have the attribute).
1758 std::function<bool(const Function &)> SkipFunction;
1759
1760 /// Returns true if this instruction violates attribute assumptions.
1761 std::function<bool(Instruction &)> InstrBreaksAttribute;
1762
1763 /// Sets the inferred attribute for this function.
1764 std::function<void(Function &)> SetAttribute;
1765
1766 /// Attribute we derive.
1767 Attribute::AttrKind AKind;
1768
1769 /// If true, only "exact" definitions can be used to infer this attribute.
1770 /// See GlobalValue::isDefinitionExact.
1771 bool RequiresExactDefinition;
1772
1773 InferenceDescriptor(Attribute::AttrKind AK,
1774 std::function<bool(const Function &)> SkipFunc,
1775 std::function<bool(Instruction &)> InstrScan,
1776 std::function<void(Function &)> SetAttr,
1777 bool ReqExactDef)
1778 : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1779 SetAttribute(SetAttr), AKind(AK),
1780 RequiresExactDefinition(ReqExactDef) {}
1781 };
1782
1783private:
1784 SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1785
1786public:
1787 void registerAttrInference(InferenceDescriptor AttrInference) {
1788 InferenceDescriptors.push_back(AttrInference);
1789 }
1790
1791 void run(const SCCNodeSet &SCCNodes, SmallPtrSet<Function *, 8> &Changed);
1792};
1793
1794/// Perform all the requested attribute inference actions according to the
1795/// attribute predicates stored before.
1796void AttributeInferer::run(const SCCNodeSet &SCCNodes,
1798 SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1799 // Go through all the functions in SCC and check corresponding attribute
1800 // assumptions for each of them. Attributes that are invalid for this SCC
1801 // will be removed from InferInSCC.
1802 for (Function *F : SCCNodes) {
1803
1804 // No attributes whose assumptions are still valid - done.
1805 if (InferInSCC.empty())
1806 return;
1807
1808 // Check if our attributes ever need scanning/can be scanned.
1809 llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1810 if (ID.SkipFunction(*F))
1811 return false;
1812
1813 // Remove from further inference (invalidate) when visiting a function
1814 // that has no instructions to scan/has an unsuitable definition.
1815 return F->isDeclaration() ||
1816 (ID.RequiresExactDefinition && !F->hasExactDefinition());
1817 });
1818
1819 // For each attribute still in InferInSCC that doesn't explicitly skip F,
1820 // set up the F instructions scan to verify assumptions of the attribute.
1823 InferInSCC, std::back_inserter(InferInThisFunc),
1824 [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1825
1826 if (InferInThisFunc.empty())
1827 continue;
1828
1829 // Start instruction scan.
1830 for (Instruction &I : instructions(*F)) {
1831 llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1832 if (!ID.InstrBreaksAttribute(I))
1833 return false;
1834 // Remove attribute from further inference on any other functions
1835 // because attribute assumptions have just been violated.
1836 llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1837 return D.AKind == ID.AKind;
1838 });
1839 // Remove attribute from the rest of current instruction scan.
1840 return true;
1841 });
1842
1843 if (InferInThisFunc.empty())
1844 break;
1845 }
1846 }
1847
1848 if (InferInSCC.empty())
1849 return;
1850
1851 for (Function *F : SCCNodes)
1852 // At this point InferInSCC contains only functions that were either:
1853 // - explicitly skipped from scan/inference, or
1854 // - verified to have no instructions that break attribute assumptions.
1855 // Hence we just go and force the attribute for all non-skipped functions.
1856 for (auto &ID : InferInSCC) {
1857 if (ID.SkipFunction(*F))
1858 continue;
1859 Changed.insert(F);
1860 ID.SetAttribute(*F);
1861 }
1862}
1863
1864struct SCCNodesResult {
1865 SCCNodeSet SCCNodes;
1866};
1867
1868} // end anonymous namespace
1869
1870/// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1872 const SCCNodeSet &SCCNodes) {
1873 const CallBase *CB = dyn_cast<CallBase>(&I);
1874 // Breaks non-convergent assumption if CS is a convergent call to a function
1875 // not in the SCC.
1876 return CB && CB->isConvergent() &&
1877 !SCCNodes.contains(CB->getCalledFunction());
1878}
1879
1880/// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1881static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1882 if (!I.mayThrow(/* IncludePhaseOneUnwind */ true))
1883 return false;
1884 if (const auto *CI = dyn_cast<CallInst>(&I)) {
1885 if (Function *Callee = CI->getCalledFunction()) {
1886 // I is a may-throw call to a function inside our SCC. This doesn't
1887 // invalidate our current working assumption that the SCC is no-throw; we
1888 // just have to scan that other function.
1889 if (SCCNodes.contains(Callee))
1890 return false;
1891 }
1892 }
1893 return true;
1894}
1895
1896/// Helper for NoFree inference predicate InstrBreaksAttribute.
1897static bool InstrBreaksNoFree(Instruction &I, const SCCNodeSet &SCCNodes) {
1899 if (!CB) {
1900 // Synchronization may establish happens-before with a free on another
1901 // thread.
1902 return I.maySynchronize();
1903 }
1904
1905 if (CB->hasFnAttr(Attribute::NoFree))
1906 return false;
1907
1908 // Speculatively assume in SCC.
1909 if (Function *Callee = CB->getCalledFunction())
1910 if (SCCNodes.contains(Callee))
1911 return false;
1912
1913 return true;
1914}
1915
1916static bool InstrBreaksNoSync(Instruction &I, const SCCNodeSet &SCCNodes) {
1917 if (!I.maySynchronize())
1918 return false;
1919
1920 // Optimistically assume calls within the SCC are nosync: if nothing else in
1921 // the SCC synchronizes, the assumption holds.
1922 if (auto *CB = dyn_cast<CallBase>(&I))
1923 if (Function *Callee = CB->getCalledFunction())
1924 if (SCCNodes.contains(Callee))
1925 return false;
1926
1927 return true;
1928}
1929
1930/// Attempt to remove convergent function attribute when possible.
1931///
1932/// Returns true if any changes to function attributes were made.
1933static void inferConvergent(const SCCNodeSet &SCCNodes,
1935 AttributeInferer AI;
1936
1937 // Request to remove the convergent attribute from all functions in the SCC
1938 // if every callsite within the SCC is not convergent (except for calls
1939 // to functions within the SCC).
1940 // Note: Removal of the attr from the callsites will happen in
1941 // InstCombineCalls separately.
1942 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1943 Attribute::Convergent,
1944 // Skip non-convergent functions.
1945 [](const Function &F) { return !F.isConvergent(); },
1946 // Instructions that break non-convergent assumption.
1947 [SCCNodes](Instruction &I) {
1948 return InstrBreaksNonConvergent(I, SCCNodes);
1949 },
1950 [](Function &F) {
1951 LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1952 << "\n");
1953 F.setNotConvergent();
1954 },
1955 /* RequiresExactDefinition= */ false});
1956 // Perform all the requested attribute inference actions.
1957 AI.run(SCCNodes, Changed);
1958}
1959
1960/// Infer attributes from all functions in the SCC by scanning every
1961/// instruction for compliance to the attribute assumptions.
1962///
1963/// Returns true if any changes to function attributes were made.
1964static void inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes,
1966 AttributeInferer AI;
1967
1969 // Request to infer nounwind attribute for all the functions in the SCC if
1970 // every callsite within the SCC is not throwing (except for calls to
1971 // functions within the SCC). Note that nounwind attribute suffers from
1972 // derefinement - results may change depending on how functions are
1973 // optimized. Thus it can be inferred only from exact definitions.
1974 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1975 Attribute::NoUnwind,
1976 // Skip non-throwing functions.
1977 [](const Function &F) { return F.doesNotThrow(); },
1978 // Instructions that break non-throwing assumption.
1979 [&SCCNodes](Instruction &I) {
1980 return InstrBreaksNonThrowing(I, SCCNodes);
1981 },
1982 [](Function &F) {
1984 << "Adding nounwind attr to fn " << F.getName() << "\n");
1985 F.setDoesNotThrow();
1986 ++NumNoUnwind;
1987 },
1988 /* RequiresExactDefinition= */ true});
1989
1991 // Request to infer nofree attribute for all the functions in the SCC if
1992 // every callsite within the SCC does not directly or indirectly free
1993 // memory (except for calls to functions within the SCC). Note that nofree
1994 // attribute suffers from derefinement - results may change depending on
1995 // how functions are optimized. Thus it can be inferred only from exact
1996 // definitions.
1997 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1998 Attribute::NoFree,
1999 // Skip functions known not to free memory.
2000 [](const Function &F) { return F.doesNotFreeMemory(); },
2001 // Instructions that break non-deallocating assumption.
2002 [&SCCNodes](Instruction &I) {
2003 return InstrBreaksNoFree(I, SCCNodes);
2004 },
2005 [](Function &F) {
2007 << "Adding nofree attr to fn " << F.getName() << "\n");
2008 F.setDoesNotFreeMemory();
2009 ++NumNoFree;
2010 },
2011 /* RequiresExactDefinition= */ true});
2012
2013 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
2014 Attribute::NoSync,
2015 // Skip already marked functions.
2016 [](const Function &F) { return F.hasNoSync(); },
2017 // Instructions that break nosync assumption.
2018 [&SCCNodes](Instruction &I) {
2019 return InstrBreaksNoSync(I, SCCNodes);
2020 },
2021 [](Function &F) {
2023 << "Adding nosync attr to fn " << F.getName() << "\n");
2024 F.setNoSync();
2025 ++NumNoSync;
2026 },
2027 /* RequiresExactDefinition= */ true});
2028
2029 // Perform all the requested attribute inference actions.
2030 AI.run(SCCNodes, Changed);
2031}
2032
2033// Determines if the function 'F' can be marked 'norecurse'.
2034// It returns true if any call within 'F' could lead to a recursive
2035// call back to 'F', and false otherwise.
2036// The 'AnyFunctionsAddressIsTaken' parameter is a module-wide flag
2037// that is true if any function's address is taken, or if any function
2038// has external linkage. This is used to determine the safety of
2039// external/library calls.
2041 bool AnyFunctionsAddressIsTaken = true) {
2042 for (const auto &BB : F) {
2043 for (const auto &I : BB) {
2044 if (const auto *CB = dyn_cast<CallBase>(&I)) {
2045 const Function *Callee = CB->getCalledFunction();
2046 if (!Callee || Callee == &F)
2047 return true;
2048
2049 if (Callee->doesNotRecurse())
2050 continue;
2051
2052 if (!AnyFunctionsAddressIsTaken ||
2053 (Callee->isDeclaration() &&
2054 Callee->hasFnAttribute(Attribute::NoCallback)))
2055 continue;
2056 return true;
2057 }
2058 }
2059 }
2060 return false;
2061}
2062
2063static void addNoRecurseAttrs(const SCCNodeSet &SCCNodes,
2065 // Try and identify functions that do not recurse.
2066
2067 // If the SCC contains multiple nodes we know for sure there is recursion.
2068 if (SCCNodes.size() != 1)
2069 return;
2070
2071 Function *F = *SCCNodes.begin();
2072 if (!F || !F->hasExactDefinition() || F->doesNotRecurse())
2073 return;
2074 if (!mayHaveRecursiveCallee(*F)) {
2075 // Every call was to a non-recursive function other than this function, and
2076 // we have no indirect recursion as the SCC size is one. This function
2077 // cannot recurse.
2078 F->setDoesNotRecurse();
2079 ++NumNoRecurse;
2080 Changed.insert(F);
2081 }
2082}
2083
2084// Set the noreturn function attribute if possible.
2085static void addNoReturnAttrs(const SCCNodeSet &SCCNodes,
2087 for (Function *F : SCCNodes) {
2088 if (!F || !F->hasExactDefinition() || F->hasFnAttribute(Attribute::Naked) ||
2089 F->doesNotReturn())
2090 continue;
2091
2092 if (!canReturn(*F)) {
2093 F->setDoesNotReturn();
2094 Changed.insert(F);
2095 }
2096 }
2097}
2098
2101 ColdPaths[&F.front()] = false;
2103 Jobs.push_back(&F.front());
2104
2105 while (!Jobs.empty()) {
2106 BasicBlock *BB = Jobs.pop_back_val();
2107
2108 // If block contains a cold callsite this path through the CG is cold.
2109 // Ignore whether the instructions actually are guaranteed to transfer
2110 // execution. Divergent behavior is considered unlikely.
2111 if (any_of(*BB, [](Instruction &I) {
2112 if (auto *CB = dyn_cast<CallBase>(&I))
2113 return CB->hasFnAttr(Attribute::Cold);
2114 return false;
2115 })) {
2116 ColdPaths[BB] = true;
2117 continue;
2118 }
2119
2120 auto Succs = successors(BB);
2121 // We found a path that doesn't go through any cold callsite.
2122 if (Succs.empty())
2123 return false;
2124
2125 // We didn't find a cold callsite in this BB, so check that all successors
2126 // contain a cold callsite (or that their successors do).
2127 // Potential TODO: We could use static branch hints to assume certain
2128 // successor paths are inherently cold, irrespective of if they contain a
2129 // cold callsite.
2130 for (BasicBlock *Succ : Succs) {
2131 // Start with false, this is necessary to ensure we don't turn loops into
2132 // cold.
2133 auto [Iter, Inserted] = ColdPaths.try_emplace(Succ, false);
2134 if (!Inserted) {
2135 if (Iter->second)
2136 continue;
2137 return false;
2138 }
2139 Jobs.push_back(Succ);
2140 }
2141 }
2142 return true;
2143}
2144
2145// Set the cold function attribute if possible.
2146static void addColdAttrs(const SCCNodeSet &SCCNodes,
2148 for (Function *F : SCCNodes) {
2149 if (!F || !F->hasExactDefinition() || F->hasFnAttribute(Attribute::Naked) ||
2150 F->hasFnAttribute(Attribute::Cold) || F->hasFnAttribute(Attribute::Hot))
2151 continue;
2152
2153 // Potential TODO: We could add attribute `cold` on functions with `coldcc`.
2154 if (allPathsGoThroughCold(*F)) {
2155 F->addFnAttr(Attribute::Cold);
2156 ++NumCold;
2157 Changed.insert(F);
2158 continue;
2159 }
2160 }
2161}
2162
2163static bool functionWillReturn(const Function &F) {
2164 // We can infer and propagate function attributes only when we know that the
2165 // definition we'll get at link time is *exactly* the definition we see now.
2166 // For more details, see GlobalValue::mayBeDerefined.
2167 if (!F.hasExactDefinition())
2168 return false;
2169
2170 // Must-progress function without side-effects must return.
2171 if (F.mustProgress() && F.onlyReadsMemory())
2172 return true;
2173
2174 // Can only analyze functions with a definition.
2175 if (F.isDeclaration())
2176 return false;
2177
2178 // Functions with loops require more sophisticated analysis, as the loop
2179 // may be infinite. For now, don't try to handle them.
2181 FindFunctionBackedges(F, Backedges);
2182 if (!Backedges.empty())
2183 return false;
2184
2185 // If there are no loops, then the function is willreturn if all calls in
2186 // it are willreturn.
2187 return all_of(instructions(F), [](const Instruction &I) {
2188 return I.willReturn();
2189 });
2190}
2191
2192// Set the willreturn function attribute if possible.
2193static void addWillReturn(const SCCNodeSet &SCCNodes,
2195 for (Function *F : SCCNodes) {
2196 if (!F || F->willReturn() || !functionWillReturn(*F))
2197 continue;
2198
2199 F->setWillReturn();
2200 NumWillReturn++;
2201 Changed.insert(F);
2202 }
2203}
2204
2205static SCCNodesResult createSCCNodeSet(ArrayRef<Function *> Functions) {
2206 SCCNodesResult Res;
2207 for (Function *F : Functions) {
2208 if (!F || F->hasOptNone() || F->hasFnAttribute(Attribute::Naked) ||
2209 F->isPresplitCoroutine()) {
2210 // Omit any functions we're trying not to optimize from the set.
2211 continue;
2212 }
2213
2214 Res.SCCNodes.insert(F);
2215 }
2216 return Res;
2217}
2218
2219template <typename AARGetterT>
2220static SmallPtrSet<Function *, 8>
2221deriveAttrsInPostOrder(ArrayRef<Function *> Functions, AARGetterT &&AARGetter,
2222 bool ArgAttrsOnly) {
2223 SCCNodesResult Nodes = createSCCNodeSet(Functions);
2224
2225 // Bail if the SCC only contains optnone functions.
2226 if (Nodes.SCCNodes.empty())
2227 return {};
2228
2230 if (ArgAttrsOnly) {
2231 // ArgAttrsOnly means to only infer attributes that may aid optimizations
2232 // on the *current* function. "initializes" attribute is to aid
2233 // optimizations (like DSE) on the callers, so skip "initializes" here.
2234 addArgumentAttrs(Nodes.SCCNodes, Changed, /*SkipInitializes=*/true);
2235 return Changed;
2236 }
2237
2238 addArgumentReturnedAttrs(Nodes.SCCNodes, Changed);
2239 addMemoryAttrs(Nodes.SCCNodes, AARGetter, Changed);
2240 addArgumentAttrs(Nodes.SCCNodes, Changed, /*SkipInitializes=*/false);
2241 inferConvergent(Nodes.SCCNodes, Changed);
2242 addNoReturnAttrs(Nodes.SCCNodes, Changed);
2243 addColdAttrs(Nodes.SCCNodes, Changed);
2244 addWillReturn(Nodes.SCCNodes, Changed);
2245 addNoUndefAttrs(Nodes.SCCNodes, Changed);
2246 addNoAliasAttrs(Nodes.SCCNodes, Changed);
2247 addNonNullAttrs(Nodes.SCCNodes, Changed);
2248 inferAttrsFromFunctionBodies(Nodes.SCCNodes, Changed);
2249 addNoRecurseAttrs(Nodes.SCCNodes, Changed);
2250
2251 // Finally, infer the maximal set of attributes from the ones we've inferred
2252 // above. This is handling the cases where one attribute on a signature
2253 // implies another, but for implementation reasons the inference rule for
2254 // the later is missing (or simply less sophisticated).
2255 for (Function *F : Nodes.SCCNodes)
2256 if (F)
2258 Changed.insert(F);
2259
2260 return Changed;
2261}
2262
2265 LazyCallGraph &CG,
2267 // Skip non-recursive functions if requested.
2268 // Only infer argument attributes for non-recursive functions, because
2269 // it can affect optimization behavior in conjunction with noalias.
2270 bool ArgAttrsOnly = false;
2271 if (C.size() == 1 && SkipNonRecursive) {
2272 LazyCallGraph::Node &N = *C.begin();
2273 if (!N->lookup(N))
2274 ArgAttrsOnly = true;
2275 }
2276
2278 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
2279
2280 // We pass a lambda into functions to wire them up to the analysis manager
2281 // for getting function analyses.
2282 auto AARGetter = [&](Function &F) -> AAResults & {
2283 return FAM.getResult<AAManager>(F);
2284 };
2285
2287 for (LazyCallGraph::Node &N : C) {
2288 Functions.push_back(&N.getFunction());
2289 }
2290
2291 auto ChangedFunctions =
2292 deriveAttrsInPostOrder(Functions, AARGetter, ArgAttrsOnly);
2293 if (ChangedFunctions.empty())
2294 return PreservedAnalyses::all();
2295
2296 // Invalidate analyses for modified functions so that we don't have to
2297 // invalidate all analyses for all functions in this SCC.
2298 PreservedAnalyses FuncPA;
2299 // We haven't changed the CFG for modified functions.
2300 FuncPA.preserveSet<CFGAnalyses>();
2301 for (Function *Changed : ChangedFunctions) {
2302 FAM.invalidate(*Changed, FuncPA);
2303 // Also invalidate any direct callers of changed functions since analyses
2304 // may care about attributes of direct callees. For example, MemorySSA cares
2305 // about whether or not a call's callee modifies memory and queries that
2306 // through function attributes.
2307 for (auto *U : Changed->users()) {
2308 if (auto *Call = dyn_cast<CallBase>(U)) {
2309 if (Call->getCalledOperand() == Changed)
2310 FAM.invalidate(*Call->getFunction(), FuncPA);
2311 }
2312 }
2313 }
2314
2316 // We have not added or removed functions.
2318 // We already invalidated all relevant function analyses above.
2320 return PA;
2321}
2322
2324 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
2325 static_cast<PassInfoMixin<PostOrderFunctionAttrsPass> *>(this)->printPipeline(
2326 OS, MapClassName2PassName);
2327 if (SkipNonRecursive)
2328 OS << "<skip-non-recursive-function-attrs>";
2329}
2330
2332 if (F.doesNotRecurse())
2333 return false;
2334
2335 // We check the preconditions for the function prior to calling this to avoid
2336 // the cost of building up a reversible post-order list. We assert them here
2337 // to make sure none of the invariants this relies on were violated.
2338 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
2339 assert(F.hasInternalLinkage() &&
2340 "Can only do top-down deduction for internal linkage functions!");
2341
2342 // If F is internal and all of its uses are calls from a non-recursive
2343 // functions, then none of its calls could in fact recurse without going
2344 // through a function marked norecurse, and so we can mark this function too
2345 // as norecurse. Note that the uses must actually be calls -- otherwise
2346 // a pointer to this function could be returned from a norecurse function but
2347 // this function could be recursively (indirectly) called. Note that this
2348 // also detects if F is directly recursive as F is not yet marked as
2349 // a norecurse function.
2350 for (auto &U : F.uses()) {
2351 const CallBase *CB = dyn_cast<CallBase>(U.getUser());
2352 if (!CB || !CB->isCallee(&U) ||
2353 !CB->getParent()->getParent()->doesNotRecurse())
2354 return false;
2355 }
2356 F.setDoesNotRecurse();
2357 ++NumNoRecurse;
2358 return true;
2359}
2360
2362 assert(!F.isDeclaration() && "Cannot deduce nofpclass without a definition!");
2363 unsigned NumArgs = F.arg_size();
2364 SmallVector<FPClassTest, 8> ArgsNoFPClass(NumArgs, fcAllFlags);
2365 FPClassTest RetNoFPClass = fcAllFlags;
2366
2367 bool Changed = false;
2368 for (User *U : F.users()) {
2369 auto *CB = dyn_cast<CallBase>(U);
2370 if (!CB || CB->getCalledFunction() != &F)
2371 return false;
2372
2373 RetNoFPClass &= CB->getRetNoFPClass();
2374 for (unsigned I = 0; I != NumArgs; ++I) {
2375 // TODO: Consider computeKnownFPClass, at least with a small search
2376 // depth. This will currently not catch non-splat vectors.
2377 const APFloat *Cst;
2378 if (match(CB->getArgOperand(I), m_APFloat(Cst)))
2379 ArgsNoFPClass[I] &= ~Cst->classify();
2380 else
2381 ArgsNoFPClass[I] &= CB->getParamNoFPClass(I);
2382 }
2383 }
2384
2385 LLVMContext &Ctx = F.getContext();
2386
2387 if (RetNoFPClass != fcNone) {
2388 FPClassTest OldAttr = F.getAttributes().getRetNoFPClass();
2389 if (OldAttr != RetNoFPClass) {
2390 F.addRetAttr(Attribute::getWithNoFPClass(Ctx, RetNoFPClass));
2391 Changed = true;
2392 }
2393 }
2394
2395 for (unsigned I = 0; I != NumArgs; ++I) {
2396 FPClassTest ArgNoFPClass = ArgsNoFPClass[I];
2397 if (ArgNoFPClass == fcNone)
2398 continue;
2399 FPClassTest OldAttr = F.getParamNoFPClass(I);
2400 if (OldAttr == ArgNoFPClass)
2401 continue;
2402
2403 F.addParamAttr(I, Attribute::getWithNoFPClass(Ctx, ArgNoFPClass));
2404 Changed = true;
2405 }
2406
2407 return Changed;
2408}
2409
2411 // We only have a post-order SCC traversal (because SCCs are inherently
2412 // discovered in post-order), so we accumulate them in a vector and then walk
2413 // it in reverse. This is simpler than using the RPO iterator infrastructure
2414 // because we need to combine SCC detection and the PO walk of the call
2415 // graph. We can also cheat egregiously because we're primarily interested in
2416 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
2417 // with multiple functions in them will clearly be recursive.
2418
2420 CG.buildRefSCCs();
2421 for (LazyCallGraph::RefSCC &RC : CG.postorder_ref_sccs()) {
2422 for (LazyCallGraph::SCC &SCC : RC) {
2423 if (SCC.size() != 1)
2424 continue;
2425 Function &F = SCC.begin()->getFunction();
2426 if (!F.isDeclaration() && F.hasInternalLinkage() && !F.use_empty())
2427 Worklist.push_back(&F);
2428 }
2429 }
2430 bool Changed = false;
2431 for (auto *F : llvm::reverse(Worklist)) {
2434 }
2435
2436 return Changed;
2437}
2438
2439PreservedAnalyses
2441 auto &CG = AM.getResult<LazyCallGraphAnalysis>(M);
2442
2443 if (!deduceFunctionAttributeInRPO(M, CG))
2444 return PreservedAnalyses::all();
2445
2448 return PA;
2449}
2450
2453
2454 // Check if any function in the whole program has its address taken or has
2455 // potentially external linkage.
2456 // We use this information when inferring norecurse attribute: If there is
2457 // no function whose address is taken and all functions have internal
2458 // linkage, there is no path for a callback to any user function.
2459 bool AnyFunctionsAddressIsTaken = false;
2460 for (Function &F : M) {
2461 if (F.isDeclaration() || F.doesNotRecurse())
2462 continue;
2463 if (!F.hasLocalLinkage() || F.hasAddressTaken()) {
2464 AnyFunctionsAddressIsTaken = true;
2465 break;
2466 }
2467 }
2468
2469 // Run norecurse inference on all RefSCCs in the LazyCallGraph for this
2470 // module.
2471 bool Changed = false;
2472 LazyCallGraph &CG = MAM.getResult<LazyCallGraphAnalysis>(M);
2473 CG.buildRefSCCs();
2474
2475 for (LazyCallGraph::RefSCC &RC : CG.postorder_ref_sccs()) {
2476 // Skip any RefSCC that is part of a call cycle. A RefSCC containing more
2477 // than one SCC indicates a recursive relationship involving indirect calls.
2478 if (RC.size() > 1)
2479 continue;
2480
2481 // RefSCC contains a single-SCC. SCC size > 1 indicates mutually recursive
2482 // functions. Ex: foo1 -> foo2 -> foo3 -> foo1.
2483 LazyCallGraph::SCC &S = *RC.begin();
2484 if (S.size() > 1)
2485 continue;
2486
2487 // Get the single function from this SCC.
2488 Function &F = S.begin()->getFunction();
2489 if (!F.hasExactDefinition() || F.doesNotRecurse())
2490 continue;
2491
2492 // If the analysis confirms that this function has no recursive calls
2493 // (either direct, indirect, or through external linkages),
2494 // we can safely apply the norecurse attribute.
2495 if (!mayHaveRecursiveCallee(F, AnyFunctionsAddressIsTaken)) {
2496 F.setDoesNotRecurse();
2497 ++NumNoRecurse;
2498 Changed = true;
2499 }
2500 }
2501
2503 if (Changed)
2505 else
2507 return PA;
2508}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This header provides classes for managing passes over SCCs of the call graph.
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Finalize Linkage
DXIL Resource Access
This file defines the DenseMap class.
static SmallPtrSet< Function *, 8 > deriveAttrsInPostOrder(ArrayRef< Function * > Functions, AARGetterT &&AARGetter, bool ArgAttrsOnly)
static cl::opt< bool > DisableNoFreeInference("disable-nofree-inference", cl::Hidden, cl::desc("Stop inferring nofree attribute during function-attrs pass"))
static bool inferInitializes(Argument &A, Function &F)
static bool allPathsGoThroughCold(Function &F)
static FunctionSummary * calculatePrevailingSummary(ValueInfo VI, DenseMap< ValueInfo, FunctionSummary * > &CachedPrevailingSummary, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing)
static void addMemoryAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter, SmallPtrSet< Function *, 8 > &Changed)
Deduce readonly/readnone/writeonly attributes for the SCC.
static bool addArgumentAttrsFromCallsites(Function &F)
If a callsite has arguments that are also arguments to the parent function, try to propagate attribut...
static void addCapturesStat(CaptureInfo CI)
static void addArgLocs(MemoryEffects &ME, const CallBase *Call, ModRefInfo ArgMR, AAResults &AAR)
static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes)
Tests whether a function is "malloc-like".
static void addColdAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
static bool mayHaveRecursiveCallee(Function &F, bool AnyFunctionsAddressIsTaken=true)
static void addNoReturnAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
static bool addNoFPClassAttrsTopDown(Function &F)
static cl::opt< bool > DisableNoUnwindInference("disable-nounwind-inference", cl::Hidden, cl::desc("Stop inferring nounwind attribute during function-attrs pass"))
static void addWillReturn(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
static void addNonNullAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Deduce nonnull attributes for the SCC.
static std::pair< MemoryEffects, MemoryEffects > checkFunctionMemoryAccess(Function &F, bool ThisBody, AAResults &AAR, const SCCNodeSet &SCCNodes)
Returns the memory access attribute for function F using AAR for AA results, where SCCNodes is the cu...
static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes)
Helper for NoUnwind inference predicate InstrBreaksAttribute.
static void inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Infer attributes from all functions in the SCC by scanning every instruction for compliance to the at...
static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes, bool &Speculative)
Tests whether this function is known to not return null.
static bool InstrBreaksNoSync(Instruction &I, const SCCNodeSet &SCCNodes)
static bool deduceFunctionAttributeInRPO(Module &M, LazyCallGraph &CG)
static ArgAccessProperties determinePointerAccessAttrs(Argument *A, const SmallPtrSet< Argument *, 8 > &SCCNodes)
Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
static bool InstrBreaksNoFree(Instruction &I, const SCCNodeSet &SCCNodes)
Helper for NoFree inference predicate InstrBreaksAttribute.
static cl::opt< bool > EnablePoisonArgAttrPropagation("enable-poison-arg-attr-prop", cl::init(true), cl::Hidden, cl::desc("Try to propagate nonnull and nofpclass argument attributes from " "callsites to caller functions."))
static bool addAccessAttrs(Argument *A, ArgAccessProperties Props)
static void addNoAliasAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Deduce noalias attributes for the SCC.
static bool addNoRecurseAttrsTopDown(Function &F)
static void addLocAccess(MemoryEffects &ME, const MemoryLocation &Loc, ModRefInfo MR, AAResults &AAR)
static void inferConvergent(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Attempt to remove convergent function attribute when possible.
static cl::opt< bool > DisableThinLTOPropagation("disable-thinlto-funcattrs", cl::init(true), cl::Hidden, cl::desc("Don't propagate function-attrs in thinLTO"))
static SCCNodesResult createSCCNodeSet(ArrayRef< Function * > Functions)
static bool InstrBreaksNonConvergent(Instruction &I, const SCCNodeSet &SCCNodes)
Helper for non-Convergent inference predicate InstrBreaksAttribute.
static void addArgumentAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed, bool SkipInitializes)
Deduce nocapture attributes for the SCC.
static void addNoRecurseAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
static bool functionWillReturn(const Function &F)
static void addNoUndefAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Deduce noundef attributes for the SCC.
static void addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Deduce returned attributes for the SCC.
Provides passes for computing function attributes based on interprocedural analyses.
Hexagon Common GEP
#define _
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
Implements a lazy call graph analysis and related passes for the new pass manager.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
uint64_t High
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
RISCVCC::CondCode CC
Remove Loads Into Fake Uses
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
A manager for alias analyses.
LLVM_ABI ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call)
Return the behavior of the given call site.
Class for arbitrary precision integers.
Definition APInt.h:78
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI const ConstantRange & getRange() const
Returns the value of the range attribute.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM_ABI ArrayRef< ConstantRange > getValueAsConstantRangeList() const
Return the attribute's value as a ConstantRange array.
static LLVM_ABI Attribute getWithNoFPClass(LLVMContext &Context, FPClassTest Mask)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
static LLVM_ABI Attribute getWithCaptureInfo(LLVMContext &Context, CaptureInfo CI)
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:262
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI FPClassTest getParamNoFPClass(unsigned i) const
Extract a test mask for disallowed floating-point value classes for the parameter.
LLVM_ABI FPClassTest getRetNoFPClass() const
Extract a test mask for disallowed floating-point value classes for the return value.
LLVM_ABI MemoryEffects getMemoryEffects() const
bool doesNotCapture(unsigned OpNo) const
Determine whether this data operand is not captured.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getDataOperandNo(Value::const_user_iterator UI) const
Given a value use iterator, return the data operand corresponding to it.
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
bool onlyWritesMemory(unsigned OpNo) const
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
bool onlyReadsMemory(unsigned OpNo) const
Value * getArgOperand(unsigned i) const
bool isConvergent() const
Determine if the invoke is convergent.
unsigned getArgOperandNo(const Use *U) const
Given a use for a arg operand, get the arg operand number that corresponds to it.
unsigned arg_size() const
bool isArgOperand(const Use *U) const
bool hasOperandBundles() const
Return true if this User has any operand bundles.
Represents which components of the pointer may be captured in which location.
Definition ModRef.h:414
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
static CaptureInfo retOnly(CaptureComponents RetComponents=CaptureComponents::All)
Create CaptureInfo that may only capture via the return value.
Definition ModRef.h:434
static CaptureInfo all()
Create CaptureInfo that may capture all components of the pointer.
Definition ModRef.h:430
This class represents a list of constant ranges.
LLVM_ABI void subtract(const ConstantRange &SubRange)
LLVM_ABI void insert(const ConstantRange &NewRange)
Insert a new range to Ranges and keep the list ordered.
bool empty() const
Return true if this list contains no members.
ArrayRef< ConstantRange > rangesRef() const
LLVM_ABI ConstantRangeList intersectWith(const ConstantRangeList &CRL) const
Return the range list that results from the intersection of this ConstantRangeList with another Const...
LLVM_ABI ConstantRangeList unionWith(const ConstantRangeList &CRL) const
Return the range list that results from the union of this ConstantRangeList with another ConstantRang...
This class represents a range of values.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
A proxy from a FunctionAnalysisManager to an SCC.
Function summary information to aid decisions and implementation of importing.
ArrayRef< EdgeTy > calls() const
Return the list of <CalleeValueInfo, CalleeInfo> pairs.
FFlags fflags() const
Get function summary flags.
Function and variable summary information to aid decisions and implementation of importing.
static bool isWeakAnyLinkage(LinkageTypes Linkage)
static bool isLinkOnceAnyLinkage(LinkageTypes Linkage)
static bool isLocalLinkage(LinkageTypes Linkage)
static bool isWeakODRLinkage(LinkageTypes Linkage)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
static bool isExternalLinkage(LinkageTypes Linkage)
static bool isLinkOnceODRLinkage(LinkageTypes Linkage)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isKnownNever(FPClassMask Mask) const
Return true if it's known this can never be one of the mask entries.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An analysis pass which computes the call graph for a module.
A node in the call graph.
A RefSCC of the call graph.
An SCC of the call graph.
A lazily constructed view of the call graph of a module.
LLVM_ABI void buildRefSCCs()
iterator_range< postorder_ref_scc_iterator > postorder_ref_sccs()
MemoryEffectsBase getWithoutLoc(Location Loc) const
Get new MemoryEffectsBase with NoModRef on the given Loc.
Definition ModRef.h:231
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
ModRefInfo getModRef(Location Loc) const
Get ModRefInfo for the given Location.
Definition ModRef.h:219
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
Representation for a specific memory location.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
op_range incoming_values()
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Return a value (possibly void), from a function.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents the LLVM 'select' instruction.
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static unsigned getPointerOperandIndex()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:986
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.
Definition SCCIterator.h:48
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool match(Val *V, const Pattern &P)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
bool capturesReadProvenanceOnly(CaptureComponents CC)
Definition ModRef.h:391
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI MemoryEffects computeFunctionBodyMemoryAccess(Function &F, AAResults &AAR)
Returns the memory access properties of this copy of the function.
@ Unknown
Not known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI bool thinLTOPropagateFunctionAttrs(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Propagate function attributes for function summaries along the index's callgraph during thinlink.
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1807
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V, bool MustPreserveProvenance=false)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto post_order(const T &G)
Post-order traversal of a graph.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ ErrnoMem
Errno memory.
Definition ModRef.h:66
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
bool capturesAnything(CaptureComponents CC)
Definition ModRef.h:379
@ Continue
Definition DWP.h:26
LLVM_ABI bool inferAttributesFromOthers(Function &F)
If we can infer one attribute from another on the declaration of a function, explicitly materialize t...
Definition Local.cpp:4034
LLVM_ABI UseCaptureInfo DetermineUseCaptureKind(const Use &U, const Value *Base)
Determine what kind of capture behaviour U may exhibit.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool capturesAll(CaptureComponents CC)
Definition ModRef.h:404
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
bool isNoModRef(const ModRefInfo MRI)
Definition ModRef.h:40
LLVM_ABI void FindFunctionBackedges(const Function &F, SmallVectorImpl< std::pair< const BasicBlock *, const BasicBlock * > > &Result)
Analyze the specified function to find all of the loop backedges in the function and return them.
Definition CFG.cpp:36
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
bool capturesAnyProvenance(CaptureComponents CC)
Definition ModRef.h:400
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI bool canReturn(const Function &F)
Return true if there is at least a path through which F can return, false if there is no such path.
Definition CFG.cpp:405
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static ArgAccessProperties all()
ArgAccessProperties & operator|=(const ArgAccessProperties &Other)
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
This callback is used in conjunction with PointerMayBeCaptured.
Flags specific to function summaries.
SmallVectorImpl< ArgumentGraphNode * >::iterator ChildIteratorType
static ChildIteratorType child_begin(NodeRef N)
static ChildIteratorType child_end(NodeRef N)
static ChildIteratorType nodes_end(ArgumentGraph *AG)
static NodeRef getEntryNode(ArgumentGraph *AG)
static ChildIteratorType nodes_begin(ArgumentGraph *AG)
typename ArgumentGraph *::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:94
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Capture information for a specific Use.
CaptureComponents UseCC
Components captured by this use.
Struct that holds a reference to a particular GUID in a global value summary.