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