1//===- Attributor.cpp - Module-wide attribute deduction -------------------===//
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// This file implements an interprocedural pass that deduces and/or propagates
10// attributes. This is done in an abstract interpretation style fixpoint
11// iteration. See the Attributor.h file comment and the class descriptions in
12// that file for more information.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/IPO/Attributor.h"
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/CallGraph.h"
25#include "llvm/Analysis/InlineCost.h"
26#include "llvm/Analysis/MemoryBuiltins.h"
27#include "llvm/Analysis/MustExecute.h"
28#include "llvm/IR/AttributeMask.h"
29#include "llvm/IR/Attributes.h"
30#include "llvm/IR/Constant.h"
31#include "llvm/IR/ConstantFold.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/GlobalValue.h"
35#include "llvm/IR/GlobalVariable.h"
36#include "llvm/IR/Instruction.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/ValueHandle.h"
41#include "llvm/Support/Casting.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Debug.h"
44#include "llvm/Support/DebugCounter.h"
45#include "llvm/Support/FileSystem.h"
46#include "llvm/Support/GraphWriter.h"
47#include "llvm/Support/ModRef.h"
48#include "llvm/Support/raw_ostream.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Cloning.h"
51#include "llvm/Transforms/Utils/Local.h"
52#include <cstdint>
53#include <memory>
54
55#ifdef EXPENSIVE_CHECKS
56#include "llvm/IR/Verifier.h"
57#endif
58
59#include <cassert>
60#include <optional>
61#include <string>
62
63using namespace llvm;
64
65#define DEBUG_TYPE "attributor"
66#define VERBOSE_DEBUG_TYPE DEBUG_TYPE "-verbose"
67
68DEBUG_COUNTER(ManifestDBGCounter, "attributor-manifest",
69 "Determine what attributes are manifested in the IR");
70
71STATISTIC(NumFnDeleted, "Number of function deleted");
72STATISTIC(NumFnWithExactDefinition,
73 "Number of functions with exact definitions");
74STATISTIC(NumFnWithoutExactDefinition,
75 "Number of functions without exact definitions");
76STATISTIC(NumFnShallowWrappersCreated, "Number of shallow wrappers created");
77STATISTIC(NumAttributesTimedOut,
78 "Number of abstract attributes timed out before fixpoint");
79STATISTIC(NumAttributesValidFixpoint,
80 "Number of abstract attributes in a valid fixpoint state");
81STATISTIC(NumAttributesManifested,
82 "Number of abstract attributes manifested in IR");
83
84// TODO: Determine a good default value.
85//
86// In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
87// (when run with the first 5 abstract attributes). The results also indicate
88// that we never reach 32 iterations but always find a fixpoint sooner.
89//
90// This will become more evolved once we perform two interleaved fixpoint
91// iterations: bottom-up and top-down.
92static cl::opt<unsigned>
93 SetFixpointIterations("attributor-max-iterations", cl::Hidden,
94 cl::desc("Maximal number of fixpoint iterations."),
95 cl::init(Val: 32));
96
97static cl::opt<unsigned>
98 MaxSpecializationPerCB("attributor-max-specializations-per-call-base",
99 cl::Hidden,
100 cl::desc("Maximal number of callees specialized for "
101 "a call base"),
102 cl::init(UINT32_MAX));
103
104static cl::opt<unsigned, true> MaxInitializationChainLengthX(
105 "attributor-max-initialization-chain-length", cl::Hidden,
106 cl::desc(
107 "Maximal number of chained initializations (to avoid stack overflows)"),
108 cl::location(L&: MaxInitializationChainLength), cl::init(Val: 1024));
109unsigned llvm::MaxInitializationChainLength;
110
111static cl::opt<bool> AnnotateDeclarationCallSites(
112 "attributor-annotate-decl-cs", cl::Hidden,
113 cl::desc("Annotate call sites of function declarations."), cl::init(Val: false));
114
115static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion",
116 cl::init(Val: true), cl::Hidden);
117
118static cl::opt<bool>
119 AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden,
120 cl::desc("Allow the Attributor to create shallow "
121 "wrappers for non-exact definitions."),
122 cl::init(Val: false));
123
124static cl::opt<bool>
125 AllowDeepWrapper("attributor-allow-deep-wrappers", cl::Hidden,
126 cl::desc("Allow the Attributor to use IP information "
127 "derived from non-exact functions via cloning"),
128 cl::init(Val: false));
129
130// These options can only used for debug builds.
131#ifndef NDEBUG
132static cl::list<std::string>
133 SeedAllowList("attributor-seed-allow-list", cl::Hidden,
134 cl::desc("Comma separated list of attribute names that are "
135 "allowed to be seeded."),
136 cl::CommaSeparated);
137
138static cl::list<std::string> FunctionSeedAllowList(
139 "attributor-function-seed-allow-list", cl::Hidden,
140 cl::desc("Comma separated list of function names that are "
141 "allowed to be seeded."),
142 cl::CommaSeparated);
143#endif
144
145static cl::opt<bool>
146 DumpDepGraph("attributor-dump-dep-graph", cl::Hidden,
147 cl::desc("Dump the dependency graph to dot files."),
148 cl::init(Val: false));
149
150static cl::opt<std::string> DepGraphDotFileNamePrefix(
151 "attributor-depgraph-dot-filename-prefix", cl::Hidden,
152 cl::desc("The prefix used for the CallGraph dot file names."));
153
154static cl::opt<bool> ViewDepGraph("attributor-view-dep-graph", cl::Hidden,
155 cl::desc("View the dependency graph."),
156 cl::init(Val: false));
157
158static cl::opt<bool> PrintDependencies("attributor-print-dep", cl::Hidden,
159 cl::desc("Print attribute dependencies"),
160 cl::init(Val: false));
161
162static cl::opt<bool> EnableCallSiteSpecific(
163 "attributor-enable-call-site-specific-deduction", cl::Hidden,
164 cl::desc("Allow the Attributor to do call site specific analysis"),
165 cl::init(Val: false));
166
167static cl::opt<bool>
168 PrintCallGraph("attributor-print-call-graph", cl::Hidden,
169 cl::desc("Print Attributor's internal call graph"),
170 cl::init(Val: false));
171
172static cl::opt<bool> SimplifyAllLoads("attributor-simplify-all-loads",
173 cl::Hidden,
174 cl::desc("Try to simplify all loads."),
175 cl::init(Val: true));
176
177static cl::opt<bool> CloseWorldAssumption(
178 "attributor-assume-closed-world", cl::Hidden,
179 cl::desc("Should a closed world be assumed, or not. Default if not set."));
180
181/// Logic operators for the change status enum class.
182///
183///{
184ChangeStatus llvm::operator|(ChangeStatus L, ChangeStatus R) {
185 return L == ChangeStatus::CHANGED ? L : R;
186}
187ChangeStatus &llvm::operator|=(ChangeStatus &L, ChangeStatus R) {
188 L = L | R;
189 return L;
190}
191ChangeStatus llvm::operator&(ChangeStatus L, ChangeStatus R) {
192 return L == ChangeStatus::UNCHANGED ? L : R;
193}
194ChangeStatus &llvm::operator&=(ChangeStatus &L, ChangeStatus R) {
195 L = L & R;
196 return L;
197}
198///}
199
200namespace {
201/// NVPTX/AMDGPU address space values (shared between both targets)
202enum class NVPTXAMDGPUAddressSpace : unsigned {
203 Generic = 0,
204 Global = 1,
205 Shared = 3,
206 Constant = 4,
207 Local = 5,
208};
209
210/// SPIRV address space values (StorageClass)
211enum class SPIRVAddressSpace : unsigned {
212 Local = 0, // Function (private/local)
213 Global = 1, // CrossWorkgroup (global)
214 Constant = 2, // UniformConstant (constant)
215 Shared = 3, // Workgroup (shared)
216 Generic = 4, // Generic
217};
218} // namespace
219
220bool AA::isGPU(const Module &M) {
221 Triple T(M.getTargetTriple());
222 return T.isGPU();
223}
224
225bool AA::isGPUSharedAddressSpace(const Module &M, unsigned AS) {
226 assert(AA::isGPU(M) && "Only callable on GPU targets");
227 Triple T(M.getTargetTriple());
228
229 if (T.isSPIRV())
230 return AS == static_cast<unsigned>(SPIRVAddressSpace::Shared);
231
232 return AS == static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Shared);
233}
234
235bool AA::isGPUConstantAddressSpace(const Module &M, unsigned AS) {
236 assert(AA::isGPU(M) && "Only callable on GPU targets");
237 Triple T(M.getTargetTriple());
238
239 if (T.isSPIRV())
240 return AS == static_cast<unsigned>(SPIRVAddressSpace::Constant);
241
242 return AS == static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Constant);
243}
244
245bool AA::isGPULocalAddressSpace(const Module &M, unsigned AS) {
246 assert(AA::isGPU(M) && "Only callable on GPU targets");
247 Triple T(M.getTargetTriple());
248
249 if (T.isSPIRV())
250 return AS == static_cast<unsigned>(SPIRVAddressSpace::Local);
251
252 return AS == static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Local);
253}
254
255bool AA::isNoSyncInst(Attributor &A, const Instruction &I,
256 const AbstractAttribute &QueryingAA) {
257 // We are looking for volatile instructions or non-relaxed atomics.
258 if (const auto *CB = dyn_cast<CallBase>(Val: &I)) {
259 if (CB->hasFnAttr(Kind: Attribute::NoSync))
260 return true;
261
262 // Non-convergent and readnone imply nosync.
263 if (!CB->isConvergent() && !CB->mayReadOrWriteMemory())
264 return true;
265
266 bool IsKnownNoSync;
267 return AA::hasAssumedIRAttr<Attribute::NoSync>(
268 A, QueryingAA: &QueryingAA, IRP: IRPosition::callsite_function(CB: *CB),
269 DepClass: DepClassTy::OPTIONAL, IsKnown&: IsKnownNoSync);
270 }
271
272 if (!I.mayReadOrWriteMemory())
273 return true;
274
275 return !AANoSync::isNonRelaxedAtomic(I: &I);
276}
277
278bool AA::isDynamicallyUnique(Attributor &A, const AbstractAttribute &QueryingAA,
279 const Value &V, bool ForAnalysisOnly) {
280 // TODO: See the AAInstanceInfo class comment.
281 if (!ForAnalysisOnly)
282 return false;
283 auto *InstanceInfoAA = A.getAAFor<AAInstanceInfo>(
284 QueryingAA, IRP: IRPosition::value(V), DepClass: DepClassTy::OPTIONAL);
285 return InstanceInfoAA && InstanceInfoAA->isAssumedUniqueForAnalysis();
286}
287
288Constant *
289AA::getInitialValueForObj(Attributor &A, const AbstractAttribute &QueryingAA,
290 Value &Obj, Type &Ty, const TargetLibraryInfo *TLI,
291 const DataLayout &DL, AA::RangeTy *RangePtr) {
292 if (Constant *Init = getInitialValueOfAllocation(V: &Obj, TLI, Ty: &Ty))
293 return Init;
294 auto *GV = dyn_cast<GlobalVariable>(Val: &Obj);
295 if (!GV)
296 return nullptr;
297
298 bool UsedAssumedInformation = false;
299 Constant *Initializer = nullptr;
300 if (A.hasGlobalVariableSimplificationCallback(GV: *GV)) {
301 auto AssumedGV = A.getAssumedInitializerFromCallBack(
302 GV: *GV, AA: &QueryingAA, UsedAssumedInformation);
303 Initializer = *AssumedGV;
304 if (!Initializer)
305 return nullptr;
306 } else {
307 if (!GV->hasLocalLinkage()) {
308 // Externally visible global that's either non-constant,
309 // or a constant with an uncertain initializer.
310 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
311 return nullptr;
312 }
313
314 // Globals with local linkage are always initialized.
315 assert(!GV->hasLocalLinkage() || GV->hasInitializer());
316
317 if (!Initializer)
318 Initializer = GV->getInitializer();
319 }
320
321 if (RangePtr && !RangePtr->offsetOrSizeAreUnknown()) {
322 int64_t StorageSize = DL.getTypeStoreSize(Ty: &Ty);
323 if (StorageSize != RangePtr->Size)
324 return nullptr;
325 APInt Offset = APInt(64, RangePtr->Offset);
326 return ConstantFoldLoadFromConst(C: Initializer, Ty: &Ty, Offset, DL);
327 }
328
329 return ConstantFoldLoadFromUniformValue(C: Initializer, Ty: &Ty, DL);
330}
331
332bool AA::isValidInScope(const Value &V, const Function *Scope) {
333 if (isa<Constant>(Val: V))
334 return true;
335 if (auto *I = dyn_cast<Instruction>(Val: &V))
336 return I->getFunction() == Scope;
337 if (auto *A = dyn_cast<Argument>(Val: &V))
338 return A->getParent() == Scope;
339 return false;
340}
341
342bool AA::isValidAtPosition(const AA::ValueAndContext &VAC,
343 InformationCache &InfoCache) {
344 if (isa<Constant>(Val: VAC.getValue()) || VAC.getValue() == VAC.getCtxI())
345 return true;
346 const Function *Scope = nullptr;
347 const Instruction *CtxI = VAC.getCtxI();
348 if (CtxI)
349 Scope = CtxI->getFunction();
350 if (auto *A = dyn_cast<Argument>(Val: VAC.getValue()))
351 return A->getParent() == Scope;
352 if (auto *I = dyn_cast<Instruction>(Val: VAC.getValue())) {
353 if (I->getFunction() == Scope) {
354 if (const DominatorTree *DT =
355 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(
356 F: *Scope))
357 return DT->dominates(Def: I, User: CtxI);
358 // Local dominance check mostly for the old PM passes.
359 if (CtxI && I->getParent() == CtxI->getParent())
360 return llvm::any_of(
361 Range: make_range(x: I->getIterator(), y: I->getParent()->end()),
362 P: [&](const Instruction &AfterI) { return &AfterI == CtxI; });
363 }
364 }
365 return false;
366}
367
368Value *AA::getWithType(Value &V, Type &Ty) {
369 if (V.getType() == &Ty)
370 return &V;
371 if (isa<PoisonValue>(Val: V))
372 return PoisonValue::get(T: &Ty);
373 if (isa<UndefValue>(Val: V))
374 return UndefValue::get(T: &Ty);
375 if (auto *C = dyn_cast<Constant>(Val: &V)) {
376 if (C->isNullValue() && !Ty.isPtrOrPtrVectorTy())
377 return Constant::getNullValue(Ty: &Ty);
378 if (C->getType()->isPointerTy() && Ty.isPointerTy())
379 return ConstantExpr::getPointerCast(C, Ty: &Ty);
380 if (C->getType()->getPrimitiveSizeInBits() >= Ty.getPrimitiveSizeInBits()) {
381 if (C->getType()->isIntegerTy() && Ty.isIntegerTy())
382 return ConstantExpr::getTrunc(C, Ty: &Ty, /* OnlyIfReduced */ true);
383 if (C->getType()->isFloatingPointTy() && Ty.isFloatingPointTy())
384 return ConstantFoldCastInstruction(opcode: Instruction::FPTrunc, V: C, DestTy: &Ty);
385 }
386 }
387 return nullptr;
388}
389
390std::optional<Value *>
391AA::combineOptionalValuesInAAValueLatice(const std::optional<Value *> &A,
392 const std::optional<Value *> &B,
393 Type *Ty) {
394 if (A == B)
395 return A;
396 if (!B)
397 return A;
398 if (*B == nullptr)
399 return nullptr;
400 if (!A)
401 return Ty ? getWithType(V&: **B, Ty&: *Ty) : nullptr;
402 if (*A == nullptr)
403 return nullptr;
404 if (!Ty)
405 Ty = (*A)->getType();
406 if (isa_and_nonnull<UndefValue>(Val: *A))
407 return getWithType(V&: **B, Ty&: *Ty);
408 if (isa<UndefValue>(Val: *B))
409 return A;
410 if (*A && *B && *A == getWithType(V&: **B, Ty&: *Ty))
411 return A;
412 return nullptr;
413}
414
415template <bool IsLoad, typename Ty>
416static bool getPotentialCopiesOfMemoryValue(
417 Attributor &A, Ty &I, SmallSetVector<Value *, 4> &PotentialCopies,
418 SmallSetVector<Instruction *, 4> *PotentialValueOrigins,
419 const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
420 bool OnlyExact) {
421 LLVM_DEBUG(dbgs() << "Trying to determine the potential copies of " << I
422 << " (only exact: " << OnlyExact << ")\n";);
423
424 Value &Ptr = *I.getPointerOperand();
425 // Containers to remember the pointer infos and new copies while we are not
426 // sure that we can find all of them. If we abort we want to avoid spurious
427 // dependences and potential copies in the provided container.
428 SmallVector<const AAPointerInfo *> PIs;
429 SmallSetVector<Value *, 8> NewCopies;
430 SmallSetVector<Instruction *, 8> NewCopyOrigins;
431
432 const auto *TLI =
433 A.getInfoCache().getTargetLibraryInfoForFunction(F: *I.getFunction());
434
435 auto Pred = [&](Value &Obj) {
436 LLVM_DEBUG(dbgs() << "Visit underlying object " << Obj << "\n");
437 if (isa<UndefValue>(Val: &Obj))
438 return true;
439 if (isa<ConstantPointerNull>(Val: &Obj)) {
440 // A null pointer access can be undefined but any offset from null may
441 // be OK. We do not try to optimize the latter.
442 if (!NullPointerIsDefined(I.getFunction(),
443 Ptr.getType()->getPointerAddressSpace()) &&
444 A.getAssumedSimplified(V: Ptr, AA: QueryingAA, UsedAssumedInformation,
445 S: AA::Interprocedural) == &Obj)
446 return true;
447 LLVM_DEBUG(
448 dbgs() << "Underlying object is a valid nullptr, giving up.\n";);
449 return false;
450 }
451 // TODO: Use assumed noalias return.
452 if (!isa<AllocaInst>(Val: &Obj) && !isa<GlobalVariable>(Val: &Obj) &&
453 !(IsLoad ? isAllocationFn(&Obj, TLI) : isNoAliasCall(V: &Obj))) {
454 LLVM_DEBUG(dbgs() << "Underlying object is not supported yet: " << Obj
455 << "\n";);
456 return false;
457 }
458 if (auto *GV = dyn_cast<GlobalVariable>(Val: &Obj))
459 if (!GV->hasLocalLinkage() &&
460 !(GV->isConstant() && GV->hasInitializer())) {
461 LLVM_DEBUG(dbgs() << "Underlying object is global with external "
462 "linkage, not supported yet: "
463 << Obj << "\n";);
464 return false;
465 }
466
467 bool NullOnly = true;
468 bool NullRequired = false;
469 auto CheckForNullOnlyAndUndef = [&](std::optional<Value *> V,
470 bool IsExact) {
471 if (!V || *V == nullptr)
472 NullOnly = false;
473 else if (isa<UndefValue>(Val: *V))
474 /* No op */;
475 else if (isa<Constant>(Val: *V) && cast<Constant>(Val: *V)->isNullValue())
476 NullRequired = !IsExact;
477 else
478 NullOnly = false;
479 };
480
481 auto AdjustWrittenValueType = [&](const AAPointerInfo::Access &Acc,
482 Value &V) {
483 Value *AdjV = AA::getWithType(V, Ty&: *I.getType());
484 if (!AdjV) {
485 LLVM_DEBUG(dbgs() << "Underlying object written but stored value "
486 "cannot be converted to read type: "
487 << *Acc.getRemoteInst() << " : " << *I.getType()
488 << "\n";);
489 }
490 return AdjV;
491 };
492
493 auto SkipCB = [&](const AAPointerInfo::Access &Acc) {
494 if ((IsLoad && !Acc.isWriteOrAssumption()) || (!IsLoad && !Acc.isRead()))
495 return true;
496 if (IsLoad) {
497 if (Acc.isWrittenValueYetUndetermined())
498 return true;
499 if (PotentialValueOrigins && !isa<AssumeInst>(Val: Acc.getRemoteInst()))
500 return false;
501 if (!Acc.isWrittenValueUnknown())
502 if (Value *V = AdjustWrittenValueType(Acc, *Acc.getWrittenValue()))
503 if (NewCopies.count(key: V)) {
504 NewCopyOrigins.insert(X: Acc.getRemoteInst());
505 return true;
506 }
507 if (auto *SI = dyn_cast<StoreInst>(Val: Acc.getRemoteInst()))
508 if (Value *V = AdjustWrittenValueType(Acc, *SI->getValueOperand()))
509 if (NewCopies.count(key: V)) {
510 NewCopyOrigins.insert(X: Acc.getRemoteInst());
511 return true;
512 }
513 }
514 return false;
515 };
516
517 auto CheckAccess = [&](const AAPointerInfo::Access &Acc, bool IsExact) {
518 if ((IsLoad && !Acc.isWriteOrAssumption()) || (!IsLoad && !Acc.isRead()))
519 return true;
520 if (IsLoad && Acc.isWrittenValueYetUndetermined())
521 return true;
522 CheckForNullOnlyAndUndef(Acc.getContent(), IsExact);
523 if (OnlyExact && !IsExact && !NullOnly &&
524 !isa_and_nonnull<UndefValue>(Val: Acc.getWrittenValue())) {
525 LLVM_DEBUG(dbgs() << "Non exact access " << *Acc.getRemoteInst()
526 << ", abort!\n");
527 return false;
528 }
529 if (NullRequired && !NullOnly) {
530 LLVM_DEBUG(dbgs() << "Required all `null` accesses due to non exact "
531 "one, however found non-null one: "
532 << *Acc.getRemoteInst() << ", abort!\n");
533 return false;
534 }
535 if (IsLoad) {
536 assert(isa<LoadInst>(I) && "Expected load or store instruction only!");
537 if (!Acc.isWrittenValueUnknown()) {
538 Value *V = AdjustWrittenValueType(Acc, *Acc.getWrittenValue());
539 if (!V)
540 return false;
541 NewCopies.insert(X: V);
542 if (PotentialValueOrigins)
543 NewCopyOrigins.insert(X: Acc.getRemoteInst());
544 return true;
545 }
546 auto *SI = dyn_cast<StoreInst>(Val: Acc.getRemoteInst());
547 if (!SI) {
548 LLVM_DEBUG(dbgs() << "Underlying object written through a non-store "
549 "instruction not supported yet: "
550 << *Acc.getRemoteInst() << "\n";);
551 return false;
552 }
553 Value *V = AdjustWrittenValueType(Acc, *SI->getValueOperand());
554 if (!V)
555 return false;
556 NewCopies.insert(X: V);
557 if (PotentialValueOrigins)
558 NewCopyOrigins.insert(X: SI);
559 } else {
560 assert(isa<StoreInst>(I) && "Expected load or store instruction only!");
561 auto *LI = dyn_cast<LoadInst>(Val: Acc.getRemoteInst());
562 if (!LI && OnlyExact) {
563 LLVM_DEBUG(dbgs() << "Underlying object read through a non-load "
564 "instruction not supported yet: "
565 << *Acc.getRemoteInst() << "\n";);
566 return false;
567 }
568 NewCopies.insert(X: Acc.getRemoteInst());
569 }
570 return true;
571 };
572
573 // If the value has been written to we don't need the initial value of the
574 // object.
575 bool HasBeenWrittenTo = false;
576
577 AA::RangeTy Range;
578 auto *PI = A.getAAFor<AAPointerInfo>(QueryingAA, IRP: IRPosition::value(V: Obj),
579 DepClass: DepClassTy::NONE);
580 if (!PI || !PI->forallInterferingAccesses(
581 A, QueryingAA, I,
582 /* FindInterferingWrites */ IsLoad,
583 /* FindInterferingReads */ !IsLoad, CheckAccess,
584 HasBeenWrittenTo, Range, SkipCB)) {
585 LLVM_DEBUG(
586 dbgs()
587 << "Failed to verify all interfering accesses for underlying object: "
588 << Obj << "\n");
589 return false;
590 }
591
592 if (IsLoad && !HasBeenWrittenTo && !Range.isUnassigned()) {
593 const DataLayout &DL = A.getDataLayout();
594 Value *InitialValue = AA::getInitialValueForObj(
595 A, QueryingAA, Obj, Ty&: *I.getType(), TLI, DL, RangePtr: &Range);
596 if (!InitialValue) {
597 LLVM_DEBUG(dbgs() << "Could not determine required initial value of "
598 "underlying object, abort!\n");
599 return false;
600 }
601 CheckForNullOnlyAndUndef(InitialValue, /* IsExact */ true);
602 if (NullRequired && !NullOnly) {
603 LLVM_DEBUG(dbgs() << "Non exact access but initial value that is not "
604 "null or undef, abort!\n");
605 return false;
606 }
607
608 NewCopies.insert(X: InitialValue);
609 if (PotentialValueOrigins)
610 NewCopyOrigins.insert(X: nullptr);
611 }
612
613 PIs.push_back(Elt: PI);
614
615 return true;
616 };
617
618 const auto *AAUO = A.getAAFor<AAUnderlyingObjects>(
619 QueryingAA, IRP: IRPosition::value(V: Ptr), DepClass: DepClassTy::OPTIONAL);
620 if (!AAUO || !AAUO->forallUnderlyingObjects(Pred)) {
621 LLVM_DEBUG(
622 dbgs() << "Underlying objects stored into could not be determined\n";);
623 return false;
624 }
625
626 // Only if we were successful collection all potential copies we record
627 // dependences (on non-fix AAPointerInfo AAs). We also only then modify the
628 // given PotentialCopies container.
629 for (const auto *PI : PIs) {
630 if (!PI->getState().isAtFixpoint())
631 UsedAssumedInformation = true;
632 A.recordDependence(FromAA: *PI, ToAA: QueryingAA, DepClass: DepClassTy::OPTIONAL);
633 }
634 PotentialCopies.insert_range(R&: NewCopies);
635 if (PotentialValueOrigins)
636 PotentialValueOrigins->insert_range(R&: NewCopyOrigins);
637
638 return true;
639}
640
641bool AA::getPotentiallyLoadedValues(
642 Attributor &A, LoadInst &LI, SmallSetVector<Value *, 4> &PotentialValues,
643 SmallSetVector<Instruction *, 4> &PotentialValueOrigins,
644 const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
645 bool OnlyExact) {
646 return getPotentialCopiesOfMemoryValue</* IsLoad */ true>(
647 A, I&: LI, PotentialCopies&: PotentialValues, PotentialValueOrigins: &PotentialValueOrigins, QueryingAA,
648 UsedAssumedInformation, OnlyExact);
649}
650
651bool AA::getPotentialCopiesOfStoredValue(
652 Attributor &A, StoreInst &SI, SmallSetVector<Value *, 4> &PotentialCopies,
653 const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
654 bool OnlyExact) {
655 return getPotentialCopiesOfMemoryValue</* IsLoad */ false>(
656 A, I&: SI, PotentialCopies, PotentialValueOrigins: nullptr, QueryingAA, UsedAssumedInformation,
657 OnlyExact);
658}
659
660static bool isAssumedReadOnlyOrReadNone(Attributor &A, const IRPosition &IRP,
661 const AbstractAttribute &QueryingAA,
662 bool RequireReadNone, bool &IsKnown) {
663 if (RequireReadNone) {
664 if (AA::hasAssumedIRAttr<Attribute::ReadNone>(
665 A, QueryingAA: &QueryingAA, IRP, DepClass: DepClassTy::OPTIONAL, IsKnown,
666 /* IgnoreSubsumingPositions */ true))
667 return true;
668 } else if (AA::hasAssumedIRAttr<Attribute::ReadOnly>(
669 A, QueryingAA: &QueryingAA, IRP, DepClass: DepClassTy::OPTIONAL, IsKnown,
670 /* IgnoreSubsumingPositions */ true))
671 return true;
672
673 IRPosition::Kind Kind = IRP.getPositionKind();
674 if (Kind == IRPosition::IRP_FUNCTION || Kind == IRPosition::IRP_CALL_SITE) {
675 const auto *MemLocAA =
676 A.getAAFor<AAMemoryLocation>(QueryingAA, IRP, DepClass: DepClassTy::NONE);
677 if (MemLocAA && MemLocAA->isAssumedReadNone()) {
678 IsKnown = MemLocAA->isKnownReadNone();
679 if (!IsKnown)
680 A.recordDependence(FromAA: *MemLocAA, ToAA: QueryingAA, DepClass: DepClassTy::OPTIONAL);
681 return true;
682 }
683 }
684
685 const auto *MemBehaviorAA =
686 A.getAAFor<AAMemoryBehavior>(QueryingAA, IRP, DepClass: DepClassTy::NONE);
687 if (MemBehaviorAA &&
688 (MemBehaviorAA->isAssumedReadNone() ||
689 (!RequireReadNone && MemBehaviorAA->isAssumedReadOnly()))) {
690 IsKnown = RequireReadNone ? MemBehaviorAA->isKnownReadNone()
691 : MemBehaviorAA->isKnownReadOnly();
692 if (!IsKnown)
693 A.recordDependence(FromAA: *MemBehaviorAA, ToAA: QueryingAA, DepClass: DepClassTy::OPTIONAL);
694 return true;
695 }
696
697 return false;
698}
699
700bool AA::isAssumedReadOnly(Attributor &A, const IRPosition &IRP,
701 const AbstractAttribute &QueryingAA, bool &IsKnown) {
702 return isAssumedReadOnlyOrReadNone(A, IRP, QueryingAA,
703 /* RequireReadNone */ false, IsKnown);
704}
705bool AA::isAssumedReadNone(Attributor &A, const IRPosition &IRP,
706 const AbstractAttribute &QueryingAA, bool &IsKnown) {
707 return isAssumedReadOnlyOrReadNone(A, IRP, QueryingAA,
708 /* RequireReadNone */ true, IsKnown);
709}
710
711static bool
712isPotentiallyReachable(Attributor &A, const Instruction &FromI,
713 const Instruction *ToI, const Function &ToFn,
714 const AbstractAttribute &QueryingAA,
715 const AA::InstExclusionSetTy *ExclusionSet,
716 std::function<bool(const Function &F)> GoBackwardsCB) {
717 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
718 dbgs() << "[AA] isPotentiallyReachable @" << ToFn.getName() << " from "
719 << FromI << " [GBCB: " << bool(GoBackwardsCB) << "][#ExS: "
720 << (ExclusionSet ? std::to_string(ExclusionSet->size()) : "none")
721 << "]\n";
722 if (ExclusionSet)
723 for (auto *ES : *ExclusionSet)
724 dbgs() << *ES << "\n";
725 });
726
727 // We know kernels (generally) cannot be called from within the module. Thus,
728 // for reachability we would need to step back from a kernel which would allow
729 // us to reach anything anyway. Even if a kernel is invoked from another
730 // kernel, values like allocas and shared memory are not accessible. We
731 // implicitly check for this situation to avoid costly lookups.
732 if (GoBackwardsCB && &ToFn != FromI.getFunction() &&
733 !GoBackwardsCB(*FromI.getFunction()) && A.getInfoCache().isKernel(F: ToFn) &&
734 A.getInfoCache().isKernel(F: *FromI.getFunction())) {
735 LLVM_DEBUG(dbgs() << "[AA] assume kernel cannot be reached from within the "
736 "module; success\n";);
737 return false;
738 }
739
740 // If we can go arbitrarily backwards we will eventually reach an entry point
741 // that can reach ToI. Only if a set of blocks through which we cannot go is
742 // provided, or once we track internal functions not accessible from the
743 // outside, it makes sense to perform backwards analysis in the absence of a
744 // GoBackwardsCB.
745 if (!GoBackwardsCB && !ExclusionSet) {
746 LLVM_DEBUG(dbgs() << "[AA] check @" << ToFn.getName() << " from " << FromI
747 << " is not checked backwards and does not have an "
748 "exclusion set, abort\n");
749 return true;
750 }
751
752 SmallPtrSet<const Instruction *, 8> Visited;
753 SmallVector<const Instruction *> Worklist;
754 Worklist.push_back(Elt: &FromI);
755
756 while (!Worklist.empty()) {
757 const Instruction *CurFromI = Worklist.pop_back_val();
758 if (!Visited.insert(Ptr: CurFromI).second)
759 continue;
760
761 const Function *FromFn = CurFromI->getFunction();
762 if (FromFn == &ToFn) {
763 if (!ToI)
764 return true;
765 LLVM_DEBUG(dbgs() << "[AA] check " << *ToI << " from " << *CurFromI
766 << " intraprocedurally\n");
767 const auto *ReachabilityAA = A.getAAFor<AAIntraFnReachability>(
768 QueryingAA, IRP: IRPosition::function(F: ToFn), DepClass: DepClassTy::OPTIONAL);
769 bool Result = !ReachabilityAA || ReachabilityAA->isAssumedReachable(
770 A, From: *CurFromI, To: *ToI, ExclusionSet);
771 LLVM_DEBUG(dbgs() << "[AA] " << *CurFromI << " "
772 << (Result ? "can potentially " : "cannot ") << "reach "
773 << *ToI << " [Intra]\n");
774 if (Result)
775 return true;
776 }
777
778 bool Result = true;
779 if (!ToFn.isDeclaration() && ToI) {
780 const auto *ToReachabilityAA = A.getAAFor<AAIntraFnReachability>(
781 QueryingAA, IRP: IRPosition::function(F: ToFn), DepClass: DepClassTy::OPTIONAL);
782 const Instruction &EntryI = ToFn.getEntryBlock().front();
783 Result = !ToReachabilityAA || ToReachabilityAA->isAssumedReachable(
784 A, From: EntryI, To: *ToI, ExclusionSet);
785 LLVM_DEBUG(dbgs() << "[AA] Entry " << EntryI << " of @" << ToFn.getName()
786 << " " << (Result ? "can potentially " : "cannot ")
787 << "reach @" << *ToI << " [ToFn]\n");
788 }
789
790 if (Result) {
791 // The entry of the ToFn can reach the instruction ToI. If the current
792 // instruction is already known to reach the ToFn.
793 const auto *FnReachabilityAA = A.getAAFor<AAInterFnReachability>(
794 QueryingAA, IRP: IRPosition::function(F: *FromFn), DepClass: DepClassTy::OPTIONAL);
795 Result = !FnReachabilityAA || FnReachabilityAA->instructionCanReach(
796 A, Inst: *CurFromI, Fn: ToFn, ExclusionSet);
797 LLVM_DEBUG(dbgs() << "[AA] " << *CurFromI << " in @" << FromFn->getName()
798 << " " << (Result ? "can potentially " : "cannot ")
799 << "reach @" << ToFn.getName() << " [FromFn]\n");
800 if (Result)
801 return true;
802 }
803
804 // TODO: Check assumed nounwind.
805 const auto *ReachabilityAA = A.getAAFor<AAIntraFnReachability>(
806 QueryingAA, IRP: IRPosition::function(F: *FromFn), DepClass: DepClassTy::OPTIONAL);
807 auto ReturnInstCB = [&](Instruction &Ret) {
808 bool Result = !ReachabilityAA || ReachabilityAA->isAssumedReachable(
809 A, From: *CurFromI, To: Ret, ExclusionSet);
810 LLVM_DEBUG(dbgs() << "[AA][Ret] " << *CurFromI << " "
811 << (Result ? "can potentially " : "cannot ") << "reach "
812 << Ret << " [Intra]\n");
813 return !Result;
814 };
815
816 // Check if we can reach returns.
817 bool UsedAssumedInformation = false;
818 if (A.checkForAllInstructions(Pred: ReturnInstCB, Fn: FromFn, QueryingAA: &QueryingAA,
819 Opcodes: {Instruction::Ret}, UsedAssumedInformation)) {
820 LLVM_DEBUG(dbgs() << "[AA] No return is reachable, done\n");
821 continue;
822 }
823
824 if (!GoBackwardsCB) {
825 LLVM_DEBUG(dbgs() << "[AA] check @" << ToFn.getName() << " from " << FromI
826 << " is not checked backwards, abort\n");
827 return true;
828 }
829
830 // If we do not go backwards from the FromFn we are done here and so far we
831 // could not find a way to reach ToFn/ToI.
832 if (!GoBackwardsCB(*FromFn))
833 continue;
834
835 LLVM_DEBUG(dbgs() << "Stepping backwards to the call sites of @"
836 << FromFn->getName() << "\n");
837
838 auto CheckCallSite = [&](AbstractCallSite ACS) {
839 CallBase *CB = ACS.getInstruction();
840 if (!CB)
841 return false;
842
843 if (isa<InvokeInst>(Val: CB))
844 return false;
845
846 Instruction *Inst = CB->getNextNode();
847 Worklist.push_back(Elt: Inst);
848 return true;
849 };
850
851 Result = !A.checkForAllCallSites(Pred: CheckCallSite, Fn: *FromFn,
852 /* RequireAllCallSites */ true,
853 QueryingAA: &QueryingAA, UsedAssumedInformation);
854 if (Result) {
855 LLVM_DEBUG(dbgs() << "[AA] stepping back to call sites from " << *CurFromI
856 << " in @" << FromFn->getName()
857 << " failed, give up\n");
858 return true;
859 }
860
861 LLVM_DEBUG(dbgs() << "[AA] stepped back to call sites from " << *CurFromI
862 << " in @" << FromFn->getName()
863 << " worklist size is: " << Worklist.size() << "\n");
864 }
865 return false;
866}
867
868bool AA::isPotentiallyReachable(
869 Attributor &A, const Instruction &FromI, const Instruction &ToI,
870 const AbstractAttribute &QueryingAA,
871 const AA::InstExclusionSetTy *ExclusionSet,
872 std::function<bool(const Function &F)> GoBackwardsCB) {
873 const Function *ToFn = ToI.getFunction();
874 return ::isPotentiallyReachable(A, FromI, ToI: &ToI, ToFn: *ToFn, QueryingAA,
875 ExclusionSet, GoBackwardsCB);
876}
877
878bool AA::isPotentiallyReachable(
879 Attributor &A, const Instruction &FromI, const Function &ToFn,
880 const AbstractAttribute &QueryingAA,
881 const AA::InstExclusionSetTy *ExclusionSet,
882 std::function<bool(const Function &F)> GoBackwardsCB) {
883 return ::isPotentiallyReachable(A, FromI, /* ToI */ nullptr, ToFn, QueryingAA,
884 ExclusionSet, GoBackwardsCB);
885}
886
887bool AA::isAssumedThreadLocalObject(Attributor &A, Value &Obj,
888 const AbstractAttribute &QueryingAA) {
889 if (isa<UndefValue>(Val: Obj))
890 return true;
891 if (isa<AllocaInst>(Val: Obj)) {
892 InformationCache &InfoCache = A.getInfoCache();
893 if (!InfoCache.stackIsAccessibleByOtherThreads()) {
894 LLVM_DEBUG(
895 dbgs() << "[AA] Object '" << Obj
896 << "' is thread local; stack objects are thread local.\n");
897 return true;
898 }
899 bool IsKnownNoCapture;
900 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
901 A, QueryingAA: &QueryingAA, IRP: IRPosition::value(V: Obj), DepClass: DepClassTy::OPTIONAL,
902 IsKnown&: IsKnownNoCapture);
903 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj << "' is "
904 << (IsAssumedNoCapture ? "" : "not") << " thread local; "
905 << (IsAssumedNoCapture ? "non-" : "")
906 << "captured stack object.\n");
907 return IsAssumedNoCapture;
908 }
909 if (auto *GV = dyn_cast<GlobalVariable>(Val: &Obj)) {
910 if (GV->isConstant()) {
911 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
912 << "' is thread local; constant global\n");
913 return true;
914 }
915 if (GV->isThreadLocal()) {
916 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
917 << "' is thread local; thread local global\n");
918 return true;
919 }
920 }
921
922 if (A.getInfoCache().IsTargetGPU()) {
923 if (AA::isGPULocalAddressSpace(M: A.getInfoCache().getModule(),
924 AS: Obj.getType()->getPointerAddressSpace())) {
925 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
926 << "' is thread local; GPU local memory\n");
927 return true;
928 }
929 if (AA::isGPUConstantAddressSpace(
930 M: A.getInfoCache().getModule(),
931 AS: Obj.getType()->getPointerAddressSpace())) {
932 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
933 << "' is thread local; GPU constant memory\n");
934 return true;
935 }
936 }
937
938 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj << "' is not thread local\n");
939 return false;
940}
941
942bool AA::isPotentiallyAffectedByBarrier(Attributor &A, const Instruction &I,
943 const AbstractAttribute &QueryingAA) {
944 if (!I.mayHaveSideEffects() && !I.mayReadFromMemory())
945 return false;
946
947 SmallSetVector<const Value *, 8> Ptrs;
948
949 auto AddLocationPtr = [&](std::optional<MemoryLocation> Loc) {
950 if (!Loc || !Loc->Ptr) {
951 LLVM_DEBUG(
952 dbgs() << "[AA] Access to unknown location; -> requires barriers\n");
953 return false;
954 }
955 Ptrs.insert(X: Loc->Ptr);
956 return true;
957 };
958
959 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Val: &I)) {
960 if (!AddLocationPtr(MemoryLocation::getForDest(MI)))
961 return true;
962 if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(Val: &I))
963 if (!AddLocationPtr(MemoryLocation::getForSource(MTI)))
964 return true;
965 } else if (!AddLocationPtr(MemoryLocation::getOrNone(Inst: &I)))
966 return true;
967
968 return isPotentiallyAffectedByBarrier(A, Ptrs: Ptrs.getArrayRef(), QueryingAA, CtxI: &I);
969}
970
971bool AA::isPotentiallyAffectedByBarrier(Attributor &A,
972 ArrayRef<const Value *> Ptrs,
973 const AbstractAttribute &QueryingAA,
974 const Instruction *CtxI) {
975 for (const Value *Ptr : Ptrs) {
976 if (!Ptr) {
977 LLVM_DEBUG(dbgs() << "[AA] nullptr; -> requires barriers\n");
978 return true;
979 }
980
981 auto Pred = [&](Value &Obj) {
982 if (AA::isAssumedThreadLocalObject(A, Obj, QueryingAA))
983 return true;
984 LLVM_DEBUG(dbgs() << "[AA] Access to '" << Obj << "' via '" << *Ptr
985 << "'; -> requires barrier\n");
986 return false;
987 };
988
989 const auto *UnderlyingObjsAA = A.getAAFor<AAUnderlyingObjects>(
990 QueryingAA, IRP: IRPosition::value(V: *Ptr), DepClass: DepClassTy::OPTIONAL);
991 if (!UnderlyingObjsAA || !UnderlyingObjsAA->forallUnderlyingObjects(Pred))
992 return true;
993 }
994 return false;
995}
996
997/// Return true if \p New is equal or worse than \p Old.
998static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
999 if (!Old.isIntAttribute())
1000 return true;
1001
1002 return Old.getValueAsInt() >= New.getValueAsInt();
1003}
1004
1005/// Return true if the information provided by \p Attr was added to the
1006/// attribute set \p AttrSet. This is only the case if it was not already
1007/// present in \p AttrSet.
1008static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
1009 AttributeSet AttrSet, bool ForceReplace,
1010 AttrBuilder &AB) {
1011
1012 if (Attr.isEnumAttribute()) {
1013 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1014 if (AttrSet.hasAttribute(Kind))
1015 return false;
1016 AB.addAttribute(Val: Kind);
1017 return true;
1018 }
1019 if (Attr.isStringAttribute()) {
1020 StringRef Kind = Attr.getKindAsString();
1021 if (AttrSet.hasAttribute(Kind)) {
1022 if (!ForceReplace)
1023 return false;
1024 }
1025 AB.addAttribute(A: Kind, V: Attr.getValueAsString());
1026 return true;
1027 }
1028 if (Attr.isIntAttribute()) {
1029 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1030 if (!ForceReplace && Kind == Attribute::Memory) {
1031 MemoryEffects ME = Attr.getMemoryEffects() & AttrSet.getMemoryEffects();
1032 if (ME == AttrSet.getMemoryEffects())
1033 return false;
1034 AB.addMemoryAttr(ME);
1035 return true;
1036 }
1037 if (AttrSet.hasAttribute(Kind)) {
1038 if (!ForceReplace && isEqualOrWorse(New: Attr, Old: AttrSet.getAttribute(Kind)))
1039 return false;
1040 }
1041 AB.addAttribute(A: Attr);
1042 return true;
1043 }
1044 if (Attr.isConstantRangeAttribute()) {
1045 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1046 if (!ForceReplace && AttrSet.hasAttribute(Kind))
1047 return false;
1048 AB.addAttribute(A: Attr);
1049 return true;
1050 }
1051
1052 llvm_unreachable("Expected enum or string attribute!");
1053}
1054
1055Argument *IRPosition::getAssociatedArgument() const {
1056 if (getPositionKind() == IRP_ARGUMENT)
1057 return cast<Argument>(Val: &getAnchorValue());
1058
1059 // Not an Argument and no argument number means this is not a call site
1060 // argument, thus we cannot find a callback argument to return.
1061 int ArgNo = getCallSiteArgNo();
1062 if (ArgNo < 0)
1063 return nullptr;
1064
1065 // Use abstract call sites to make the connection between the call site
1066 // values and the ones in callbacks. If a callback was found that makes use
1067 // of the underlying call site operand, we want the corresponding callback
1068 // callee argument and not the direct callee argument.
1069 std::optional<Argument *> CBCandidateArg;
1070 SmallVector<const Use *, 4> CallbackUses;
1071 const auto &CB = cast<CallBase>(Val&: getAnchorValue());
1072 AbstractCallSite::getCallbackUses(CB, CallbackUses);
1073 for (const Use *U : CallbackUses) {
1074 AbstractCallSite ACS(U);
1075 assert(ACS && ACS.isCallbackCall());
1076 if (!ACS.getCalledFunction())
1077 continue;
1078
1079 for (unsigned u = 0, e = ACS.getNumArgOperands(); u < e; u++) {
1080
1081 // Test if the underlying call site operand is argument number u of the
1082 // callback callee.
1083 if (ACS.getCallArgOperandNo(ArgNo: u) != ArgNo)
1084 continue;
1085
1086 assert(ACS.getCalledFunction()->arg_size() > u &&
1087 "ACS mapped into var-args arguments!");
1088 if (CBCandidateArg) {
1089 CBCandidateArg = nullptr;
1090 break;
1091 }
1092 CBCandidateArg = ACS.getCalledFunction()->getArg(i: u);
1093 }
1094 }
1095
1096 // If we found a unique callback candidate argument, return it.
1097 if (CBCandidateArg && *CBCandidateArg)
1098 return *CBCandidateArg;
1099
1100 // If no callbacks were found, or none used the underlying call site operand
1101 // exclusively, use the direct callee argument if available.
1102 auto *Callee = dyn_cast_if_present<Function>(Val: CB.getCalledOperand());
1103 if (Callee && Callee->arg_size() > unsigned(ArgNo))
1104 return Callee->getArg(i: ArgNo);
1105
1106 return nullptr;
1107}
1108
1109ChangeStatus AbstractAttribute::update(Attributor &A) {
1110 ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
1111 if (getState().isAtFixpoint())
1112 return HasChanged;
1113
1114 LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
1115
1116 HasChanged = updateImpl(A);
1117
1118 LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
1119 << "\n");
1120
1121 return HasChanged;
1122}
1123
1124Attributor::Attributor(SetVector<Function *> &Functions,
1125 InformationCache &InfoCache,
1126 AttributorConfig Configuration)
1127 : Allocator(InfoCache.Allocator), Functions(Functions),
1128 InfoCache(InfoCache), Configuration(Configuration) {
1129 if (!isClosedWorldModule())
1130 return;
1131 for (Function *Fn : Functions)
1132 if (Fn->hasAddressTaken(/*PutOffender=*/nullptr,
1133 /*IgnoreCallbackUses=*/false,
1134 /*IgnoreAssumeLikeCalls=*/true,
1135 /*IgnoreLLVMUsed=*/IngoreLLVMUsed: true,
1136 /*IgnoreARCAttachedCall=*/false,
1137 /*IgnoreCastedDirectCall=*/true))
1138 InfoCache.IndirectlyCallableFunctions.push_back(Elt: Fn);
1139}
1140
1141bool Attributor::getAttrsFromAssumes(const IRPosition &IRP,
1142 Attribute::AttrKind AK,
1143 SmallVectorImpl<Attribute> &Attrs) {
1144 assert(IRP.getPositionKind() != IRPosition::IRP_INVALID &&
1145 "Did expect a valid position!");
1146 MustBeExecutedContextExplorer *Explorer =
1147 getInfoCache().getMustBeExecutedContextExplorer();
1148 if (!Explorer)
1149 return false;
1150
1151 Value &AssociatedValue = IRP.getAssociatedValue();
1152
1153 const Assume2KnowledgeMap &A2K =
1154 getInfoCache().getKnowledgeMap().lookup(Val: {&AssociatedValue, AK});
1155
1156 // Check if we found any potential assume use, if not we don't need to create
1157 // explorer iterators.
1158 if (A2K.empty())
1159 return false;
1160
1161 LLVMContext &Ctx = AssociatedValue.getContext();
1162 unsigned AttrsSize = Attrs.size();
1163 auto EIt = Explorer->begin(PP: IRP.getCtxI()),
1164 EEnd = Explorer->end(IRP.getCtxI());
1165 for (const auto &It : A2K)
1166 if (Explorer->findInContextOf(I: It.first, EIt, EEnd))
1167 Attrs.push_back(Elt: Attribute::get(Context&: Ctx, Kind: AK, Val: It.second.Max));
1168 return AttrsSize != Attrs.size();
1169}
1170
1171template <typename DescTy>
1172ChangeStatus
1173Attributor::updateAttrMap(const IRPosition &IRP, ArrayRef<DescTy> AttrDescs,
1174 function_ref<bool(const DescTy &, AttributeSet,
1175 AttributeMask &, AttrBuilder &)>
1176 CB) {
1177 if (AttrDescs.empty())
1178 return ChangeStatus::UNCHANGED;
1179 switch (IRP.getPositionKind()) {
1180 case IRPosition::IRP_FLOAT:
1181 case IRPosition::IRP_INVALID:
1182 return ChangeStatus::UNCHANGED;
1183 default:
1184 break;
1185 };
1186
1187 AttributeList AL = IRP.getAttrList();
1188 Value *AttrListAnchor = IRP.getAttrListAnchor();
1189 auto [Iter, Inserted] = AttrsMap.insert(KV: {AttrListAnchor, AL});
1190 if (!Inserted)
1191 AL = Iter->second;
1192
1193 LLVMContext &Ctx = IRP.getAnchorValue().getContext();
1194 auto AttrIdx = IRP.getAttrIdx();
1195 AttributeSet AS = AL.getAttributes(Index: AttrIdx);
1196 AttributeMask AM;
1197 AttrBuilder AB(Ctx);
1198
1199 ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
1200 for (const DescTy &AttrDesc : AttrDescs)
1201 if (CB(AttrDesc, AS, AM, AB))
1202 HasChanged = ChangeStatus::CHANGED;
1203
1204 if (HasChanged == ChangeStatus::UNCHANGED)
1205 return ChangeStatus::UNCHANGED;
1206
1207 AL = AL.removeAttributesAtIndex(C&: Ctx, Index: AttrIdx, AttrsToRemove: AM);
1208 AL = AL.addAttributesAtIndex(C&: Ctx, Index: AttrIdx, B: AB);
1209
1210 Iter->second = AL;
1211 return HasChanged;
1212}
1213
1214bool Attributor::hasAttr(const IRPosition &IRP,
1215 ArrayRef<Attribute::AttrKind> AttrKinds,
1216 bool IgnoreSubsumingPositions,
1217 Attribute::AttrKind ImpliedAttributeKind) {
1218 bool Implied = false;
1219 bool HasAttr = false;
1220 auto HasAttrCB = [&](const Attribute::AttrKind &Kind, AttributeSet AttrSet,
1221 AttributeMask &, AttrBuilder &) {
1222 if (AttrSet.hasAttribute(Kind)) {
1223 Implied |= Kind != ImpliedAttributeKind;
1224 HasAttr = true;
1225 }
1226 return false;
1227 };
1228 for (const IRPosition &EquivIRP : SubsumingPositionIterator(IRP)) {
1229 updateAttrMap<Attribute::AttrKind>(IRP: EquivIRP, AttrDescs: AttrKinds, CB: HasAttrCB);
1230 if (HasAttr)
1231 break;
1232 // The first position returned by the SubsumingPositionIterator is
1233 // always the position itself. If we ignore subsuming positions we
1234 // are done after the first iteration.
1235 if (IgnoreSubsumingPositions)
1236 break;
1237 Implied = true;
1238 }
1239 if (!HasAttr) {
1240 Implied = true;
1241 SmallVector<Attribute> Attrs;
1242 for (Attribute::AttrKind AK : AttrKinds)
1243 if (getAttrsFromAssumes(IRP, AK, Attrs)) {
1244 HasAttr = true;
1245 break;
1246 }
1247 }
1248
1249 // Check if we should manifest the implied attribute kind at the IRP.
1250 if (ImpliedAttributeKind != Attribute::None && HasAttr && Implied)
1251 manifestAttrs(IRP, DeducedAttrs: {Attribute::get(Context&: IRP.getAnchorValue().getContext(),
1252 Kind: ImpliedAttributeKind)});
1253 return HasAttr;
1254}
1255
1256void Attributor::getAttrs(const IRPosition &IRP,
1257 ArrayRef<Attribute::AttrKind> AttrKinds,
1258 SmallVectorImpl<Attribute> &Attrs,
1259 bool IgnoreSubsumingPositions) {
1260 auto CollectAttrCB = [&](const Attribute::AttrKind &Kind,
1261 AttributeSet AttrSet, AttributeMask &,
1262 AttrBuilder &) {
1263 if (AttrSet.hasAttribute(Kind))
1264 Attrs.push_back(Elt: AttrSet.getAttribute(Kind));
1265 return false;
1266 };
1267 for (const IRPosition &EquivIRP : SubsumingPositionIterator(IRP)) {
1268 updateAttrMap<Attribute::AttrKind>(IRP: EquivIRP, AttrDescs: AttrKinds, CB: CollectAttrCB);
1269 // The first position returned by the SubsumingPositionIterator is
1270 // always the position itself. If we ignore subsuming positions we
1271 // are done after the first iteration.
1272 if (IgnoreSubsumingPositions)
1273 break;
1274 }
1275 for (Attribute::AttrKind AK : AttrKinds)
1276 getAttrsFromAssumes(IRP, AK, Attrs);
1277}
1278
1279ChangeStatus Attributor::removeAttrs(const IRPosition &IRP,
1280 ArrayRef<Attribute::AttrKind> AttrKinds) {
1281 auto RemoveAttrCB = [&](const Attribute::AttrKind &Kind, AttributeSet AttrSet,
1282 AttributeMask &AM, AttrBuilder &) {
1283 if (!AttrSet.hasAttribute(Kind))
1284 return false;
1285 AM.addAttribute(Val: Kind);
1286 return true;
1287 };
1288 return updateAttrMap<Attribute::AttrKind>(IRP, AttrDescs: AttrKinds, CB: RemoveAttrCB);
1289}
1290
1291ChangeStatus Attributor::removeAttrs(const IRPosition &IRP,
1292 ArrayRef<StringRef> Attrs) {
1293 auto RemoveAttrCB = [&](StringRef Attr, AttributeSet AttrSet,
1294 AttributeMask &AM, AttrBuilder &) -> bool {
1295 if (!AttrSet.hasAttribute(Kind: Attr))
1296 return false;
1297 AM.addAttribute(A: Attr);
1298 return true;
1299 };
1300
1301 return updateAttrMap<StringRef>(IRP, AttrDescs: Attrs, CB: RemoveAttrCB);
1302}
1303
1304ChangeStatus Attributor::manifestAttrs(const IRPosition &IRP,
1305 ArrayRef<Attribute> Attrs,
1306 bool ForceReplace) {
1307 LLVMContext &Ctx = IRP.getAnchorValue().getContext();
1308 auto AddAttrCB = [&](const Attribute &Attr, AttributeSet AttrSet,
1309 AttributeMask &, AttrBuilder &AB) {
1310 return addIfNotExistent(Ctx, Attr, AttrSet, ForceReplace, AB);
1311 };
1312 return updateAttrMap<Attribute>(IRP, AttrDescs: Attrs, CB: AddAttrCB);
1313}
1314
1315SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) {
1316 IRPositions.emplace_back(Args: IRP);
1317
1318 // Helper to determine if operand bundles on a call site are benign or
1319 // potentially problematic. We handle only llvm.assume for now.
1320 auto CanIgnoreOperandBundles = [](const CallBase &CB) {
1321 return (isa<IntrinsicInst>(Val: CB) &&
1322 cast<IntrinsicInst>(Val: CB).getIntrinsicID() == Intrinsic ::assume);
1323 };
1324
1325 const auto *CB = dyn_cast<CallBase>(Val: &IRP.getAnchorValue());
1326 switch (IRP.getPositionKind()) {
1327 case IRPosition::IRP_INVALID:
1328 case IRPosition::IRP_FLOAT:
1329 case IRPosition::IRP_FUNCTION:
1330 return;
1331 case IRPosition::IRP_ARGUMENT:
1332 case IRPosition::IRP_RETURNED:
1333 IRPositions.emplace_back(Args: IRPosition::function(F: *IRP.getAnchorScope()));
1334 return;
1335 case IRPosition::IRP_CALL_SITE:
1336 assert(CB && "Expected call site!");
1337 // TODO: We need to look at the operand bundles similar to the redirection
1338 // in CallBase.
1339 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB))
1340 if (auto *Callee = dyn_cast_if_present<Function>(Val: CB->getCalledOperand()))
1341 IRPositions.emplace_back(Args: IRPosition::function(F: *Callee));
1342 return;
1343 case IRPosition::IRP_CALL_SITE_RETURNED:
1344 assert(CB && "Expected call site!");
1345 // TODO: We need to look at the operand bundles similar to the redirection
1346 // in CallBase.
1347 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
1348 if (auto *Callee =
1349 dyn_cast_if_present<Function>(Val: CB->getCalledOperand())) {
1350 IRPositions.emplace_back(Args: IRPosition::returned(F: *Callee));
1351 IRPositions.emplace_back(Args: IRPosition::function(F: *Callee));
1352 for (const Argument &Arg : Callee->args())
1353 if (Arg.hasReturnedAttr()) {
1354 IRPositions.emplace_back(
1355 Args: IRPosition::callsite_argument(CB: *CB, ArgNo: Arg.getArgNo()));
1356 IRPositions.emplace_back(
1357 Args: IRPosition::value(V: *CB->getArgOperand(i: Arg.getArgNo())));
1358 IRPositions.emplace_back(Args: IRPosition::argument(Arg));
1359 }
1360 }
1361 }
1362 IRPositions.emplace_back(Args: IRPosition::callsite_function(CB: *CB));
1363 return;
1364 case IRPosition::IRP_CALL_SITE_ARGUMENT: {
1365 assert(CB && "Expected call site!");
1366 // TODO: We need to look at the operand bundles similar to the redirection
1367 // in CallBase.
1368 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
1369 auto *Callee = dyn_cast_if_present<Function>(Val: CB->getCalledOperand());
1370 if (Callee) {
1371 if (Argument *Arg = IRP.getAssociatedArgument())
1372 IRPositions.emplace_back(Args: IRPosition::argument(Arg: *Arg));
1373 IRPositions.emplace_back(Args: IRPosition::function(F: *Callee));
1374 }
1375 }
1376 IRPositions.emplace_back(Args: IRPosition::value(V: IRP.getAssociatedValue()));
1377 return;
1378 }
1379 }
1380}
1381
1382void IRPosition::verify() {
1383#ifdef EXPENSIVE_CHECKS
1384 switch (getPositionKind()) {
1385 case IRP_INVALID:
1386 assert((CBContext == nullptr) &&
1387 "Invalid position must not have CallBaseContext!");
1388 assert(!Enc.getOpaqueValue() &&
1389 "Expected a nullptr for an invalid position!");
1390 return;
1391 case IRP_FLOAT:
1392 assert((!isa<Argument>(&getAssociatedValue())) &&
1393 "Expected specialized kind for argument values!");
1394 return;
1395 case IRP_RETURNED:
1396 assert(isa<Function>(getAsValuePtr()) &&
1397 "Expected function for a 'returned' position!");
1398 assert(getAsValuePtr() == &getAssociatedValue() &&
1399 "Associated value mismatch!");
1400 return;
1401 case IRP_CALL_SITE_RETURNED:
1402 assert((CBContext == nullptr) &&
1403 "'call site returned' position must not have CallBaseContext!");
1404 assert((isa<CallBase>(getAsValuePtr())) &&
1405 "Expected call base for 'call site returned' position!");
1406 assert(getAsValuePtr() == &getAssociatedValue() &&
1407 "Associated value mismatch!");
1408 return;
1409 case IRP_CALL_SITE:
1410 assert((CBContext == nullptr) &&
1411 "'call site function' position must not have CallBaseContext!");
1412 assert((isa<CallBase>(getAsValuePtr())) &&
1413 "Expected call base for 'call site function' position!");
1414 assert(getAsValuePtr() == &getAssociatedValue() &&
1415 "Associated value mismatch!");
1416 return;
1417 case IRP_FUNCTION:
1418 assert(isa<Function>(getAsValuePtr()) &&
1419 "Expected function for a 'function' position!");
1420 assert(getAsValuePtr() == &getAssociatedValue() &&
1421 "Associated value mismatch!");
1422 return;
1423 case IRP_ARGUMENT:
1424 assert(isa<Argument>(getAsValuePtr()) &&
1425 "Expected argument for a 'argument' position!");
1426 assert(getAsValuePtr() == &getAssociatedValue() &&
1427 "Associated value mismatch!");
1428 return;
1429 case IRP_CALL_SITE_ARGUMENT: {
1430 assert((CBContext == nullptr) &&
1431 "'call site argument' position must not have CallBaseContext!");
1432 Use *U = getAsUsePtr();
1433 (void)U; // Silence unused variable warning.
1434 assert(U && "Expected use for a 'call site argument' position!");
1435 assert(isa<CallBase>(U->getUser()) &&
1436 "Expected call base user for a 'call site argument' position!");
1437 assert(cast<CallBase>(U->getUser())->isArgOperand(U) &&
1438 "Expected call base argument operand for a 'call site argument' "
1439 "position");
1440 assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) ==
1441 unsigned(getCallSiteArgNo()) &&
1442 "Argument number mismatch!");
1443 assert(U->get() == &getAssociatedValue() && "Associated value mismatch!");
1444 return;
1445 }
1446 }
1447#endif
1448}
1449
1450std::optional<Constant *>
1451Attributor::getAssumedConstant(const IRPosition &IRP,
1452 const AbstractAttribute &AA,
1453 bool &UsedAssumedInformation) {
1454 // First check all callbacks provided by outside AAs. If any of them returns
1455 // a non-null value that is different from the associated value, or
1456 // std::nullopt, we assume it's simplified.
1457 for (auto &CB : SimplificationCallbacks.lookup(Val: IRP)) {
1458 std::optional<Value *> SimplifiedV = CB(IRP, &AA, UsedAssumedInformation);
1459 if (!SimplifiedV)
1460 return std::nullopt;
1461 if (isa_and_nonnull<Constant>(Val: *SimplifiedV))
1462 return cast<Constant>(Val: *SimplifiedV);
1463 return nullptr;
1464 }
1465 if (auto *C = dyn_cast<Constant>(Val: &IRP.getAssociatedValue()))
1466 return C;
1467 SmallVector<AA::ValueAndContext> Values;
1468 if (getAssumedSimplifiedValues(IRP, AA: &AA, Values,
1469 S: AA::ValueScope::Interprocedural,
1470 UsedAssumedInformation)) {
1471 if (Values.empty())
1472 return std::nullopt;
1473 if (auto *C = dyn_cast_or_null<Constant>(
1474 Val: AAPotentialValues::getSingleValue(A&: *this, AA, IRP, Values)))
1475 return C;
1476 }
1477 return nullptr;
1478}
1479
1480std::optional<Value *> Attributor::getAssumedSimplified(
1481 const IRPosition &IRP, const AbstractAttribute *AA,
1482 bool &UsedAssumedInformation, AA::ValueScope S) {
1483 // First check all callbacks provided by outside AAs. If any of them returns
1484 // a non-null value that is different from the associated value, or
1485 // std::nullopt, we assume it's simplified.
1486 for (auto &CB : SimplificationCallbacks.lookup(Val: IRP))
1487 return CB(IRP, AA, UsedAssumedInformation);
1488
1489 SmallVector<AA::ValueAndContext> Values;
1490 if (!getAssumedSimplifiedValues(IRP, AA, Values, S, UsedAssumedInformation))
1491 return &IRP.getAssociatedValue();
1492 if (Values.empty())
1493 return std::nullopt;
1494 if (AA)
1495 if (Value *V = AAPotentialValues::getSingleValue(A&: *this, AA: *AA, IRP, Values))
1496 return V;
1497 if (IRP.getPositionKind() == IRPosition::IRP_RETURNED ||
1498 IRP.getPositionKind() == IRPosition::IRP_CALL_SITE_RETURNED)
1499 return nullptr;
1500 return &IRP.getAssociatedValue();
1501}
1502
1503bool Attributor::getAssumedSimplifiedValues(
1504 const IRPosition &InitialIRP, const AbstractAttribute *AA,
1505 SmallVectorImpl<AA::ValueAndContext> &Values, AA::ValueScope S,
1506 bool &UsedAssumedInformation, bool RecurseForSelectAndPHI) {
1507 SmallPtrSet<Value *, 8> Seen;
1508 SmallVector<IRPosition, 8> Worklist;
1509 Worklist.push_back(Elt: InitialIRP);
1510 while (!Worklist.empty()) {
1511 const IRPosition &IRP = Worklist.pop_back_val();
1512
1513 // First check all callbacks provided by outside AAs. If any of them returns
1514 // a non-null value that is different from the associated value, or
1515 // std::nullopt, we assume it's simplified.
1516 int NV = Values.size();
1517 const auto &SimplificationCBs = SimplificationCallbacks.lookup(Val: IRP);
1518 for (const auto &CB : SimplificationCBs) {
1519 std::optional<Value *> CBResult = CB(IRP, AA, UsedAssumedInformation);
1520 if (!CBResult.has_value())
1521 continue;
1522 Value *V = *CBResult;
1523 if (!V)
1524 return false;
1525 if ((S & AA::ValueScope::Interprocedural) ||
1526 AA::isValidInScope(V: *V, Scope: IRP.getAnchorScope()))
1527 Values.push_back(Elt: AA::ValueAndContext{*V, nullptr});
1528 else
1529 return false;
1530 }
1531 if (SimplificationCBs.empty()) {
1532 // If no high-level/outside simplification occurred, use
1533 // AAPotentialValues.
1534 const auto *PotentialValuesAA =
1535 getOrCreateAAFor<AAPotentialValues>(IRP, QueryingAA: AA, DepClass: DepClassTy::OPTIONAL);
1536 if (PotentialValuesAA &&
1537 PotentialValuesAA->getAssumedSimplifiedValues(A&: *this, Values, S)) {
1538 UsedAssumedInformation |= !PotentialValuesAA->isAtFixpoint();
1539 } else if (IRP.getPositionKind() != IRPosition::IRP_RETURNED) {
1540 Values.push_back(Elt: {IRP.getAssociatedValue(), IRP.getCtxI()});
1541 } else {
1542 // TODO: We could visit all returns and add the operands.
1543 return false;
1544 }
1545 }
1546
1547 if (!RecurseForSelectAndPHI)
1548 break;
1549
1550 for (int I = NV, E = Values.size(); I < E; ++I) {
1551 Value *V = Values[I].getValue();
1552 if (!isa<PHINode>(Val: V) && !isa<SelectInst>(Val: V))
1553 continue;
1554 if (!Seen.insert(Ptr: V).second)
1555 continue;
1556 // Move the last element to this slot.
1557 Values[I] = Values[E - 1];
1558 // Eliminate the last slot, adjust the indices.
1559 Values.pop_back();
1560 --E;
1561 --I;
1562 // Add a new value (select or phi) to the worklist.
1563 Worklist.push_back(Elt: IRPosition::value(V: *V));
1564 }
1565 }
1566 return true;
1567}
1568
1569std::optional<Value *> Attributor::translateArgumentToCallSiteContent(
1570 std::optional<Value *> V, CallBase &CB, const AbstractAttribute &AA,
1571 bool &UsedAssumedInformation) {
1572 if (!V)
1573 return V;
1574 if (*V == nullptr || isa<Constant>(Val: *V))
1575 return V;
1576 if (auto *Arg = dyn_cast<Argument>(Val: *V))
1577 if (CB.getCalledOperand() == Arg->getParent() &&
1578 CB.arg_size() > Arg->getArgNo())
1579 if (!Arg->hasPointeeInMemoryValueAttr())
1580 return getAssumedSimplified(
1581 IRP: IRPosition::callsite_argument(CB, ArgNo: Arg->getArgNo()), AA,
1582 UsedAssumedInformation, S: AA::Intraprocedural);
1583 return nullptr;
1584}
1585
1586Attributor::~Attributor() {
1587 // The abstract attributes are allocated via the BumpPtrAllocator Allocator,
1588 // thus we cannot delete them. We can, and want to, destruct them though.
1589 for (auto &It : AAMap) {
1590 AbstractAttribute *AA = It.getSecond();
1591 AA->~AbstractAttribute();
1592 }
1593}
1594
1595bool Attributor::isAssumedDead(const AbstractAttribute &AA,
1596 const AAIsDead *FnLivenessAA,
1597 bool &UsedAssumedInformation,
1598 bool CheckBBLivenessOnly, DepClassTy DepClass) {
1599 if (!Configuration.UseLiveness)
1600 return false;
1601 const IRPosition &IRP = AA.getIRPosition();
1602 if (!Functions.count(key: IRP.getAnchorScope()))
1603 return false;
1604 return isAssumedDead(IRP, QueryingAA: &AA, FnLivenessAA, UsedAssumedInformation,
1605 CheckBBLivenessOnly, DepClass);
1606}
1607
1608bool Attributor::isAssumedDead(const Use &U,
1609 const AbstractAttribute *QueryingAA,
1610 const AAIsDead *FnLivenessAA,
1611 bool &UsedAssumedInformation,
1612 bool CheckBBLivenessOnly, DepClassTy DepClass) {
1613 if (!Configuration.UseLiveness)
1614 return false;
1615 Instruction *UserI = dyn_cast<Instruction>(Val: U.getUser());
1616 if (!UserI)
1617 return isAssumedDead(IRP: IRPosition::value(V: *U.get()), QueryingAA, FnLivenessAA,
1618 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1619
1620 if (auto *CB = dyn_cast<CallBase>(Val: UserI)) {
1621 // For call site argument uses we can check if the argument is
1622 // unused/dead.
1623 if (CB->isArgOperand(U: &U)) {
1624 const IRPosition &CSArgPos =
1625 IRPosition::callsite_argument(CB: *CB, ArgNo: CB->getArgOperandNo(U: &U));
1626 return isAssumedDead(IRP: CSArgPos, QueryingAA, FnLivenessAA,
1627 UsedAssumedInformation, CheckBBLivenessOnly,
1628 DepClass);
1629 }
1630 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(Val: UserI)) {
1631 const IRPosition &RetPos = IRPosition::returned(F: *RI->getFunction());
1632 return isAssumedDead(IRP: RetPos, QueryingAA, FnLivenessAA,
1633 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1634 } else if (PHINode *PHI = dyn_cast<PHINode>(Val: UserI)) {
1635 BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
1636 return isAssumedDead(I: *IncomingBB->getTerminator(), QueryingAA, LivenessAA: FnLivenessAA,
1637 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1638 } else if (StoreInst *SI = dyn_cast<StoreInst>(Val: UserI)) {
1639 if (!CheckBBLivenessOnly && SI->getPointerOperand() != U.get()) {
1640 const IRPosition IRP = IRPosition::inst(I: *SI);
1641 const AAIsDead *IsDeadAA =
1642 getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClass: DepClassTy::NONE);
1643 if (IsDeadAA && IsDeadAA->isRemovableStore()) {
1644 if (QueryingAA)
1645 recordDependence(FromAA: *IsDeadAA, ToAA: *QueryingAA, DepClass);
1646 if (!IsDeadAA->isKnown(BitsEncoding: AAIsDead::IS_REMOVABLE))
1647 UsedAssumedInformation = true;
1648 return true;
1649 }
1650 }
1651 }
1652
1653 return isAssumedDead(IRP: IRPosition::inst(I: *UserI), QueryingAA, FnLivenessAA,
1654 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1655}
1656
1657bool Attributor::isAssumedDead(const Instruction &I,
1658 const AbstractAttribute *QueryingAA,
1659 const AAIsDead *FnLivenessAA,
1660 bool &UsedAssumedInformation,
1661 bool CheckBBLivenessOnly, DepClassTy DepClass,
1662 bool CheckForDeadStore) {
1663 if (!Configuration.UseLiveness)
1664 return false;
1665 const IRPosition::CallBaseContext *CBCtx =
1666 QueryingAA ? QueryingAA->getCallBaseContext() : nullptr;
1667
1668 if (ManifestAddedBlocks.contains(Ptr: I.getParent()))
1669 return false;
1670
1671 const Function &F = *I.getFunction();
1672 if (!FnLivenessAA || FnLivenessAA->getAnchorScope() != &F)
1673 FnLivenessAA = getOrCreateAAFor<AAIsDead>(IRP: IRPosition::function(F, CBContext: CBCtx),
1674 QueryingAA, DepClass: DepClassTy::NONE);
1675
1676 // Don't use recursive reasoning.
1677 if (!FnLivenessAA || QueryingAA == FnLivenessAA)
1678 return false;
1679
1680 // If we have a context instruction and a liveness AA we use it.
1681 if (CheckBBLivenessOnly ? FnLivenessAA->isAssumedDead(BB: I.getParent())
1682 : FnLivenessAA->isAssumedDead(I: &I)) {
1683 if (QueryingAA)
1684 recordDependence(FromAA: *FnLivenessAA, ToAA: *QueryingAA, DepClass);
1685 if (!FnLivenessAA->isKnownDead(I: &I))
1686 UsedAssumedInformation = true;
1687 return true;
1688 }
1689
1690 if (CheckBBLivenessOnly)
1691 return false;
1692
1693 const IRPosition IRP = IRPosition::inst(I, CBContext: CBCtx);
1694 const AAIsDead *IsDeadAA =
1695 getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClass: DepClassTy::NONE);
1696
1697 // Don't use recursive reasoning.
1698 if (!IsDeadAA || QueryingAA == IsDeadAA)
1699 return false;
1700
1701 if (IsDeadAA->isAssumedDead()) {
1702 if (QueryingAA)
1703 recordDependence(FromAA: *IsDeadAA, ToAA: *QueryingAA, DepClass);
1704 if (!IsDeadAA->isKnownDead())
1705 UsedAssumedInformation = true;
1706 return true;
1707 }
1708
1709 if (CheckForDeadStore && isa<StoreInst>(Val: I) && IsDeadAA->isRemovableStore()) {
1710 if (QueryingAA)
1711 recordDependence(FromAA: *IsDeadAA, ToAA: *QueryingAA, DepClass);
1712 if (!IsDeadAA->isKnownDead())
1713 UsedAssumedInformation = true;
1714 return true;
1715 }
1716
1717 return false;
1718}
1719
1720bool Attributor::isAssumedDead(const IRPosition &IRP,
1721 const AbstractAttribute *QueryingAA,
1722 const AAIsDead *FnLivenessAA,
1723 bool &UsedAssumedInformation,
1724 bool CheckBBLivenessOnly, DepClassTy DepClass) {
1725 if (!Configuration.UseLiveness)
1726 return false;
1727 // Don't check liveness for constants, e.g. functions, used as (floating)
1728 // values since the context instruction and such is here meaningless.
1729 if (IRP.getPositionKind() == IRPosition::IRP_FLOAT &&
1730 isa<Constant>(Val: IRP.getAssociatedValue())) {
1731 return false;
1732 }
1733
1734 Instruction *CtxI = IRP.getCtxI();
1735 if (CtxI &&
1736 isAssumedDead(I: *CtxI, QueryingAA, FnLivenessAA, UsedAssumedInformation,
1737 /* CheckBBLivenessOnly */ true,
1738 DepClass: CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL))
1739 return true;
1740
1741 if (CheckBBLivenessOnly)
1742 return false;
1743
1744 // If we haven't succeeded we query the specific liveness info for the IRP.
1745 const AAIsDead *IsDeadAA;
1746 if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE)
1747 IsDeadAA = getOrCreateAAFor<AAIsDead>(
1748 IRP: IRPosition::callsite_returned(CB: cast<CallBase>(Val&: IRP.getAssociatedValue())),
1749 QueryingAA, DepClass: DepClassTy::NONE);
1750 else
1751 IsDeadAA = getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClass: DepClassTy::NONE);
1752
1753 // Don't use recursive reasoning.
1754 if (!IsDeadAA || QueryingAA == IsDeadAA)
1755 return false;
1756
1757 if (IsDeadAA->isAssumedDead()) {
1758 if (QueryingAA)
1759 recordDependence(FromAA: *IsDeadAA, ToAA: *QueryingAA, DepClass);
1760 if (!IsDeadAA->isKnownDead())
1761 UsedAssumedInformation = true;
1762 return true;
1763 }
1764
1765 return false;
1766}
1767
1768bool Attributor::isAssumedDead(const BasicBlock &BB,
1769 const AbstractAttribute *QueryingAA,
1770 const AAIsDead *FnLivenessAA,
1771 DepClassTy DepClass) {
1772 if (!Configuration.UseLiveness)
1773 return false;
1774 const Function &F = *BB.getParent();
1775 if (!FnLivenessAA || FnLivenessAA->getAnchorScope() != &F)
1776 FnLivenessAA = getOrCreateAAFor<AAIsDead>(IRP: IRPosition::function(F),
1777 QueryingAA, DepClass: DepClassTy::NONE);
1778
1779 // Don't use recursive reasoning.
1780 if (!FnLivenessAA || QueryingAA == FnLivenessAA)
1781 return false;
1782
1783 if (FnLivenessAA->isAssumedDead(BB: &BB)) {
1784 if (QueryingAA)
1785 recordDependence(FromAA: *FnLivenessAA, ToAA: *QueryingAA, DepClass);
1786 return true;
1787 }
1788
1789 return false;
1790}
1791
1792bool Attributor::checkForAllCallees(
1793 function_ref<bool(ArrayRef<const Function *>)> Pred,
1794 const AbstractAttribute &QueryingAA, const CallBase &CB) {
1795 if (const Function *Callee = dyn_cast<Function>(Val: CB.getCalledOperand()))
1796 return Pred(Callee);
1797
1798 const auto *CallEdgesAA = getAAFor<AACallEdges>(
1799 QueryingAA, IRP: IRPosition::callsite_function(CB), DepClass: DepClassTy::OPTIONAL);
1800 if (!CallEdgesAA || CallEdgesAA->hasUnknownCallee())
1801 return false;
1802
1803 const auto &Callees = CallEdgesAA->getOptimisticEdges();
1804 return Pred(Callees.getArrayRef());
1805}
1806
1807bool canMarkAsVisited(const User *Usr) {
1808 return isa<PHINode>(Val: Usr) || !isa<Instruction>(Val: Usr);
1809}
1810
1811bool Attributor::checkForAllUses(
1812 function_ref<bool(const Use &, bool &)> Pred,
1813 const AbstractAttribute &QueryingAA, const Value &V,
1814 bool CheckBBLivenessOnly, DepClassTy LivenessDepClass,
1815 bool IgnoreDroppableUses,
1816 function_ref<bool(const Use &OldU, const Use &NewU)> EquivalentUseCB) {
1817
1818 // Check virtual uses first.
1819 for (VirtualUseCallbackTy &CB : VirtualUseCallbacks.lookup(Val: &V))
1820 if (!CB(*this, &QueryingAA))
1821 return false;
1822
1823 if (isa<ConstantData>(Val: V))
1824 return false;
1825
1826 // Check the trivial case first as it catches void values.
1827 if (V.use_empty())
1828 return true;
1829
1830 const IRPosition &IRP = QueryingAA.getIRPosition();
1831 SmallVector<const Use *, 16> Worklist;
1832 SmallPtrSet<const Use *, 16> Visited;
1833
1834 auto AddUsers = [&](const Value &V, const Use *OldUse) {
1835 for (const Use &UU : V.uses()) {
1836 if (OldUse && EquivalentUseCB && !EquivalentUseCB(*OldUse, UU)) {
1837 LLVM_DEBUG(dbgs() << "[Attributor] Potential copy was "
1838 "rejected by the equivalence call back: "
1839 << *UU << "!\n");
1840 return false;
1841 }
1842
1843 Worklist.push_back(Elt: &UU);
1844 }
1845 return true;
1846 };
1847
1848 AddUsers(V, /* OldUse */ nullptr);
1849
1850 LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size()
1851 << " initial uses to check\n");
1852
1853 const Function *ScopeFn = IRP.getAnchorScope();
1854 const auto *LivenessAA =
1855 ScopeFn ? getAAFor<AAIsDead>(QueryingAA, IRP: IRPosition::function(F: *ScopeFn),
1856 DepClass: DepClassTy::NONE)
1857 : nullptr;
1858
1859 while (!Worklist.empty()) {
1860 const Use *U = Worklist.pop_back_val();
1861 if (canMarkAsVisited(Usr: U->getUser()) && !Visited.insert(Ptr: U).second)
1862 continue;
1863 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
1864 if (auto *Fn = dyn_cast<Function>(U->getUser()))
1865 dbgs() << "[Attributor] Check use: " << **U << " in " << Fn->getName()
1866 << "\n";
1867 else
1868 dbgs() << "[Attributor] Check use: " << **U << " in " << *U->getUser()
1869 << "\n";
1870 });
1871 bool UsedAssumedInformation = false;
1872 if (isAssumedDead(U: *U, QueryingAA: &QueryingAA, FnLivenessAA: LivenessAA, UsedAssumedInformation,
1873 CheckBBLivenessOnly, DepClass: LivenessDepClass)) {
1874 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
1875 dbgs() << "[Attributor] Dead use, skip!\n");
1876 continue;
1877 }
1878 if (IgnoreDroppableUses && U->getUser()->isDroppable()) {
1879 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
1880 dbgs() << "[Attributor] Droppable user, skip!\n");
1881 continue;
1882 }
1883
1884 if (auto *SI = dyn_cast<StoreInst>(Val: U->getUser())) {
1885 if (&SI->getOperandUse(i: 0) == U) {
1886 if (!Visited.insert(Ptr: U).second)
1887 continue;
1888 SmallSetVector<Value *, 4> PotentialCopies;
1889 if (AA::getPotentialCopiesOfStoredValue(
1890 A&: *this, SI&: *SI, PotentialCopies, QueryingAA, UsedAssumedInformation,
1891 /* OnlyExact */ true)) {
1892 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
1893 dbgs()
1894 << "[Attributor] Value is stored, continue with "
1895 << PotentialCopies.size()
1896 << " potential copies instead!\n");
1897 for (Value *PotentialCopy : PotentialCopies)
1898 if (!AddUsers(*PotentialCopy, U))
1899 return false;
1900 continue;
1901 }
1902 }
1903 }
1904
1905 bool Follow = false;
1906 if (!Pred(*U, Follow))
1907 return false;
1908 if (!Follow)
1909 continue;
1910
1911 User &Usr = *U->getUser();
1912 AddUsers(Usr, /* OldUse */ nullptr);
1913 }
1914
1915 return true;
1916}
1917
1918bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
1919 const AbstractAttribute &QueryingAA,
1920 bool RequireAllCallSites,
1921 bool &UsedAssumedInformation) {
1922 // We can try to determine information from
1923 // the call sites. However, this is only possible all call sites are known,
1924 // hence the function has internal linkage.
1925 const IRPosition &IRP = QueryingAA.getIRPosition();
1926 const Function *AssociatedFunction = IRP.getAssociatedFunction();
1927 if (!AssociatedFunction) {
1928 LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP
1929 << "\n");
1930 return false;
1931 }
1932
1933 return checkForAllCallSites(Pred, Fn: *AssociatedFunction, RequireAllCallSites,
1934 QueryingAA: &QueryingAA, UsedAssumedInformation);
1935}
1936
1937bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
1938 const Function &Fn,
1939 bool RequireAllCallSites,
1940 const AbstractAttribute *QueryingAA,
1941 bool &UsedAssumedInformation,
1942 bool CheckPotentiallyDead) {
1943 if (RequireAllCallSites && !Fn.hasLocalLinkage()) {
1944 LLVM_DEBUG(
1945 dbgs()
1946 << "[Attributor] Function " << Fn.getName()
1947 << " has no internal linkage, hence not all call sites are known\n");
1948 return false;
1949 }
1950 // Check virtual uses first.
1951 for (VirtualUseCallbackTy &CB : VirtualUseCallbacks.lookup(Val: &Fn))
1952 if (!CB(*this, QueryingAA))
1953 return false;
1954
1955 SmallVector<const Use *, 8> Uses(make_pointer_range(Range: Fn.uses()));
1956 for (unsigned u = 0; u < Uses.size(); ++u) {
1957 const Use &U = *Uses[u];
1958 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
1959 if (auto *Fn = dyn_cast<Function>(U))
1960 dbgs() << "[Attributor] Check use: " << Fn->getName() << " in "
1961 << *U.getUser() << "\n";
1962 else
1963 dbgs() << "[Attributor] Check use: " << *U << " in " << *U.getUser()
1964 << "\n";
1965 });
1966 if (!CheckPotentiallyDead &&
1967 isAssumedDead(U, QueryingAA, FnLivenessAA: nullptr, UsedAssumedInformation,
1968 /* CheckBBLivenessOnly */ true)) {
1969 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
1970 dbgs() << "[Attributor] Dead use, skip!\n");
1971 continue;
1972 }
1973 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: U.getUser())) {
1974 if (CE->isCast() && CE->getType()->isPointerTy()) {
1975 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
1976 dbgs() << "[Attributor] Use, is constant cast expression, add "
1977 << CE->getNumUses() << " uses of that expression instead!\n";
1978 });
1979 for (const Use &CEU : CE->uses())
1980 Uses.push_back(Elt: &CEU);
1981 continue;
1982 }
1983 }
1984
1985 AbstractCallSite ACS(&U);
1986 if (!ACS) {
1987 LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName()
1988 << " has non call site use " << *U.get() << " in "
1989 << *U.getUser() << "\n");
1990 return false;
1991 }
1992
1993 const Use *EffectiveUse =
1994 ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U;
1995 if (!ACS.isCallee(U: EffectiveUse)) {
1996 if (!RequireAllCallSites) {
1997 LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
1998 << " is not a call of " << Fn.getName()
1999 << ", skip use\n");
2000 continue;
2001 }
2002 LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
2003 << " is an invalid use of " << Fn.getName() << "\n");
2004 return false;
2005 }
2006
2007 // Make sure the arguments that can be matched between the call site and the
2008 // callee argee on their type. It is unlikely they do not and it doesn't
2009 // make sense for all attributes to know/care about this.
2010 assert(&Fn == ACS.getCalledFunction() && "Expected known callee");
2011 unsigned MinArgsParams =
2012 std::min(a: size_t(ACS.getNumArgOperands()), b: Fn.arg_size());
2013 for (unsigned u = 0; u < MinArgsParams; ++u) {
2014 Value *CSArgOp = ACS.getCallArgOperand(ArgNo: u);
2015 if (CSArgOp && Fn.getArg(i: u)->getType() != CSArgOp->getType()) {
2016 LLVM_DEBUG(
2017 dbgs() << "[Attributor] Call site / callee argument type mismatch ["
2018 << u << "@" << Fn.getName() << ": "
2019 << *Fn.getArg(u)->getType() << " vs. "
2020 << *ACS.getCallArgOperand(u)->getType() << "\n");
2021 return false;
2022 }
2023 }
2024
2025 if (Pred(ACS))
2026 continue;
2027
2028 LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for "
2029 << *ACS.getInstruction() << "\n");
2030 return false;
2031 }
2032
2033 return true;
2034}
2035
2036bool Attributor::shouldPropagateCallBaseContext(const IRPosition &IRP) {
2037 // TODO: Maintain a cache of Values that are
2038 // on the pathway from a Argument to a Instruction that would effect the
2039 // liveness/return state etc.
2040 return EnableCallSiteSpecific;
2041}
2042
2043bool Attributor::checkForAllReturnedValues(function_ref<bool(Value &)> Pred,
2044 const AbstractAttribute &QueryingAA,
2045 AA::ValueScope S,
2046 bool RecurseForSelectAndPHI) {
2047
2048 const IRPosition &IRP = QueryingAA.getIRPosition();
2049 const Function *AssociatedFunction = IRP.getAssociatedFunction();
2050 if (!AssociatedFunction)
2051 return false;
2052
2053 bool UsedAssumedInformation = false;
2054 SmallVector<AA::ValueAndContext> Values;
2055 if (!getAssumedSimplifiedValues(
2056 InitialIRP: IRPosition::returned(F: *AssociatedFunction), AA: &QueryingAA, Values, S,
2057 UsedAssumedInformation, RecurseForSelectAndPHI))
2058 return false;
2059
2060 return llvm::all_of(Range&: Values, P: [&](const AA::ValueAndContext &VAC) {
2061 return Pred(*VAC.getValue());
2062 });
2063}
2064
2065static bool checkForAllInstructionsImpl(
2066 Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap,
2067 function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA,
2068 const AAIsDead *LivenessAA, ArrayRef<unsigned> Opcodes,
2069 bool &UsedAssumedInformation, bool CheckBBLivenessOnly = false,
2070 bool CheckPotentiallyDead = false) {
2071 for (unsigned Opcode : Opcodes) {
2072 // Check if we have instructions with this opcode at all first.
2073 auto *Insts = OpcodeInstMap.lookup(Val: Opcode);
2074 if (!Insts)
2075 continue;
2076
2077 for (Instruction *I : *Insts) {
2078 // Skip dead instructions.
2079 if (A && !CheckPotentiallyDead &&
2080 A->isAssumedDead(IRP: IRPosition::inst(I: *I), QueryingAA, FnLivenessAA: LivenessAA,
2081 UsedAssumedInformation, CheckBBLivenessOnly)) {
2082 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
2083 dbgs() << "[Attributor] Instruction " << *I
2084 << " is potentially dead, skip!\n";);
2085 continue;
2086 }
2087
2088 if (!Pred(*I))
2089 return false;
2090 }
2091 }
2092 return true;
2093}
2094
2095bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
2096 const Function *Fn,
2097 const AbstractAttribute *QueryingAA,
2098 ArrayRef<unsigned> Opcodes,
2099 bool &UsedAssumedInformation,
2100 bool CheckBBLivenessOnly,
2101 bool CheckPotentiallyDead) {
2102 // Since we need to provide instructions we have to have an exact definition.
2103 if (!Fn || Fn->isDeclaration())
2104 return false;
2105
2106 const IRPosition &QueryIRP = IRPosition::function(F: *Fn);
2107 const auto *LivenessAA =
2108 CheckPotentiallyDead && QueryingAA
2109 ? (getAAFor<AAIsDead>(QueryingAA: *QueryingAA, IRP: QueryIRP, DepClass: DepClassTy::NONE))
2110 : nullptr;
2111
2112 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F: *Fn);
2113 if (!checkForAllInstructionsImpl(A: this, OpcodeInstMap, Pred, QueryingAA,
2114 LivenessAA, Opcodes, UsedAssumedInformation,
2115 CheckBBLivenessOnly, CheckPotentiallyDead))
2116 return false;
2117
2118 return true;
2119}
2120
2121bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
2122 const AbstractAttribute &QueryingAA,
2123 ArrayRef<unsigned> Opcodes,
2124 bool &UsedAssumedInformation,
2125 bool CheckBBLivenessOnly,
2126 bool CheckPotentiallyDead) {
2127 const IRPosition &IRP = QueryingAA.getIRPosition();
2128 const Function *AssociatedFunction = IRP.getAssociatedFunction();
2129 return checkForAllInstructions(Pred, Fn: AssociatedFunction, QueryingAA: &QueryingAA, Opcodes,
2130 UsedAssumedInformation, CheckBBLivenessOnly,
2131 CheckPotentiallyDead);
2132}
2133
2134bool Attributor::checkForAllReadWriteInstructions(
2135 function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA,
2136 bool &UsedAssumedInformation) {
2137 TimeTraceScope TS("checkForAllReadWriteInstructions");
2138
2139 const Function *AssociatedFunction =
2140 QueryingAA.getIRPosition().getAssociatedFunction();
2141 if (!AssociatedFunction)
2142 return false;
2143
2144 const IRPosition &QueryIRP = IRPosition::function(F: *AssociatedFunction);
2145 const auto *LivenessAA =
2146 getAAFor<AAIsDead>(QueryingAA, IRP: QueryIRP, DepClass: DepClassTy::NONE);
2147
2148 for (Instruction *I :
2149 InfoCache.getReadOrWriteInstsForFunction(F: *AssociatedFunction)) {
2150 // Skip dead instructions.
2151 if (isAssumedDead(IRP: IRPosition::inst(I: *I), QueryingAA: &QueryingAA, FnLivenessAA: LivenessAA,
2152 UsedAssumedInformation))
2153 continue;
2154
2155 if (!Pred(*I))
2156 return false;
2157 }
2158
2159 return true;
2160}
2161
2162void Attributor::runTillFixpoint() {
2163 TimeTraceScope TimeScope("Attributor::runTillFixpoint");
2164 LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
2165 << DG.SyntheticRoot.Deps.size()
2166 << " abstract attributes.\n");
2167
2168 // Now that all abstract attributes are collected and initialized we start
2169 // the abstract analysis.
2170
2171 unsigned IterationCounter = 1;
2172 unsigned MaxIterations =
2173 Configuration.MaxFixpointIterations.value_or(u&: SetFixpointIterations);
2174
2175 SmallVector<AbstractAttribute *, 32> ChangedAAs;
2176 SetVector<AbstractAttribute *> Worklist, InvalidAAs;
2177 Worklist.insert_range(R&: DG.SyntheticRoot);
2178
2179 do {
2180 // Remember the size to determine new attributes.
2181 size_t NumAAs = DG.SyntheticRoot.Deps.size();
2182 LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
2183 << ", Worklist size: " << Worklist.size() << "\n");
2184
2185 // For invalid AAs we can fix dependent AAs that have a required dependence,
2186 // thereby folding long dependence chains in a single step without the need
2187 // to run updates.
2188 for (unsigned u = 0; u < InvalidAAs.size(); ++u) {
2189 AbstractAttribute *InvalidAA = InvalidAAs[u];
2190
2191 // Check the dependences to fast track invalidation.
2192 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
2193 dbgs() << "[Attributor] InvalidAA: " << *InvalidAA
2194 << " has " << InvalidAA->Deps.size()
2195 << " required & optional dependences\n");
2196 for (auto &DepIt : InvalidAA->Deps) {
2197 AbstractAttribute *DepAA = cast<AbstractAttribute>(Val: DepIt.getPointer());
2198 if (DepIt.getInt() == unsigned(DepClassTy::OPTIONAL)) {
2199 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
2200 dbgs() << " - recompute: " << *DepAA);
2201 Worklist.insert(X: DepAA);
2202 continue;
2203 }
2204 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, dbgs()
2205 << " - invalidate: " << *DepAA);
2206 DepAA->getState().indicatePessimisticFixpoint();
2207 assert(DepAA->getState().isAtFixpoint() && "Expected fixpoint state!");
2208 if (!DepAA->getState().isValidState())
2209 InvalidAAs.insert(X: DepAA);
2210 else
2211 ChangedAAs.push_back(Elt: DepAA);
2212 }
2213 InvalidAA->Deps.clear();
2214 }
2215
2216 // Add all abstract attributes that are potentially dependent on one that
2217 // changed to the work list.
2218 for (AbstractAttribute *ChangedAA : ChangedAAs) {
2219 for (auto &DepIt : ChangedAA->Deps)
2220 Worklist.insert(X: cast<AbstractAttribute>(Val: DepIt.getPointer()));
2221 ChangedAA->Deps.clear();
2222 }
2223
2224 LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter
2225 << ", Worklist+Dependent size: " << Worklist.size()
2226 << "\n");
2227
2228 // Reset the changed and invalid set.
2229 ChangedAAs.clear();
2230 InvalidAAs.clear();
2231
2232 // Update all abstract attribute in the work list and record the ones that
2233 // changed.
2234 for (AbstractAttribute *AA : Worklist) {
2235 const auto &AAState = AA->getState();
2236 if (!AAState.isAtFixpoint())
2237 if (updateAA(AA&: *AA) == ChangeStatus::CHANGED)
2238 ChangedAAs.push_back(Elt: AA);
2239
2240 // Use the InvalidAAs vector to propagate invalid states fast transitively
2241 // without requiring updates.
2242 if (!AAState.isValidState())
2243 InvalidAAs.insert(X: AA);
2244 }
2245
2246 // Add attributes to the changed set if they have been created in the last
2247 // iteration.
2248 ChangedAAs.append(in_start: DG.SyntheticRoot.begin() + NumAAs,
2249 in_end: DG.SyntheticRoot.end());
2250
2251 // Reset the work list and repopulate with the changed abstract attributes.
2252 // Note that dependent ones are added above.
2253 Worklist.clear();
2254 Worklist.insert_range(R&: ChangedAAs);
2255 Worklist.insert_range(R&: QueryAAsAwaitingUpdate);
2256 QueryAAsAwaitingUpdate.clear();
2257
2258 } while (!Worklist.empty() && (IterationCounter++ < MaxIterations));
2259
2260 if (IterationCounter > MaxIterations && !Functions.empty()) {
2261 auto Remark = [&](OptimizationRemarkMissed ORM) {
2262 return ORM << "Attributor did not reach a fixpoint after "
2263 << ore::NV("Iterations", MaxIterations) << " iterations.";
2264 };
2265 Function *F = Functions.front();
2266 emitRemark<OptimizationRemarkMissed>(F, RemarkName: "FixedPoint", RemarkCB&: Remark);
2267 }
2268
2269 LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
2270 << IterationCounter << "/" << MaxIterations
2271 << " iterations\n");
2272
2273 // Reset abstract arguments not settled in a sound fixpoint by now. This
2274 // happens when we stopped the fixpoint iteration early. Note that only the
2275 // ones marked as "changed" *and* the ones transitively depending on them
2276 // need to be reverted to a pessimistic state. Others might not be in a
2277 // fixpoint state but we can use the optimistic results for them anyway.
2278 SmallPtrSet<AbstractAttribute *, 32> Visited;
2279 for (unsigned u = 0; u < ChangedAAs.size(); u++) {
2280 AbstractAttribute *ChangedAA = ChangedAAs[u];
2281 if (!Visited.insert(Ptr: ChangedAA).second)
2282 continue;
2283
2284 AbstractState &State = ChangedAA->getState();
2285 if (!State.isAtFixpoint()) {
2286 State.indicatePessimisticFixpoint();
2287
2288 NumAttributesTimedOut++;
2289 }
2290
2291 for (auto &DepIt : ChangedAA->Deps)
2292 ChangedAAs.push_back(Elt: cast<AbstractAttribute>(Val: DepIt.getPointer()));
2293 ChangedAA->Deps.clear();
2294 }
2295
2296 LLVM_DEBUG({
2297 if (!Visited.empty())
2298 dbgs() << "\n[Attributor] Finalized " << Visited.size()
2299 << " abstract attributes.\n";
2300 });
2301}
2302
2303void Attributor::registerForUpdate(AbstractAttribute &AA) {
2304 assert(AA.isQueryAA() &&
2305 "Non-query AAs should not be required to register for updates!");
2306 QueryAAsAwaitingUpdate.insert(X: &AA);
2307}
2308
2309ChangeStatus Attributor::manifestAttributes() {
2310 TimeTraceScope TimeScope("Attributor::manifestAttributes");
2311 size_t NumFinalAAs = DG.SyntheticRoot.Deps.size();
2312
2313 unsigned NumManifested = 0;
2314 unsigned NumAtFixpoint = 0;
2315 ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
2316 for (auto &DepAA : DG.SyntheticRoot.Deps) {
2317 AbstractAttribute *AA = cast<AbstractAttribute>(Val: DepAA.getPointer());
2318 AbstractState &State = AA->getState();
2319
2320 // If there is not already a fixpoint reached, we can now take the
2321 // optimistic state. This is correct because we enforced a pessimistic one
2322 // on abstract attributes that were transitively dependent on a changed one
2323 // already above.
2324 if (!State.isAtFixpoint())
2325 State.indicateOptimisticFixpoint();
2326
2327 // We must not manifest Attributes that use Callbase info.
2328 if (AA->hasCallBaseContext())
2329 continue;
2330 // If the state is invalid, we do not try to manifest it.
2331 if (!State.isValidState())
2332 continue;
2333
2334 if (AA->getCtxI() && !isRunOn(Fn&: *AA->getAnchorScope()))
2335 continue;
2336
2337 // Skip dead code.
2338 bool UsedAssumedInformation = false;
2339 if (isAssumedDead(AA: *AA, FnLivenessAA: nullptr, UsedAssumedInformation,
2340 /* CheckBBLivenessOnly */ true))
2341 continue;
2342 // Check if the manifest debug counter that allows skipping manifestation of
2343 // AAs
2344 if (!DebugCounter::shouldExecute(Counter&: ManifestDBGCounter))
2345 continue;
2346 // Manifest the state and record if we changed the IR.
2347 ChangeStatus LocalChange = AA->manifest(A&: *this);
2348 if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
2349 AA->trackStatistics();
2350 LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA
2351 << "\n");
2352
2353 ManifestChange = ManifestChange | LocalChange;
2354
2355 NumAtFixpoint++;
2356 NumManifested += (LocalChange == ChangeStatus::CHANGED);
2357 }
2358
2359 (void)NumManifested;
2360 (void)NumAtFixpoint;
2361 LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
2362 << " arguments while " << NumAtFixpoint
2363 << " were in a valid fixpoint state\n");
2364
2365 NumAttributesManifested += NumManifested;
2366 NumAttributesValidFixpoint += NumAtFixpoint;
2367
2368 (void)NumFinalAAs;
2369 if (NumFinalAAs != DG.SyntheticRoot.Deps.size()) {
2370 auto DepIt = DG.SyntheticRoot.Deps.begin();
2371 for (unsigned u = 0; u < NumFinalAAs; ++u)
2372 ++DepIt;
2373 for (unsigned u = NumFinalAAs; u < DG.SyntheticRoot.Deps.size();
2374 ++u, ++DepIt) {
2375 errs() << "Unexpected abstract attribute: "
2376 << cast<AbstractAttribute>(Val: DepIt->getPointer()) << " :: "
2377 << cast<AbstractAttribute>(Val: DepIt->getPointer())
2378 ->getIRPosition()
2379 .getAssociatedValue()
2380 << "\n";
2381 }
2382 llvm_unreachable("Expected the final number of abstract attributes to "
2383 "remain unchanged!");
2384 }
2385
2386 for (auto &It : AttrsMap) {
2387 AttributeList &AL = It.getSecond();
2388 const IRPosition &IRP =
2389 isa<Function>(Val: It.getFirst())
2390 ? IRPosition::function(F: *cast<Function>(Val: It.getFirst()))
2391 : IRPosition::callsite_function(CB: *cast<CallBase>(Val: It.getFirst()));
2392 IRP.setAttrList(AL);
2393 }
2394
2395 return ManifestChange;
2396}
2397
2398void Attributor::identifyDeadInternalFunctions() {
2399 // Early exit if we don't intend to delete functions.
2400 if (!Configuration.DeleteFns)
2401 return;
2402
2403 // To avoid triggering an assertion in the lazy call graph we will not delete
2404 // any internal library functions. We should modify the assertion though and
2405 // allow internals to be deleted.
2406 const auto *TLI =
2407 isModulePass()
2408 ? nullptr
2409 : getInfoCache().getTargetLibraryInfoForFunction(F: *Functions.back());
2410
2411 // Identify dead internal functions and delete them. This happens outside
2412 // the other fixpoint analysis as we might treat potentially dead functions
2413 // as live to lower the number of iterations. If they happen to be dead, the
2414 // below fixpoint loop will identify and eliminate them.
2415
2416 SmallVector<Function *, 8> InternalFns;
2417 for (Function *F : Functions)
2418 if (F->hasLocalLinkage() &&
2419 (isModulePass() || TLI->getLibFunc(FDecl: *F) == NotLibFunc))
2420 InternalFns.push_back(Elt: F);
2421
2422 SmallPtrSet<Function *, 8> LiveInternalFns;
2423 bool FoundLiveInternal = true;
2424 while (FoundLiveInternal) {
2425 FoundLiveInternal = false;
2426 for (Function *&F : InternalFns) {
2427 if (!F)
2428 continue;
2429
2430 bool UsedAssumedInformation = false;
2431 if (checkForAllCallSites(
2432 Pred: [&](AbstractCallSite ACS) {
2433 Function *Callee = ACS.getInstruction()->getFunction();
2434 return ToBeDeletedFunctions.count(key: Callee) ||
2435 (Functions.count(key: Callee) && Callee->hasLocalLinkage() &&
2436 !LiveInternalFns.count(Ptr: Callee));
2437 },
2438 Fn: *F, RequireAllCallSites: true, QueryingAA: nullptr, UsedAssumedInformation)) {
2439 continue;
2440 }
2441
2442 LiveInternalFns.insert(Ptr: F);
2443 F = nullptr;
2444 FoundLiveInternal = true;
2445 }
2446 }
2447
2448 for (Function *F : InternalFns)
2449 if (F)
2450 ToBeDeletedFunctions.insert(X: F);
2451}
2452
2453ChangeStatus Attributor::cleanupIR() {
2454 TimeTraceScope TimeScope("Attributor::cleanupIR");
2455 // Delete stuff at the end to avoid invalid references and a nice order.
2456 LLVM_DEBUG(dbgs() << "\n[Attributor] Delete/replace at least "
2457 << ToBeDeletedFunctions.size() << " functions and "
2458 << ToBeDeletedBlocks.size() << " blocks and "
2459 << ToBeDeletedInsts.size() << " instructions and "
2460 << ToBeChangedValues.size() << " values and "
2461 << ToBeChangedUses.size() << " uses. To insert "
2462 << ToBeChangedToUnreachableInsts.size()
2463 << " unreachables.\n"
2464 << "Preserve manifest added " << ManifestAddedBlocks.size()
2465 << " blocks\n");
2466
2467 SmallVector<WeakTrackingVH, 32> DeadInsts;
2468 SmallVector<Instruction *, 32> TerminatorsToFold;
2469
2470 auto ReplaceUse = [&](Use *U, Value *NewV) {
2471 Value *OldV = U->get();
2472
2473 // If we plan to replace NewV we need to update it at this point.
2474 do {
2475 const auto &Entry = ToBeChangedValues.lookup(Key: NewV);
2476 if (!get<0>(Pair: Entry))
2477 break;
2478 NewV = get<0>(Pair: Entry);
2479 } while (true);
2480
2481 Instruction *I = dyn_cast<Instruction>(Val: U->getUser());
2482 assert((!I || isRunOn(*I->getFunction())) &&
2483 "Cannot replace an instruction outside the current SCC!");
2484
2485 // Do not replace uses in returns if the value is a must-tail call we will
2486 // not delete.
2487 if (auto *RI = dyn_cast_or_null<ReturnInst>(Val: I)) {
2488 if (auto *CI = dyn_cast<CallInst>(Val: OldV->stripPointerCasts()))
2489 if (CI->isMustTailCall() && !ToBeDeletedInsts.count(key: CI))
2490 return;
2491 // If we rewrite a return and the new value is not an argument, strip the
2492 // `returned` attribute as it is wrong now.
2493 if (!isa<Argument>(Val: NewV))
2494 for (auto &Arg : RI->getFunction()->args())
2495 Arg.removeAttr(Kind: Attribute::Returned);
2496 }
2497
2498 LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser()
2499 << " instead of " << *OldV << "\n");
2500 U->set(NewV);
2501
2502 if (Instruction *I = dyn_cast<Instruction>(Val: OldV)) {
2503 CGModifiedFunctions.insert(X: I->getFunction());
2504 if (!isa<PHINode>(Val: I) && !ToBeDeletedInsts.count(key: I) &&
2505 isInstructionTriviallyDead(I))
2506 DeadInsts.push_back(Elt: I);
2507 }
2508 if (isa<UndefValue>(Val: NewV) && isa<CallBase>(Val: U->getUser())) {
2509 auto *CB = cast<CallBase>(Val: U->getUser());
2510 if (CB->isArgOperand(U)) {
2511 unsigned Idx = CB->getArgOperandNo(U);
2512 CB->removeParamAttr(ArgNo: Idx, Kind: Attribute::NoUndef);
2513 auto *Callee = dyn_cast_if_present<Function>(Val: CB->getCalledOperand());
2514 if (Callee && Callee->arg_size() > Idx)
2515 Callee->removeParamAttr(ArgNo: Idx, Kind: Attribute::NoUndef);
2516 }
2517 }
2518 if (isa<Constant>(Val: NewV) && isa<CondBrInst>(Val: U->getUser())) {
2519 Instruction *UserI = cast<Instruction>(Val: U->getUser());
2520 if (isa<UndefValue>(Val: NewV)) {
2521 ToBeChangedToUnreachableInsts.insert(X: UserI);
2522 } else {
2523 TerminatorsToFold.push_back(Elt: UserI);
2524 }
2525 }
2526 };
2527
2528 for (auto &It : ToBeChangedUses) {
2529 Use *U = It.first;
2530 Value *NewV = It.second;
2531 ReplaceUse(U, NewV);
2532 }
2533
2534 SmallVector<Use *, 4> Uses;
2535 for (auto &It : ToBeChangedValues) {
2536 Value *OldV = It.first;
2537 auto [NewV, Done] = It.second;
2538 Uses.clear();
2539 for (auto &U : OldV->uses())
2540 if (Done || !U.getUser()->isDroppable())
2541 Uses.push_back(Elt: &U);
2542 for (Use *U : Uses) {
2543 if (auto *I = dyn_cast<Instruction>(Val: U->getUser()))
2544 if (!isRunOn(Fn&: *I->getFunction()))
2545 continue;
2546 ReplaceUse(U, NewV);
2547 }
2548 }
2549
2550 for (const auto &V : InvokeWithDeadSuccessor)
2551 if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(Val: V)) {
2552 assert(isRunOn(*II->getFunction()) &&
2553 "Cannot replace an invoke outside the current SCC!");
2554 bool UnwindBBIsDead = II->hasFnAttr(Kind: Attribute::NoUnwind);
2555 bool NormalBBIsDead = II->hasFnAttr(Kind: Attribute::NoReturn);
2556 bool Invoke2CallAllowed =
2557 !AAIsDead::mayCatchAsynchronousExceptions(F: *II->getFunction());
2558 assert((UnwindBBIsDead || NormalBBIsDead) &&
2559 "Invoke does not have dead successors!");
2560 BasicBlock *BB = II->getParent();
2561 BasicBlock *NormalDestBB = II->getNormalDest();
2562 if (UnwindBBIsDead) {
2563 Instruction *NormalNextIP = &NormalDestBB->front();
2564 if (Invoke2CallAllowed) {
2565 changeToCall(II);
2566 NormalNextIP = BB->getTerminator();
2567 }
2568 if (NormalBBIsDead)
2569 ToBeChangedToUnreachableInsts.insert(X: NormalNextIP);
2570 } else {
2571 assert(NormalBBIsDead && "Broken invariant!");
2572 if (!NormalDestBB->getUniquePredecessor())
2573 NormalDestBB = SplitBlockPredecessors(BB: NormalDestBB, Preds: {BB}, Suffix: ".dead");
2574 ToBeChangedToUnreachableInsts.insert(X: &NormalDestBB->front());
2575 }
2576 }
2577 for (Instruction *I : TerminatorsToFold) {
2578 assert(isRunOn(*I->getFunction()) &&
2579 "Cannot replace a terminator outside the current SCC!");
2580 CGModifiedFunctions.insert(X: I->getFunction());
2581 ConstantFoldTerminator(BB: I->getParent());
2582 }
2583 for (const auto &V : ToBeChangedToUnreachableInsts)
2584 if (Instruction *I = dyn_cast_or_null<Instruction>(Val: V)) {
2585 LLVM_DEBUG(dbgs() << "[Attributor] Change to unreachable: " << *I
2586 << "\n");
2587 assert(isRunOn(*I->getFunction()) &&
2588 "Cannot replace an instruction outside the current SCC!");
2589 CGModifiedFunctions.insert(X: I->getFunction());
2590 changeToUnreachable(I);
2591 }
2592
2593 for (const auto &V : ToBeDeletedInsts) {
2594 if (Instruction *I = dyn_cast_or_null<Instruction>(Val: V)) {
2595 assert((!isa<CallBase>(I) || isa<IntrinsicInst>(I) ||
2596 isRunOn(*I->getFunction())) &&
2597 "Cannot delete an instruction outside the current SCC!");
2598 I->dropDroppableUses();
2599 CGModifiedFunctions.insert(X: I->getFunction());
2600 if (!I->getType()->isVoidTy())
2601 I->replaceAllUsesWith(V: UndefValue::get(T: I->getType()));
2602 if (!isa<PHINode>(Val: I) && isInstructionTriviallyDead(I))
2603 DeadInsts.push_back(Elt: I);
2604 else
2605 I->eraseFromParent();
2606 }
2607 }
2608
2609 llvm::erase_if(C&: DeadInsts, P: [&](WeakTrackingVH I) { return !I; });
2610
2611 LLVM_DEBUG({
2612 dbgs() << "[Attributor] DeadInsts size: " << DeadInsts.size() << "\n";
2613 for (auto &I : DeadInsts)
2614 if (I)
2615 dbgs() << " - " << *I << "\n";
2616 });
2617
2618 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
2619
2620 if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
2621 SmallVector<BasicBlock *, 8> ToBeDeletedBBs;
2622 ToBeDeletedBBs.reserve(N: NumDeadBlocks);
2623 for (BasicBlock *BB : ToBeDeletedBlocks) {
2624 assert(isRunOn(*BB->getParent()) &&
2625 "Cannot delete a block outside the current SCC!");
2626 CGModifiedFunctions.insert(X: BB->getParent());
2627 // Do not delete BBs added during manifests of AAs.
2628 if (ManifestAddedBlocks.contains(Ptr: BB))
2629 continue;
2630 ToBeDeletedBBs.push_back(Elt: BB);
2631 }
2632 // Actually we do not delete the blocks but squash them into a single
2633 // unreachable but untangling branches that jump here is something we need
2634 // to do in a more generic way.
2635 detachDeadBlocks(BBs: ToBeDeletedBBs, Updates: nullptr);
2636 }
2637
2638 identifyDeadInternalFunctions();
2639
2640 // Rewrite the functions as requested during manifest.
2641 ChangeStatus ManifestChange = rewriteFunctionSignatures(ModifiedFns&: CGModifiedFunctions);
2642
2643 for (Function *Fn : CGModifiedFunctions)
2644 if (!ToBeDeletedFunctions.count(key: Fn) && Functions.count(key: Fn))
2645 Configuration.CGUpdater.reanalyzeFunction(Fn&: *Fn);
2646
2647 for (Function *Fn : ToBeDeletedFunctions) {
2648 if (!Functions.count(key: Fn))
2649 continue;
2650 Configuration.CGUpdater.removeFunction(Fn&: *Fn);
2651 }
2652
2653 if (!ToBeChangedUses.empty())
2654 ManifestChange = ChangeStatus::CHANGED;
2655
2656 if (!ToBeChangedToUnreachableInsts.empty())
2657 ManifestChange = ChangeStatus::CHANGED;
2658
2659 if (!ToBeDeletedFunctions.empty())
2660 ManifestChange = ChangeStatus::CHANGED;
2661
2662 if (!ToBeDeletedBlocks.empty())
2663 ManifestChange = ChangeStatus::CHANGED;
2664
2665 if (!ToBeDeletedInsts.empty())
2666 ManifestChange = ChangeStatus::CHANGED;
2667
2668 if (!InvokeWithDeadSuccessor.empty())
2669 ManifestChange = ChangeStatus::CHANGED;
2670
2671 if (!DeadInsts.empty())
2672 ManifestChange = ChangeStatus::CHANGED;
2673
2674 NumFnDeleted += ToBeDeletedFunctions.size();
2675
2676 LLVM_DEBUG(dbgs() << "[Attributor] Deleted " << ToBeDeletedFunctions.size()
2677 << " functions after manifest.\n");
2678
2679#ifdef EXPENSIVE_CHECKS
2680 for (Function *F : Functions) {
2681 if (ToBeDeletedFunctions.count(F))
2682 continue;
2683 assert(!verifyFunction(*F, &errs()) && "Module verification failed!");
2684 }
2685#endif
2686
2687 return ManifestChange;
2688}
2689
2690ChangeStatus Attributor::run() {
2691 TimeTraceScope TimeScope("Attributor::run");
2692 AttributorCallGraph ACallGraph(*this);
2693
2694 if (PrintCallGraph)
2695 ACallGraph.populateAll();
2696
2697 Phase = AttributorPhase::UPDATE;
2698 runTillFixpoint();
2699
2700 // dump graphs on demand
2701 if (DumpDepGraph)
2702 DG.dumpGraph();
2703
2704 if (ViewDepGraph)
2705 DG.viewGraph();
2706
2707 if (PrintDependencies)
2708 DG.print();
2709
2710 Phase = AttributorPhase::MANIFEST;
2711 ChangeStatus ManifestChange = manifestAttributes();
2712
2713 Phase = AttributorPhase::CLEANUP;
2714 ChangeStatus CleanupChange = cleanupIR();
2715
2716 if (PrintCallGraph)
2717 ACallGraph.print();
2718
2719 return ManifestChange | CleanupChange;
2720}
2721
2722ChangeStatus Attributor::updateAA(AbstractAttribute &AA) {
2723 TimeTraceScope TimeScope("updateAA", [&]() {
2724 return AA.getName().str() +
2725 std::to_string(val: AA.getIRPosition().getPositionKind());
2726 });
2727 assert(Phase == AttributorPhase::UPDATE &&
2728 "We can update AA only in the update stage!");
2729
2730 // Use a new dependence vector for this update.
2731 DependenceVector DV;
2732 DependenceStack.push_back(Elt: &DV);
2733
2734 auto &AAState = AA.getState();
2735 ChangeStatus CS = ChangeStatus::UNCHANGED;
2736 bool UsedAssumedInformation = false;
2737 if (!isAssumedDead(AA, FnLivenessAA: nullptr, UsedAssumedInformation,
2738 /* CheckBBLivenessOnly */ true))
2739 CS = AA.update(A&: *this);
2740
2741 if (!AA.isQueryAA() && DV.empty() && !AA.getState().isAtFixpoint()) {
2742 // If the AA did not rely on outside information but changed, we run it
2743 // again to see if it found a fixpoint. Most AAs do but we don't require
2744 // them to. Hence, it might take the AA multiple iterations to get to a
2745 // fixpoint even if it does not rely on outside information, which is fine.
2746 ChangeStatus RerunCS = ChangeStatus::UNCHANGED;
2747 if (CS == ChangeStatus::CHANGED)
2748 RerunCS = AA.update(A&: *this);
2749
2750 // If the attribute did not change during the run or rerun, and it still did
2751 // not query any non-fix information, the state will not change and we can
2752 // indicate that right at this point.
2753 if (RerunCS == ChangeStatus::UNCHANGED && !AA.isQueryAA() && DV.empty())
2754 AAState.indicateOptimisticFixpoint();
2755 }
2756
2757 if (!AAState.isAtFixpoint())
2758 rememberDependences();
2759
2760 // Verify the stack was used properly, that is we pop the dependence vector we
2761 // put there earlier.
2762 DependenceVector *PoppedDV = DependenceStack.pop_back_val();
2763 (void)PoppedDV;
2764 assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!");
2765
2766 return CS;
2767}
2768
2769void Attributor::createShallowWrapper(Function &F) {
2770 assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!");
2771
2772 Module &M = *F.getParent();
2773 LLVMContext &Ctx = M.getContext();
2774 FunctionType *FnTy = F.getFunctionType();
2775
2776 Function *Wrapper =
2777 Function::Create(Ty: FnTy, Linkage: F.getLinkage(), AddrSpace: F.getAddressSpace(), N: F.getName());
2778 F.setName(""); // set the inside function anonymous
2779 M.getFunctionList().insert(where: F.getIterator(), New: Wrapper);
2780
2781 F.setLinkage(GlobalValue::InternalLinkage);
2782
2783 F.replaceAllUsesWith(V: Wrapper);
2784 assert(F.use_empty() && "Uses remained after wrapper was created!");
2785
2786 // Move the COMDAT section to the wrapper.
2787 // TODO: Check if we need to keep it for F as well.
2788 Wrapper->setComdat(F.getComdat());
2789 F.setComdat(nullptr);
2790
2791 // Copy all metadata and attributes but keep them on F as well.
2792 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
2793 F.getAllMetadata(MDs);
2794 for (auto MDIt : MDs)
2795 Wrapper->addMetadata(KindID: MDIt.first, MD&: *MDIt.second);
2796 Wrapper->setAttributes(F.getAttributes());
2797
2798 // Create the call in the wrapper.
2799 BasicBlock *EntryBB = BasicBlock::Create(Context&: Ctx, Name: "entry", Parent: Wrapper);
2800
2801 SmallVector<Value *, 8> Args;
2802 Argument *FArgIt = F.arg_begin();
2803 for (Argument &Arg : Wrapper->args()) {
2804 Args.push_back(Elt: &Arg);
2805 Arg.setName((FArgIt++)->getName());
2806 }
2807
2808 CallInst *CI = CallInst::Create(Func: &F, Args, NameStr: "", InsertBefore: EntryBB);
2809 CI->setTailCall(true);
2810 CI->addFnAttr(Kind: Attribute::NoInline);
2811 ReturnInst::Create(C&: Ctx, retVal: CI->getType()->isVoidTy() ? nullptr : CI, InsertBefore: EntryBB);
2812
2813 NumFnShallowWrappersCreated++;
2814}
2815
2816bool Attributor::isInternalizable(Function &F) {
2817 if (F.isDeclaration() || F.hasLocalLinkage() ||
2818 GlobalValue::isInterposableLinkage(Linkage: F.getLinkage()))
2819 return false;
2820 return true;
2821}
2822
2823Function *Attributor::internalizeFunction(Function &F, bool Force) {
2824 if (!AllowDeepWrapper && !Force)
2825 return nullptr;
2826 if (!isInternalizable(F))
2827 return nullptr;
2828
2829 SmallPtrSet<Function *, 2> FnSet = {&F};
2830 DenseMap<Function *, Function *> InternalizedFns;
2831 internalizeFunctions(FnSet, FnMap&: InternalizedFns);
2832
2833 return InternalizedFns[&F];
2834}
2835
2836bool Attributor::internalizeFunctions(SmallPtrSetImpl<Function *> &FnSet,
2837 DenseMap<Function *, Function *> &FnMap) {
2838 for (Function *F : FnSet)
2839 if (!Attributor::isInternalizable(F&: *F))
2840 return false;
2841
2842 FnMap.clear();
2843 // Generate the internalized version of each function.
2844 for (Function *F : FnSet) {
2845 Module &M = *F->getParent();
2846 FunctionType *FnTy = F->getFunctionType();
2847
2848 // Create a copy of the current function
2849 Function *Copied =
2850 Function::Create(Ty: FnTy, Linkage: F->getLinkage(), AddrSpace: F->getAddressSpace(),
2851 N: F->getName() + ".internalized");
2852 ValueToValueMapTy VMap;
2853 auto *NewFArgIt = Copied->arg_begin();
2854 for (auto &Arg : F->args()) {
2855 auto ArgName = Arg.getName();
2856 NewFArgIt->setName(ArgName);
2857 VMap[&Arg] = &(*NewFArgIt++);
2858 }
2859 SmallVector<ReturnInst *, 8> Returns;
2860
2861 // Copy the body of the original function to the new one
2862 CloneFunctionInto(NewFunc: Copied, OldFunc: F, VMap,
2863 Changes: CloneFunctionChangeType::LocalChangesOnly, Returns);
2864
2865 // Set the linakage and visibility late as CloneFunctionInto has some
2866 // implicit requirements.
2867 Copied->setVisibility(GlobalValue::DefaultVisibility);
2868 Copied->setLinkage(GlobalValue::PrivateLinkage);
2869
2870 // Copy metadata
2871 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
2872 F->getAllMetadata(MDs);
2873 for (auto MDIt : MDs)
2874 if (!Copied->hasMetadata())
2875 Copied->addMetadata(KindID: MDIt.first, MD&: *MDIt.second);
2876
2877 M.getFunctionList().insert(where: F->getIterator(), New: Copied);
2878 Copied->setDSOLocal(true);
2879 FnMap[F] = Copied;
2880 }
2881
2882 // Replace all uses of the old function with the new internalized function
2883 // unless the caller is a function that was just internalized.
2884 for (Function *F : FnSet) {
2885 auto &InternalizedFn = FnMap[F];
2886 auto IsNotInternalized = [&](Use &U) -> bool {
2887 if (auto *CB = dyn_cast<CallBase>(Val: U.getUser()))
2888 return !FnMap.lookup(Val: CB->getCaller());
2889 return false;
2890 };
2891 F->replaceUsesWithIf(New: InternalizedFn, ShouldReplace: IsNotInternalized);
2892 }
2893
2894 return true;
2895}
2896
2897bool Attributor::isValidFunctionSignatureRewrite(
2898 Argument &Arg, ArrayRef<Type *> ReplacementTypes) {
2899
2900 if (!Configuration.RewriteSignatures)
2901 return false;
2902
2903 Function *Fn = Arg.getParent();
2904 auto CallSiteCanBeChanged = [Fn](AbstractCallSite ACS) {
2905 // Forbid the call site to cast the function return type. If we need to
2906 // rewrite these functions we need to re-create a cast for the new call site
2907 // (if the old had uses).
2908 if (!ACS.getCalledFunction() ||
2909 ACS.getInstruction()->getType() !=
2910 ACS.getCalledFunction()->getReturnType())
2911 return false;
2912 if (cast<CallBase>(Val: ACS.getInstruction())->getCalledOperand()->getType() !=
2913 Fn->getType())
2914 return false;
2915 if (ACS.getNumArgOperands() != Fn->arg_size())
2916 return false;
2917 // Forbid must-tail calls for now.
2918 return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall();
2919 };
2920
2921 // Avoid var-arg functions for now.
2922 if (Fn->isVarArg()) {
2923 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n");
2924 return false;
2925 }
2926
2927 // Avoid functions with complicated argument passing semantics.
2928 AttributeList FnAttributeList = Fn->getAttributes();
2929 if (FnAttributeList.hasAttrSomewhere(Kind: Attribute::Nest) ||
2930 FnAttributeList.hasAttrSomewhere(Kind: Attribute::StructRet) ||
2931 FnAttributeList.hasAttrSomewhere(Kind: Attribute::InAlloca) ||
2932 FnAttributeList.hasAttrSomewhere(Kind: Attribute::Preallocated)) {
2933 LLVM_DEBUG(
2934 dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n");
2935 return false;
2936 }
2937
2938 // Avoid callbacks for now.
2939 bool UsedAssumedInformation = false;
2940 if (!checkForAllCallSites(Pred: CallSiteCanBeChanged, Fn: *Fn, RequireAllCallSites: true, QueryingAA: nullptr,
2941 UsedAssumedInformation,
2942 /* CheckPotentiallyDead */ true)) {
2943 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n");
2944 return false;
2945 }
2946
2947 auto InstPred = [](Instruction &I) {
2948 if (auto *CI = dyn_cast<CallInst>(Val: &I))
2949 return !CI->isMustTailCall();
2950 return true;
2951 };
2952
2953 // Forbid must-tail calls for now.
2954 // TODO:
2955 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F: *Fn);
2956 if (!checkForAllInstructionsImpl(A: nullptr, OpcodeInstMap, Pred: InstPred, QueryingAA: nullptr,
2957 LivenessAA: nullptr, Opcodes: {Instruction::Call},
2958 UsedAssumedInformation)) {
2959 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n");
2960 return false;
2961 }
2962
2963 return true;
2964}
2965
2966bool Attributor::registerFunctionSignatureRewrite(
2967 Argument &Arg, ArrayRef<Type *> ReplacementTypes,
2968 ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB,
2969 ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) {
2970 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
2971 << Arg.getParent()->getName() << " with "
2972 << ReplacementTypes.size() << " replacements\n");
2973 assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) &&
2974 "Cannot register an invalid rewrite");
2975
2976 Function *Fn = Arg.getParent();
2977 SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
2978 ArgumentReplacementMap[Fn];
2979 if (ARIs.empty())
2980 ARIs.resize(N: Fn->arg_size());
2981
2982 // If we have a replacement already with less than or equal new arguments,
2983 // ignore this request.
2984 std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()];
2985 if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) {
2986 LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n");
2987 return false;
2988 }
2989
2990 // If we have a replacement already but we like the new one better, delete
2991 // the old.
2992 ARI.reset();
2993
2994 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
2995 << Arg.getParent()->getName() << " with "
2996 << ReplacementTypes.size() << " replacements\n");
2997
2998 // Remember the replacement.
2999 ARI.reset(p: new ArgumentReplacementInfo(*this, Arg, ReplacementTypes,
3000 std::move(CalleeRepairCB),
3001 std::move(ACSRepairCB)));
3002
3003 return true;
3004}
3005
3006bool Attributor::shouldSeedAttribute(AbstractAttribute &AA) {
3007 bool Result = true;
3008#ifndef NDEBUG
3009 if (SeedAllowList.size() != 0)
3010 Result = llvm::is_contained(SeedAllowList, AA.getName());
3011 Function *Fn = AA.getAnchorScope();
3012 if (FunctionSeedAllowList.size() != 0 && Fn)
3013 Result &= llvm::is_contained(FunctionSeedAllowList, Fn->getName());
3014#endif
3015 return Result;
3016}
3017
3018ChangeStatus Attributor::rewriteFunctionSignatures(
3019 SmallSetVector<Function *, 8> &ModifiedFns) {
3020 ChangeStatus Changed = ChangeStatus::UNCHANGED;
3021
3022 for (auto &It : ArgumentReplacementMap) {
3023 Function *OldFn = It.getFirst();
3024
3025 // Deleted functions do not require rewrites.
3026 if (!Functions.count(key: OldFn) || ToBeDeletedFunctions.count(key: OldFn))
3027 continue;
3028
3029 const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
3030 It.getSecond();
3031 assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!");
3032
3033 SmallVector<Type *, 16> NewArgumentTypes;
3034 SmallVector<AttributeSet, 16> NewArgumentAttributes;
3035
3036 // Collect replacement argument types and copy over existing attributes.
3037 AttributeList OldFnAttributeList = OldFn->getAttributes();
3038 for (Argument &Arg : OldFn->args()) {
3039 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3040 ARIs[Arg.getArgNo()]) {
3041 NewArgumentTypes.append(in_start: ARI->ReplacementTypes.begin(),
3042 in_end: ARI->ReplacementTypes.end());
3043 NewArgumentAttributes.append(NumInputs: ARI->getNumReplacementArgs(),
3044 Elt: AttributeSet());
3045 } else {
3046 NewArgumentTypes.push_back(Elt: Arg.getType());
3047 NewArgumentAttributes.push_back(
3048 Elt: OldFnAttributeList.getParamAttrs(ArgNo: Arg.getArgNo()));
3049 }
3050 }
3051
3052 uint64_t LargestVectorWidth = 0;
3053 for (auto *I : NewArgumentTypes)
3054 if (auto *VT = dyn_cast<llvm::VectorType>(Val: I))
3055 LargestVectorWidth =
3056 std::max(a: LargestVectorWidth,
3057 b: VT->getPrimitiveSizeInBits().getKnownMinValue());
3058
3059 FunctionType *OldFnTy = OldFn->getFunctionType();
3060 Type *RetTy = OldFnTy->getReturnType();
3061
3062 // Construct the new function type using the new arguments types.
3063 FunctionType *NewFnTy =
3064 FunctionType::get(Result: RetTy, Params: NewArgumentTypes, isVarArg: OldFnTy->isVarArg());
3065
3066 LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName()
3067 << "' from " << *OldFn->getFunctionType() << " to "
3068 << *NewFnTy << "\n");
3069
3070 // Create the new function body and insert it into the module.
3071 Function *NewFn = Function::Create(Ty: NewFnTy, Linkage: OldFn->getLinkage(),
3072 AddrSpace: OldFn->getAddressSpace(), N: "");
3073 Functions.insert(X: NewFn);
3074 OldFn->getParent()->getFunctionList().insert(where: OldFn->getIterator(), New: NewFn);
3075 NewFn->takeName(V: OldFn);
3076 NewFn->copyAttributesFrom(Src: OldFn);
3077
3078 // Patch the pointer to LLVM function in debug info descriptor.
3079 NewFn->setSubprogram(OldFn->getSubprogram());
3080 OldFn->setSubprogram(nullptr);
3081
3082 // Recompute the parameter attributes list based on the new arguments for
3083 // the function.
3084 LLVMContext &Ctx = OldFn->getContext();
3085 NewFn->setAttributes(AttributeList::get(
3086 C&: Ctx, FnAttrs: OldFnAttributeList.getFnAttrs(), RetAttrs: OldFnAttributeList.getRetAttrs(),
3087 ArgAttrs: NewArgumentAttributes));
3088 AttributeFuncs::updateMinLegalVectorWidthAttr(Fn&: *NewFn, Width: LargestVectorWidth);
3089
3090 // Remove argmem from the memory effects if we have no more pointer
3091 // arguments, or they are readnone.
3092 MemoryEffects ME = NewFn->getMemoryEffects();
3093 int ArgNo = -1;
3094 if (ME.doesAccessArgPointees() && all_of(Range&: NewArgumentTypes, P: [&](Type *T) {
3095 ++ArgNo;
3096 return !T->isPtrOrPtrVectorTy() ||
3097 NewFn->hasParamAttribute(ArgNo, Kind: Attribute::ReadNone);
3098 })) {
3099 NewFn->setMemoryEffects(ME - MemoryEffects::argMemOnly());
3100 }
3101
3102 // Since we have now created the new function, splice the body of the old
3103 // function right into the new function, leaving the old rotting hulk of the
3104 // function empty.
3105 NewFn->splice(ToIt: NewFn->begin(), FromF: OldFn);
3106
3107 // Set of all "call-like" instructions that invoke the old function mapped
3108 // to their new replacements.
3109 SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs;
3110
3111 // Callback to create a new "call-like" instruction for a given one.
3112 auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) {
3113 CallBase *OldCB = cast<CallBase>(Val: ACS.getInstruction());
3114 const AttributeList &OldCallAttributeList = OldCB->getAttributes();
3115
3116 // Collect the new argument operands for the replacement call site.
3117 SmallVector<Value *, 16> NewArgOperands;
3118 SmallVector<AttributeSet, 16> NewArgOperandAttributes;
3119 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) {
3120 unsigned NewFirstArgNum = NewArgOperands.size();
3121 (void)NewFirstArgNum; // only used inside assert.
3122 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3123 ARIs[OldArgNum]) {
3124 if (ARI->ACSRepairCB)
3125 ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
3126 assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
3127 NewArgOperands.size() &&
3128 "ACS repair callback did not provide as many operand as new "
3129 "types were registered!");
3130 // TODO: Exose the attribute set to the ACS repair callback
3131 NewArgOperandAttributes.append(NumInputs: ARI->ReplacementTypes.size(),
3132 Elt: AttributeSet());
3133 } else {
3134 NewArgOperands.push_back(Elt: ACS.getCallArgOperand(ArgNo: OldArgNum));
3135 NewArgOperandAttributes.push_back(
3136 Elt: OldCallAttributeList.getParamAttrs(ArgNo: OldArgNum));
3137 }
3138 }
3139
3140 assert(NewArgOperands.size() == NewArgOperandAttributes.size() &&
3141 "Mismatch # argument operands vs. # argument operand attributes!");
3142 assert(NewArgOperands.size() == NewFn->arg_size() &&
3143 "Mismatch # argument operands vs. # function arguments!");
3144
3145 SmallVector<OperandBundleDef, 4> OperandBundleDefs;
3146 OldCB->getOperandBundlesAsDefs(Defs&: OperandBundleDefs);
3147
3148 // Create a new call or invoke instruction to replace the old one.
3149 CallBase *NewCB;
3150 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: OldCB)) {
3151 NewCB = InvokeInst::Create(Func: NewFn, IfNormal: II->getNormalDest(),
3152 IfException: II->getUnwindDest(), Args: NewArgOperands,
3153 Bundles: OperandBundleDefs, NameStr: "", InsertBefore: OldCB->getIterator());
3154 } else {
3155 auto *NewCI = CallInst::Create(Func: NewFn, Args: NewArgOperands, Bundles: OperandBundleDefs,
3156 NameStr: "", InsertBefore: OldCB->getIterator());
3157 NewCI->setTailCallKind(cast<CallInst>(Val: OldCB)->getTailCallKind());
3158 NewCB = NewCI;
3159 }
3160
3161 // Copy over various properties and the new attributes.
3162 NewCB->copyProfileAndDebugMetadata(SrcInst: *OldCB);
3163 NewCB->setCallingConv(OldCB->getCallingConv());
3164 NewCB->takeName(V: OldCB);
3165 NewCB->setAttributes(AttributeList::get(
3166 C&: Ctx, FnAttrs: OldCallAttributeList.getFnAttrs(),
3167 RetAttrs: OldCallAttributeList.getRetAttrs(), ArgAttrs: NewArgOperandAttributes));
3168
3169 AttributeFuncs::updateMinLegalVectorWidthAttr(Fn&: *NewCB->getCaller(),
3170 Width: LargestVectorWidth);
3171
3172 CallSitePairs.push_back(Elt: {OldCB, NewCB});
3173 return true;
3174 };
3175
3176 // Use the CallSiteReplacementCreator to create replacement call sites.
3177 bool UsedAssumedInformation = false;
3178 bool Success = checkForAllCallSites(Pred: CallSiteReplacementCreator, Fn: *OldFn,
3179 RequireAllCallSites: true, QueryingAA: nullptr, UsedAssumedInformation,
3180 /* CheckPotentiallyDead */ true);
3181 (void)Success;
3182 assert(Success && "Assumed call site replacement to succeed!");
3183
3184 // Rewire the arguments.
3185 Argument *OldFnArgIt = OldFn->arg_begin();
3186 Argument *NewFnArgIt = NewFn->arg_begin();
3187 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size();
3188 ++OldArgNum, ++OldFnArgIt) {
3189 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3190 ARIs[OldArgNum]) {
3191 if (ARI->CalleeRepairCB)
3192 ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
3193 if (ARI->ReplacementTypes.empty())
3194 OldFnArgIt->replaceAllUsesWith(
3195 V: PoisonValue::get(T: OldFnArgIt->getType()));
3196 NewFnArgIt += ARI->ReplacementTypes.size();
3197 } else {
3198 NewFnArgIt->takeName(V: &*OldFnArgIt);
3199 OldFnArgIt->replaceAllUsesWith(V: &*NewFnArgIt);
3200 ++NewFnArgIt;
3201 }
3202 }
3203
3204 // Eliminate the instructions *after* we visited all of them.
3205 for (auto &CallSitePair : CallSitePairs) {
3206 CallBase &OldCB = *CallSitePair.first;
3207 CallBase &NewCB = *CallSitePair.second;
3208 assert(OldCB.getType() == NewCB.getType() &&
3209 "Cannot handle call sites with different types!");
3210 ModifiedFns.insert(X: OldCB.getFunction());
3211 OldCB.replaceAllUsesWith(V: &NewCB);
3212 OldCB.eraseFromParent();
3213 }
3214
3215 // Replace the function in the call graph (if any).
3216 Configuration.CGUpdater.replaceFunctionWith(OldFn&: *OldFn, NewFn&: *NewFn);
3217
3218 // If the old function was modified and needed to be reanalyzed, the new one
3219 // does now.
3220 if (ModifiedFns.remove(X: OldFn))
3221 ModifiedFns.insert(X: NewFn);
3222
3223 Changed = ChangeStatus::CHANGED;
3224 }
3225
3226 return Changed;
3227}
3228
3229void InformationCache::initializeInformationCache(const Function &CF,
3230 FunctionInfo &FI) {
3231 // As we do not modify the function here we can remove the const
3232 // withouth breaking implicit assumptions. At the end of the day, we could
3233 // initialize the cache eagerly which would look the same to the users.
3234 Function &F = const_cast<Function &>(CF);
3235
3236 FI.IsKernel = F.hasFnAttribute(Kind: "kernel");
3237
3238 // Walk all instructions to find interesting instructions that might be
3239 // queried by abstract attributes during their initialization or update.
3240 // This has to happen before we create attributes.
3241
3242 DenseMap<const Value *, std::optional<short>> AssumeUsesMap;
3243
3244 // Add \p V to the assume uses map which track the number of uses outside of
3245 // "visited" assumes. If no outside uses are left the value is added to the
3246 // assume only use vector.
3247 auto AddToAssumeUsesMap = [&](const Value &V) -> void {
3248 SmallVector<const Instruction *> Worklist;
3249 if (auto *I = dyn_cast<Instruction>(Val: &V))
3250 Worklist.push_back(Elt: I);
3251 while (!Worklist.empty()) {
3252 const Instruction *I = Worklist.pop_back_val();
3253 std::optional<short> &NumUses = AssumeUsesMap[I];
3254 if (!NumUses)
3255 NumUses = I->getNumUses();
3256 NumUses = *NumUses - /* this assume */ 1;
3257 if (*NumUses != 0)
3258 continue;
3259 AssumeOnlyValues.insert(X: I);
3260 for (const Value *Op : I->operands())
3261 if (auto *OpI = dyn_cast<Instruction>(Val: Op))
3262 Worklist.push_back(Elt: OpI);
3263 }
3264 };
3265
3266 for (Instruction &I : instructions(F: &F)) {
3267 bool IsInterestingOpcode = false;
3268
3269 // To allow easy access to all instructions in a function with a given
3270 // opcode we store them in the InfoCache. As not all opcodes are interesting
3271 // to concrete attributes we only cache the ones that are as identified in
3272 // the following switch.
3273 // Note: There are no concrete attributes now so this is initially empty.
3274 switch (I.getOpcode()) {
3275 default:
3276 assert(!isa<CallBase>(&I) &&
3277 "New call base instruction type needs to be known in the "
3278 "Attributor.");
3279 break;
3280 case Instruction::Call:
3281 // Calls are interesting on their own, additionally:
3282 // For `llvm.assume` calls we also fill the KnowledgeMap as we find them.
3283 // For `must-tail` calls we remember the caller and callee.
3284 if (auto *Assume = dyn_cast<AssumeInst>(Val: &I)) {
3285 AssumeOnlyValues.insert(X: Assume);
3286 fillMapFromAssume(Assume&: *Assume, Result&: KnowledgeMap);
3287 AddToAssumeUsesMap(*Assume->getArgOperand(i: 0));
3288 } else if (cast<CallInst>(Val&: I).isMustTailCall()) {
3289 FI.ContainsMustTailCall = true;
3290 if (auto *Callee = dyn_cast_if_present<Function>(
3291 Val: cast<CallInst>(Val&: I).getCalledOperand()))
3292 getFunctionInfo(F: *Callee).CalledViaMustTail = true;
3293 }
3294 [[fallthrough]];
3295 case Instruction::CallBr:
3296 case Instruction::Invoke:
3297 case Instruction::CleanupRet:
3298 case Instruction::CatchSwitch:
3299 case Instruction::AtomicRMW:
3300 case Instruction::AtomicCmpXchg:
3301 case Instruction::UncondBr:
3302 case Instruction::CondBr:
3303 case Instruction::Resume:
3304 case Instruction::Ret:
3305 case Instruction::Load:
3306 // The alignment of a pointer is interesting for loads.
3307 case Instruction::Store:
3308 // The alignment of a pointer is interesting for stores.
3309 case Instruction::Alloca:
3310 case Instruction::AddrSpaceCast:
3311 IsInterestingOpcode = true;
3312 }
3313 if (IsInterestingOpcode) {
3314 auto *&Insts = FI.OpcodeInstMap[I.getOpcode()];
3315 if (!Insts)
3316 Insts = new (Allocator) InstructionVectorTy();
3317 Insts->push_back(Elt: &I);
3318 }
3319 if (I.mayReadOrWriteMemory())
3320 FI.RWInsts.push_back(Elt: &I);
3321 }
3322
3323 if (F.hasFnAttribute(Kind: Attribute::AlwaysInline) &&
3324 isInlineViable(Callee&: F).isSuccess())
3325 InlineableFunctions.insert(Ptr: &F);
3326}
3327
3328InformationCache::FunctionInfo::~FunctionInfo() {
3329 // The instruction vectors are allocated using a BumpPtrAllocator, we need to
3330 // manually destroy them.
3331 for (auto &It : OpcodeInstMap)
3332 It.getSecond()->~InstructionVectorTy();
3333}
3334
3335ArrayRef<Function *>
3336InformationCache::getIndirectlyCallableFunctions(Attributor &A) const {
3337 assert(A.isClosedWorldModule() && "Cannot see all indirect callees!");
3338 return IndirectlyCallableFunctions;
3339}
3340
3341std::optional<unsigned> InformationCache::getFlatAddressSpace() const {
3342 if (IsTargetGPU())
3343 return 0;
3344 return std::nullopt;
3345}
3346
3347void Attributor::recordDependence(const AbstractAttribute &FromAA,
3348 const AbstractAttribute &ToAA,
3349 DepClassTy DepClass) {
3350 if (DepClass == DepClassTy::NONE)
3351 return;
3352 // If we are outside of an update, thus before the actual fixpoint iteration
3353 // started (= when we create AAs), we do not track dependences because we will
3354 // put all AAs into the initial worklist anyway.
3355 if (DependenceStack.empty())
3356 return;
3357 if (FromAA.getState().isAtFixpoint())
3358 return;
3359 DependenceStack.back()->push_back(Elt: {.FromAA: &FromAA, .ToAA: &ToAA, .DepClass: DepClass});
3360}
3361
3362void Attributor::rememberDependences() {
3363 assert(!DependenceStack.empty() && "No dependences to remember!");
3364
3365 for (DepInfo &DI : *DependenceStack.back()) {
3366 assert((DI.DepClass == DepClassTy::REQUIRED ||
3367 DI.DepClass == DepClassTy::OPTIONAL) &&
3368 "Expected required or optional dependence (1 bit)!");
3369 auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps;
3370 DepAAs.insert(X: AbstractAttribute::DepTy(
3371 const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass)));
3372 }
3373}
3374
3375template <Attribute::AttrKind AK, typename AAType>
3376void Attributor::checkAndQueryIRAttr(const IRPosition &IRP, AttributeSet Attrs,
3377 bool SkipHasAttrCheck) {
3378 bool IsKnown;
3379 if (SkipHasAttrCheck || !Attrs.hasAttribute(Kind: AK))
3380 if (!Configuration.Allowed || Configuration.Allowed->count(V: &AAType::ID))
3381 if (!AA::hasAssumedIRAttr<AK>(*this, nullptr, IRP, DepClassTy::NONE,
3382 IsKnown))
3383 getOrCreateAAFor<AAType>(IRP);
3384}
3385
3386void Attributor::identifyDefaultAbstractAttributes(Function &F) {
3387 assert(!F.isDeclaration());
3388
3389 if (!VisitedFunctions.insert(V: &F).second)
3390 return;
3391
3392 // In non-module runs we need to look at the call sites of a function to
3393 // determine if it is part of a must-tail call edge. This will influence what
3394 // attributes we can derive.
3395 InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F);
3396 if (!isModulePass() && !FI.CalledViaMustTail) {
3397 for (const Use &U : F.uses())
3398 if (const auto *CB = dyn_cast<CallBase>(Val: U.getUser()))
3399 if (CB->isCallee(U: &U) && CB->isMustTailCall())
3400 FI.CalledViaMustTail = true;
3401 }
3402
3403 IRPosition FPos = IRPosition::function(F);
3404 bool IsIPOAmendable = isFunctionIPOAmendable(F);
3405 auto Attrs = F.getAttributes();
3406 auto FnAttrs = Attrs.getFnAttrs();
3407
3408 // Check for dead BasicBlocks in every function.
3409 // We need dead instruction detection because we do not want to deal with
3410 // broken IR in which SSA rules do not apply.
3411 getOrCreateAAFor<AAIsDead>(IRP: FPos);
3412
3413 // Every function might contain instructions that cause "undefined
3414 // behavior".
3415 getOrCreateAAFor<AAUndefinedBehavior>(IRP: FPos);
3416
3417 // Every function might be applicable for Heap-To-Stack conversion.
3418 if (EnableHeapToStack)
3419 getOrCreateAAFor<AAHeapToStack>(IRP: FPos);
3420
3421 // Every function might be "must-progress".
3422 checkAndQueryIRAttr<Attribute::MustProgress, AAMustProgress>(IRP: FPos, Attrs: FnAttrs);
3423
3424 // Every function might be "no-free".
3425 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(IRP: FPos, Attrs: FnAttrs);
3426
3427 // Every function might be "will-return".
3428 checkAndQueryIRAttr<Attribute::WillReturn, AAWillReturn>(IRP: FPos, Attrs: FnAttrs);
3429
3430 // Every function might be marked "nosync"
3431 checkAndQueryIRAttr<Attribute::NoSync, AANoSync>(IRP: FPos, Attrs: FnAttrs);
3432
3433 // Everything that is visible from the outside (=function, argument, return
3434 // positions), cannot be changed if the function is not IPO amendable. We can
3435 // however analyse the code inside.
3436 if (IsIPOAmendable) {
3437
3438 // Every function can be nounwind.
3439 checkAndQueryIRAttr<Attribute::NoUnwind, AANoUnwind>(IRP: FPos, Attrs: FnAttrs);
3440
3441 // Every function might be "no-return".
3442 checkAndQueryIRAttr<Attribute::NoReturn, AANoReturn>(IRP: FPos, Attrs: FnAttrs);
3443
3444 // Every function might be "no-recurse".
3445 checkAndQueryIRAttr<Attribute::NoRecurse, AANoRecurse>(IRP: FPos, Attrs: FnAttrs);
3446
3447 // Every function can be "non-convergent".
3448 if (Attrs.hasFnAttr(Kind: Attribute::Convergent))
3449 getOrCreateAAFor<AANonConvergent>(IRP: FPos);
3450
3451 // Every function might be "readnone/readonly/writeonly/...".
3452 getOrCreateAAFor<AAMemoryBehavior>(IRP: FPos);
3453
3454 // Every function can be "readnone/argmemonly/inaccessiblememonly/...".
3455 getOrCreateAAFor<AAMemoryLocation>(IRP: FPos);
3456
3457 // Every function can track active assumptions.
3458 getOrCreateAAFor<AAAssumptionInfo>(IRP: FPos);
3459
3460 // If we're not using a dynamic mode for float, there's nothing worthwhile
3461 // to infer. This misses the edge case denormal-fp-math="dynamic" and
3462 // denormal-fp-math-f32=something, but that likely has no real world use.
3463 DenormalMode Mode = F.getDenormalMode(FPType: APFloat::IEEEsingle());
3464 if (Mode.Input == DenormalMode::Dynamic ||
3465 Mode.Output == DenormalMode::Dynamic)
3466 getOrCreateAAFor<AADenormalFPMath>(IRP: FPos);
3467
3468 // Return attributes are only appropriate if the return type is non void.
3469 Type *ReturnType = F.getReturnType();
3470 if (!ReturnType->isVoidTy()) {
3471 IRPosition RetPos = IRPosition::returned(F);
3472 AttributeSet RetAttrs = Attrs.getRetAttrs();
3473
3474 // Every returned value might be dead.
3475 getOrCreateAAFor<AAIsDead>(IRP: RetPos);
3476
3477 // Every function might be simplified.
3478 bool UsedAssumedInformation = false;
3479 getAssumedSimplified(IRP: RetPos, AA: nullptr, UsedAssumedInformation,
3480 S: AA::Intraprocedural);
3481
3482 // Every returned value might be marked noundef.
3483 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(IRP: RetPos, Attrs: RetAttrs);
3484
3485 if (ReturnType->isPointerTy()) {
3486
3487 // Every function with pointer return type might be marked align.
3488 getOrCreateAAFor<AAAlign>(IRP: RetPos);
3489
3490 // Every function with pointer return type might be marked nonnull.
3491 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(IRP: RetPos, Attrs: RetAttrs);
3492
3493 // Every function with pointer return type might be marked noalias.
3494 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(IRP: RetPos, Attrs: RetAttrs);
3495
3496 // Every function with pointer return type might be marked
3497 // dereferenceable.
3498 getOrCreateAAFor<AADereferenceable>(IRP: RetPos);
3499 } else if (AttributeFuncs::isNoFPClassCompatibleType(Ty: ReturnType)) {
3500 getOrCreateAAFor<AANoFPClass>(IRP: RetPos);
3501 }
3502 }
3503 }
3504
3505 for (Argument &Arg : F.args()) {
3506 IRPosition ArgPos = IRPosition::argument(Arg);
3507 auto ArgNo = Arg.getArgNo();
3508 AttributeSet ArgAttrs = Attrs.getParamAttrs(ArgNo);
3509
3510 if (!IsIPOAmendable) {
3511 if (Arg.getType()->isPointerTy())
3512 // Every argument with pointer type might be marked nofree.
3513 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(IRP: ArgPos, Attrs: ArgAttrs);
3514 continue;
3515 }
3516
3517 // Every argument might be simplified. We have to go through the
3518 // Attributor interface though as outside AAs can register custom
3519 // simplification callbacks.
3520 bool UsedAssumedInformation = false;
3521 getAssumedSimplified(IRP: ArgPos, /* AA */ nullptr, UsedAssumedInformation,
3522 S: AA::Intraprocedural);
3523
3524 // Every argument might be dead.
3525 getOrCreateAAFor<AAIsDead>(IRP: ArgPos);
3526
3527 // Every argument might be marked noundef.
3528 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(IRP: ArgPos, Attrs: ArgAttrs);
3529
3530 if (Arg.getType()->isPointerTy()) {
3531 // Every argument with pointer type might be marked nonnull.
3532 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(IRP: ArgPos, Attrs: ArgAttrs);
3533
3534 // Every argument with pointer type might be marked noalias.
3535 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(IRP: ArgPos, Attrs: ArgAttrs);
3536
3537 // Every argument with pointer type might be marked dereferenceable.
3538 getOrCreateAAFor<AADereferenceable>(IRP: ArgPos);
3539
3540 // Every argument with pointer type might be marked align.
3541 getOrCreateAAFor<AAAlign>(IRP: ArgPos);
3542
3543 // Every argument with pointer type might be marked nocapture.
3544 checkAndQueryIRAttr<Attribute::Captures, AANoCapture>(
3545 IRP: ArgPos, Attrs: ArgAttrs, /*SkipHasAttrCheck=*/true);
3546
3547 // Every argument with pointer type might be marked
3548 // "readnone/readonly/writeonly/..."
3549 getOrCreateAAFor<AAMemoryBehavior>(IRP: ArgPos);
3550
3551 // Every argument with pointer type might be marked nofree.
3552 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(IRP: ArgPos, Attrs: ArgAttrs);
3553
3554 // Every argument with pointer type might be privatizable (or
3555 // promotable)
3556 getOrCreateAAFor<AAPrivatizablePtr>(IRP: ArgPos);
3557 } else if (AttributeFuncs::isNoFPClassCompatibleType(Ty: Arg.getType())) {
3558 getOrCreateAAFor<AANoFPClass>(IRP: ArgPos);
3559 }
3560 }
3561
3562 auto CallSitePred = [&](Instruction &I) -> bool {
3563 auto &CB = cast<CallBase>(Val&: I);
3564 IRPosition CBInstPos = IRPosition::inst(I: CB);
3565 IRPosition CBFnPos = IRPosition::callsite_function(CB);
3566
3567 // Call sites might be dead if they do not have side effects and no live
3568 // users. The return value might be dead if there are no live users.
3569 getOrCreateAAFor<AAIsDead>(IRP: CBInstPos);
3570
3571 Function *Callee = dyn_cast_if_present<Function>(Val: CB.getCalledOperand());
3572 // TODO: Even if the callee is not known now we might be able to simplify
3573 // the call/callee.
3574 if (!Callee) {
3575 getOrCreateAAFor<AAIndirectCallInfo>(IRP: CBFnPos);
3576 return true;
3577 }
3578
3579 // Every call site can track active assumptions.
3580 getOrCreateAAFor<AAAssumptionInfo>(IRP: CBFnPos);
3581
3582 // Skip declarations except if annotations on their call sites were
3583 // explicitly requested.
3584 if (!AnnotateDeclarationCallSites && Callee->isDeclaration() &&
3585 !Callee->hasMetadata(KindID: LLVMContext::MD_callback))
3586 return true;
3587
3588 if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) {
3589 IRPosition CBRetPos = IRPosition::callsite_returned(CB);
3590 bool UsedAssumedInformation = false;
3591 getAssumedSimplified(IRP: CBRetPos, AA: nullptr, UsedAssumedInformation,
3592 S: AA::Intraprocedural);
3593
3594 if (AttributeFuncs::isNoFPClassCompatibleType(Ty: Callee->getReturnType()))
3595 getOrCreateAAFor<AANoFPClass>(IRP: CBInstPos);
3596 }
3597
3598 const AttributeList &CBAttrs = CBFnPos.getAttrList();
3599 for (int I = 0, E = CB.arg_size(); I < E; ++I) {
3600
3601 IRPosition CBArgPos = IRPosition::callsite_argument(CB, ArgNo: I);
3602 AttributeSet CBArgAttrs = CBAttrs.getParamAttrs(ArgNo: I);
3603
3604 // Every call site argument might be dead.
3605 getOrCreateAAFor<AAIsDead>(IRP: CBArgPos);
3606
3607 // Call site argument might be simplified. We have to go through the
3608 // Attributor interface though as outside AAs can register custom
3609 // simplification callbacks.
3610 bool UsedAssumedInformation = false;
3611 getAssumedSimplified(IRP: CBArgPos, /* AA */ nullptr, UsedAssumedInformation,
3612 S: AA::Intraprocedural);
3613
3614 // Every call site argument might be marked "noundef".
3615 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(IRP: CBArgPos, Attrs: CBArgAttrs);
3616
3617 Type *ArgTy = CB.getArgOperand(i: I)->getType();
3618
3619 if (!ArgTy->isPointerTy()) {
3620 if (AttributeFuncs::isNoFPClassCompatibleType(Ty: ArgTy))
3621 getOrCreateAAFor<AANoFPClass>(IRP: CBArgPos);
3622
3623 continue;
3624 }
3625
3626 // Call site argument attribute "non-null".
3627 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(IRP: CBArgPos, Attrs: CBArgAttrs);
3628
3629 // Call site argument attribute "captures(none)".
3630 checkAndQueryIRAttr<Attribute::Captures, AANoCapture>(
3631 IRP: CBArgPos, Attrs: CBArgAttrs, /*SkipHasAttrCheck=*/true);
3632
3633 // Call site argument attribute "no-alias".
3634 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(IRP: CBArgPos, Attrs: CBArgAttrs);
3635
3636 // Call site argument attribute "dereferenceable".
3637 getOrCreateAAFor<AADereferenceable>(IRP: CBArgPos);
3638
3639 // Call site argument attribute "align".
3640 getOrCreateAAFor<AAAlign>(IRP: CBArgPos);
3641
3642 // Call site argument attribute
3643 // "readnone/readonly/writeonly/..."
3644 if (!CBAttrs.hasParamAttr(ArgNo: I, Kind: Attribute::ReadNone))
3645 getOrCreateAAFor<AAMemoryBehavior>(IRP: CBArgPos);
3646
3647 // Call site argument attribute "nofree".
3648 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(IRP: CBArgPos, Attrs: CBArgAttrs);
3649 }
3650 return true;
3651 };
3652
3653 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
3654 [[maybe_unused]] bool Success;
3655 bool UsedAssumedInformation = false;
3656 Success = checkForAllInstructionsImpl(
3657 A: nullptr, OpcodeInstMap, Pred: CallSitePred, QueryingAA: nullptr, LivenessAA: nullptr,
3658 Opcodes: {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
3659 (unsigned)Instruction::Call},
3660 UsedAssumedInformation);
3661 assert(Success && "Expected the check call to be successful!");
3662
3663 auto LoadStorePred = [&](Instruction &I) -> bool {
3664 if (auto *LI = dyn_cast<LoadInst>(Val: &I)) {
3665 getOrCreateAAFor<AAAlign>(IRP: IRPosition::value(V: *LI->getPointerOperand()));
3666 if (SimplifyAllLoads)
3667 getAssumedSimplified(IRP: IRPosition::value(V: I), AA: nullptr,
3668 UsedAssumedInformation, S: AA::Intraprocedural);
3669 getOrCreateAAFor<AAInvariantLoadPointer>(
3670 IRP: IRPosition::value(V: *LI->getPointerOperand()));
3671 getOrCreateAAFor<AAAddressSpace>(
3672 IRP: IRPosition::value(V: *LI->getPointerOperand()));
3673 } else {
3674 auto &SI = cast<StoreInst>(Val&: I);
3675 getOrCreateAAFor<AAIsDead>(IRP: IRPosition::inst(I));
3676 getAssumedSimplified(IRP: IRPosition::value(V: *SI.getValueOperand()), AA: nullptr,
3677 UsedAssumedInformation, S: AA::Intraprocedural);
3678 getOrCreateAAFor<AAAlign>(IRP: IRPosition::value(V: *SI.getPointerOperand()));
3679 getOrCreateAAFor<AAAddressSpace>(
3680 IRP: IRPosition::value(V: *SI.getPointerOperand()));
3681 }
3682 return true;
3683 };
3684 Success = checkForAllInstructionsImpl(
3685 A: nullptr, OpcodeInstMap, Pred: LoadStorePred, QueryingAA: nullptr, LivenessAA: nullptr,
3686 Opcodes: {(unsigned)Instruction::Load, (unsigned)Instruction::Store},
3687 UsedAssumedInformation);
3688 assert(Success && "Expected the check call to be successful!");
3689
3690 // AllocaInstPredicate
3691 auto AAAllocationInfoPred = [&](Instruction &I) -> bool {
3692 getOrCreateAAFor<AAAllocationInfo>(IRP: IRPosition::value(V: I));
3693 return true;
3694 };
3695
3696 Success = checkForAllInstructionsImpl(
3697 A: nullptr, OpcodeInstMap, Pred: AAAllocationInfoPred, QueryingAA: nullptr, LivenessAA: nullptr,
3698 Opcodes: {(unsigned)Instruction::Alloca}, UsedAssumedInformation);
3699 assert(Success && "Expected the check call to be successful!");
3700}
3701
3702bool Attributor::isClosedWorldModule() const {
3703 if (CloseWorldAssumption.getNumOccurrences())
3704 return CloseWorldAssumption;
3705 return isModulePass() && Configuration.IsClosedWorldModule;
3706}
3707
3708/// Helpers to ease debugging through output streams and print calls.
3709///
3710///{
3711raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
3712 return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
3713}
3714
3715raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) {
3716 switch (AP) {
3717 case IRPosition::IRP_INVALID:
3718 return OS << "inv";
3719 case IRPosition::IRP_FLOAT:
3720 return OS << "flt";
3721 case IRPosition::IRP_RETURNED:
3722 return OS << "fn_ret";
3723 case IRPosition::IRP_CALL_SITE_RETURNED:
3724 return OS << "cs_ret";
3725 case IRPosition::IRP_FUNCTION:
3726 return OS << "fn";
3727 case IRPosition::IRP_CALL_SITE:
3728 return OS << "cs";
3729 case IRPosition::IRP_ARGUMENT:
3730 return OS << "arg";
3731 case IRPosition::IRP_CALL_SITE_ARGUMENT:
3732 return OS << "cs_arg";
3733 }
3734 llvm_unreachable("Unknown attribute position!");
3735}
3736
3737raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) {
3738 const Value &AV = Pos.getAssociatedValue();
3739 OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " ["
3740 << Pos.getAnchorValue().getName() << "@" << Pos.getCallSiteArgNo() << "]";
3741
3742 if (Pos.hasCallBaseContext())
3743 OS << "[cb_context:" << *Pos.getCallBaseContext() << "]";
3744 return OS << "}";
3745}
3746
3747raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) {
3748 OS << "range-state(" << S.getBitWidth() << ")<";
3749 S.getKnown().print(OS);
3750 OS << " / ";
3751 S.getAssumed().print(OS);
3752 OS << ">";
3753
3754 return OS << static_cast<const AbstractState &>(S);
3755}
3756
3757raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
3758 return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
3759}
3760
3761raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
3762 AA.print(OS);
3763 return OS;
3764}
3765
3766raw_ostream &llvm::operator<<(raw_ostream &OS,
3767 const PotentialConstantIntValuesState &S) {
3768 OS << "set-state(< {";
3769 if (!S.isValidState())
3770 OS << "full-set";
3771 else {
3772 for (const auto &It : S.getAssumedSet())
3773 OS << It << ", ";
3774 if (S.undefIsContained())
3775 OS << "undef ";
3776 }
3777 OS << "} >)";
3778
3779 return OS;
3780}
3781
3782raw_ostream &llvm::operator<<(raw_ostream &OS,
3783 const PotentialLLVMValuesState &S) {
3784 OS << "set-state(< {";
3785 if (!S.isValidState())
3786 OS << "full-set";
3787 else {
3788 for (const auto &It : S.getAssumedSet()) {
3789 if (auto *F = dyn_cast<Function>(Val: It.first.getValue()))
3790 OS << "@" << F->getName() << "[" << int(It.second) << "], ";
3791 else
3792 OS << *It.first.getValue() << "[" << int(It.second) << "], ";
3793 }
3794 if (S.undefIsContained())
3795 OS << "undef ";
3796 }
3797 OS << "} >)";
3798
3799 return OS;
3800}
3801
3802void AbstractAttribute::print(Attributor *A, raw_ostream &OS) const {
3803 OS << "[";
3804 OS << getName();
3805 OS << "] for CtxI ";
3806
3807 if (auto *I = getCtxI()) {
3808 OS << "'";
3809 I->print(O&: OS);
3810 OS << "'";
3811 } else
3812 OS << "<<null inst>>";
3813
3814 OS << " at position " << getIRPosition() << " with state " << getAsStr(A)
3815 << '\n';
3816}
3817
3818void AbstractAttribute::printWithDeps(raw_ostream &OS) const {
3819 print(OS);
3820
3821 for (const auto &DepAA : Deps) {
3822 auto *AA = DepAA.getPointer();
3823 OS << " updates ";
3824 AA->print(OS);
3825 }
3826
3827 OS << '\n';
3828}
3829
3830raw_ostream &llvm::operator<<(raw_ostream &OS,
3831 const AAPointerInfo::Access &Acc) {
3832 OS << " [" << Acc.getKind() << "] " << *Acc.getRemoteInst();
3833 if (Acc.getLocalInst() != Acc.getRemoteInst())
3834 OS << " via " << *Acc.getLocalInst();
3835 if (Acc.getContent()) {
3836 if (*Acc.getContent())
3837 OS << " [" << **Acc.getContent() << "]";
3838 else
3839 OS << " [ <unknown> ]";
3840 }
3841 return OS;
3842}
3843///}
3844
3845/// ----------------------------------------------------------------------------
3846/// Pass (Manager) Boilerplate
3847/// ----------------------------------------------------------------------------
3848
3849static bool runAttributorOnFunctions(InformationCache &InfoCache,
3850 SetVector<Function *> &Functions,
3851 CallGraphUpdater &CGUpdater,
3852 FunctionAnalysisManager &FAM,
3853 bool DeleteFns, bool IsModulePass) {
3854 if (Functions.empty())
3855 return false;
3856
3857 LLVM_DEBUG({
3858 dbgs() << "[Attributor] Run on module with " << Functions.size()
3859 << " functions:\n";
3860 for (Function *Fn : Functions)
3861 dbgs() << " - " << Fn->getName() << "\n";
3862 });
3863
3864 // Create an Attributor and initially empty information cache that is filled
3865 // while we identify default attribute opportunities.
3866 AttributorConfig AC(CGUpdater);
3867 AC.IsModulePass = IsModulePass;
3868 AC.DeleteFns = DeleteFns;
3869 auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
3870 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(IR&: *F);
3871 };
3872 AC.OREGetter = OREGetter;
3873 AC.PassName = DEBUG_TYPE;
3874
3875 /// Tracking callback for specialization of indirect calls.
3876 DenseMap<CallBase *, std::unique_ptr<SmallPtrSet<Function *, 8>>>
3877 IndirectCalleeTrackingMap;
3878 if (MaxSpecializationPerCB.getNumOccurrences()) {
3879 AC.IndirectCalleeSpecializationCallback =
3880 [&](Attributor &, const AbstractAttribute &AA, CallBase &CB,
3881 Function &Callee, unsigned) {
3882 if (MaxSpecializationPerCB == 0)
3883 return false;
3884 auto &Set = IndirectCalleeTrackingMap[&CB];
3885 if (!Set)
3886 Set = std::make_unique<SmallPtrSet<Function *, 8>>();
3887 if (Set->size() >= MaxSpecializationPerCB)
3888 return Set->contains(Ptr: &Callee);
3889 Set->insert(Ptr: &Callee);
3890 return true;
3891 };
3892 }
3893
3894 Attributor A(Functions, InfoCache, AC);
3895
3896 // Create shallow wrappers for all functions that are not IPO amendable
3897 if (AllowShallowWrappers)
3898 for (Function *F : Functions)
3899 if (!A.isFunctionIPOAmendable(F: *F))
3900 Attributor::createShallowWrapper(F&: *F);
3901
3902 // Internalize non-exact functions
3903 // TODO: for now we eagerly internalize functions without calculating the
3904 // cost, we need a cost interface to determine whether internalizing
3905 // a function is "beneficial"
3906 if (AllowDeepWrapper) {
3907 unsigned FunSize = Functions.size();
3908 for (unsigned u = 0; u < FunSize; u++) {
3909 Function *F = Functions[u];
3910 if (!F->isDeclaration() && !F->isDefinitionExact() && !F->use_empty() &&
3911 !GlobalValue::isInterposableLinkage(Linkage: F->getLinkage())) {
3912 Function *NewF = Attributor::internalizeFunction(F&: *F);
3913 assert(NewF && "Could not internalize function.");
3914 Functions.insert(X: NewF);
3915
3916 // Update call graph
3917 CGUpdater.replaceFunctionWith(OldFn&: *F, NewFn&: *NewF);
3918 for (const Use &U : NewF->uses())
3919 if (CallBase *CB = dyn_cast<CallBase>(Val: U.getUser())) {
3920 auto *CallerF = CB->getCaller();
3921 CGUpdater.reanalyzeFunction(Fn&: *CallerF);
3922 }
3923 }
3924 }
3925 }
3926
3927 for (Function *F : Functions) {
3928 if (F->isDeclaration())
3929 continue;
3930
3931 if (F->hasExactDefinition())
3932 NumFnWithExactDefinition++;
3933 else
3934 NumFnWithoutExactDefinition++;
3935
3936 // We look at internal functions only on-demand but if any use is not a
3937 // direct call or outside the current set of analyzed functions, we have
3938 // to do it eagerly.
3939 if (F->hasLocalLinkage()) {
3940 if (llvm::all_of(Range: F->uses(), P: [&Functions](const Use &U) {
3941 const auto *CB = dyn_cast<CallBase>(Val: U.getUser());
3942 return CB && CB->isCallee(U: &U) &&
3943 Functions.count(key: const_cast<Function *>(CB->getCaller()));
3944 }))
3945 continue;
3946 }
3947
3948 // Populate the Attributor with abstract attribute opportunities in the
3949 // function and the information cache with IR information.
3950 A.identifyDefaultAbstractAttributes(F&: *F);
3951 }
3952
3953 ChangeStatus Changed = A.run();
3954
3955 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
3956 << " functions, result: " << Changed << ".\n");
3957 return Changed == ChangeStatus::CHANGED;
3958}
3959
3960static bool runAttributorLightOnFunctions(InformationCache &InfoCache,
3961 SetVector<Function *> &Functions,
3962 CallGraphUpdater &CGUpdater,
3963 FunctionAnalysisManager &FAM,
3964 bool IsModulePass) {
3965 if (Functions.empty())
3966 return false;
3967
3968 LLVM_DEBUG({
3969 dbgs() << "[AttributorLight] Run on module with " << Functions.size()
3970 << " functions:\n";
3971 for (Function *Fn : Functions)
3972 dbgs() << " - " << Fn->getName() << "\n";
3973 });
3974
3975 // Create an Attributor and initially empty information cache that is filled
3976 // while we identify default attribute opportunities.
3977 AttributorConfig AC(CGUpdater);
3978 AC.IsModulePass = IsModulePass;
3979 AC.DeleteFns = false;
3980 DenseSet<const char *> Allowed(
3981 {&AAWillReturn::ID, &AANoUnwind::ID, &AANoRecurse::ID, &AANoSync::ID,
3982 &AANoFree::ID, &AANoReturn::ID, &AAMemoryLocation::ID,
3983 &AAMemoryBehavior::ID, &AAUnderlyingObjects::ID, &AANoCapture::ID,
3984 &AAInterFnReachability::ID, &AAIntraFnReachability::ID, &AACallEdges::ID,
3985 &AANoFPClass::ID, &AAMustProgress::ID, &AANonNull::ID,
3986 &AADenormalFPMath::ID});
3987 AC.Allowed = &Allowed;
3988 AC.UseLiveness = false;
3989
3990 Attributor A(Functions, InfoCache, AC);
3991
3992 for (Function *F : Functions) {
3993 if (F->isDeclaration())
3994 continue;
3995
3996 if (F->hasExactDefinition())
3997 NumFnWithExactDefinition++;
3998 else
3999 NumFnWithoutExactDefinition++;
4000
4001 // We look at internal functions only on-demand but if any use is not a
4002 // direct call or outside the current set of analyzed functions, we have
4003 // to do it eagerly.
4004 if (AC.UseLiveness && F->hasLocalLinkage()) {
4005 if (llvm::all_of(Range: F->uses(), P: [&Functions](const Use &U) {
4006 const auto *CB = dyn_cast<CallBase>(Val: U.getUser());
4007 return CB && CB->isCallee(U: &U) &&
4008 Functions.count(key: const_cast<Function *>(CB->getCaller()));
4009 }))
4010 continue;
4011 }
4012
4013 // Populate the Attributor with abstract attribute opportunities in the
4014 // function and the information cache with IR information.
4015 A.identifyDefaultAbstractAttributes(F&: *F);
4016 }
4017
4018 ChangeStatus Changed = A.run();
4019
4020 if (Changed == ChangeStatus::CHANGED) {
4021 // Invalidate analyses for modified functions so that we don't have to
4022 // invalidate all analyses for all functions in this SCC.
4023 PreservedAnalyses FuncPA;
4024 // We haven't changed the CFG for modified functions.
4025 FuncPA.preserveSet<CFGAnalyses>();
4026 for (Function *Changed : A.getModifiedFunctions()) {
4027 FAM.invalidate(IR&: *Changed, PA: FuncPA);
4028 // Also invalidate any direct callers of changed functions since analyses
4029 // may care about attributes of direct callees. For example, MemorySSA
4030 // cares about whether or not a call's callee modifies memory and queries
4031 // that through function attributes.
4032 for (auto *U : Changed->users()) {
4033 if (auto *Call = dyn_cast<CallBase>(Val: U)) {
4034 if (Call->getCalledFunction() == Changed)
4035 FAM.invalidate(IR&: *Call->getFunction(), PA: FuncPA);
4036 }
4037 }
4038 }
4039 }
4040 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
4041 << " functions, result: " << Changed << ".\n");
4042 return Changed == ChangeStatus::CHANGED;
4043}
4044
4045void AADepGraph::viewGraph() { llvm::ViewGraph(G: this, Name: "Dependency Graph"); }
4046
4047void AADepGraph::dumpGraph() {
4048 static std::atomic<int> CallTimes;
4049 std::string Prefix;
4050
4051 if (!DepGraphDotFileNamePrefix.empty())
4052 Prefix = DepGraphDotFileNamePrefix;
4053 else
4054 Prefix = "dep_graph";
4055 std::string Filename =
4056 Prefix + "_" + std::to_string(val: CallTimes.load()) + ".dot";
4057
4058 outs() << "Dependency graph dump to " << Filename << ".\n";
4059
4060 std::error_code EC;
4061
4062 raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF);
4063 if (!EC)
4064 llvm::WriteGraph(O&: File, G: this);
4065
4066 CallTimes++;
4067}
4068
4069void AADepGraph::print() {
4070 for (auto DepAA : SyntheticRoot.Deps)
4071 cast<AbstractAttribute>(Val: DepAA.getPointer())->printWithDeps(OS&: outs());
4072}
4073
4074PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
4075 FunctionAnalysisManager &FAM =
4076 AM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
4077 AnalysisGetter AG(FAM);
4078
4079 SetVector<Function *> Functions;
4080 Functions.reserve(Size: M.size());
4081 for (Function &F : M)
4082 Functions.insert(X: &F);
4083
4084 CallGraphUpdater CGUpdater;
4085 BumpPtrAllocator Allocator;
4086 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
4087 if (runAttributorOnFunctions(InfoCache, Functions, CGUpdater, FAM,
4088 /* DeleteFns */ true, /* IsModulePass */ true)) {
4089 // FIXME: Think about passes we will preserve and add them here.
4090 return PreservedAnalyses::none();
4091 }
4092 return PreservedAnalyses::all();
4093}
4094
4095PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C,
4096 CGSCCAnalysisManager &AM,
4097 LazyCallGraph &CG,
4098 CGSCCUpdateResult &UR) {
4099 FunctionAnalysisManager &FAM =
4100 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(IR&: C, ExtraArgs&: CG).getManager();
4101 AnalysisGetter AG(FAM);
4102
4103 SetVector<Function *> Functions;
4104 Functions.reserve(Size: C.size());
4105 for (LazyCallGraph::Node &N : C)
4106 Functions.insert(X: &N.getFunction());
4107
4108 if (Functions.empty())
4109 return PreservedAnalyses::all();
4110
4111 Module &M = *Functions.back()->getParent();
4112 CallGraphUpdater CGUpdater;
4113 CGUpdater.initialize(LCG&: CG, SCC&: C, AM, UR);
4114 BumpPtrAllocator Allocator;
4115 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
4116 if (runAttributorOnFunctions(InfoCache, Functions, CGUpdater, FAM,
4117 /* DeleteFns */ false,
4118 /* IsModulePass */ false)) {
4119 // FIXME: Think about passes we will preserve and add them here.
4120 PreservedAnalyses PA;
4121 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
4122 return PA;
4123 }
4124 return PreservedAnalyses::all();
4125}
4126
4127PreservedAnalyses AttributorLightPass::run(Module &M,
4128 ModuleAnalysisManager &AM) {
4129 FunctionAnalysisManager &FAM =
4130 AM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
4131 AnalysisGetter AG(FAM, /* CachedOnly */ true);
4132
4133 SetVector<Function *> Functions;
4134 Functions.reserve(Size: M.size());
4135 for (Function &F : M)
4136 Functions.insert(X: &F);
4137
4138 CallGraphUpdater CGUpdater;
4139 BumpPtrAllocator Allocator;
4140 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
4141 if (runAttributorLightOnFunctions(InfoCache, Functions, CGUpdater, FAM,
4142 /* IsModulePass */ true)) {
4143 PreservedAnalyses PA;
4144 // We have not added or removed functions.
4145 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
4146 // We already invalidated all relevant function analyses above.
4147 PA.preserveSet<AllAnalysesOn<Function>>();
4148 return PA;
4149 }
4150 return PreservedAnalyses::all();
4151}
4152
4153PreservedAnalyses AttributorLightCGSCCPass::run(LazyCallGraph::SCC &C,
4154 CGSCCAnalysisManager &AM,
4155 LazyCallGraph &CG,
4156 CGSCCUpdateResult &UR) {
4157 FunctionAnalysisManager &FAM =
4158 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(IR&: C, ExtraArgs&: CG).getManager();
4159 AnalysisGetter AG(FAM);
4160
4161 SetVector<Function *> Functions;
4162 for (LazyCallGraph::Node &N : C)
4163 Functions.insert(X: &N.getFunction());
4164
4165 if (Functions.empty())
4166 return PreservedAnalyses::all();
4167
4168 Module &M = *Functions.back()->getParent();
4169 CallGraphUpdater CGUpdater;
4170 CGUpdater.initialize(LCG&: CG, SCC&: C, AM, UR);
4171 BumpPtrAllocator Allocator;
4172 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
4173 if (runAttributorLightOnFunctions(InfoCache, Functions, CGUpdater, FAM,
4174 /* IsModulePass */ false)) {
4175 PreservedAnalyses PA;
4176 // We have not added or removed functions.
4177 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
4178 // We already invalidated all relevant function analyses above.
4179 PA.preserveSet<AllAnalysesOn<Function>>();
4180 return PA;
4181 }
4182 return PreservedAnalyses::all();
4183}
4184namespace llvm {
4185
4186template <> struct GraphTraits<AADepGraphNode *> {
4187 using NodeRef = AADepGraphNode *;
4188 using DepTy = PointerIntPair<AADepGraphNode *, 1>;
4189 using EdgeRef = PointerIntPair<AADepGraphNode *, 1>;
4190
4191 static NodeRef getEntryNode(AADepGraphNode *DGN) { return DGN; }
4192 static NodeRef DepGetVal(const DepTy &DT) { return DT.getPointer(); }
4193
4194 using ChildIteratorType =
4195 mapped_iterator<AADepGraphNode::DepSetTy::iterator, decltype(&DepGetVal)>;
4196 using ChildEdgeIteratorType = AADepGraphNode::DepSetTy::iterator;
4197
4198 static ChildIteratorType child_begin(NodeRef N) { return N->child_begin(); }
4199
4200 static ChildIteratorType child_end(NodeRef N) { return N->child_end(); }
4201};
4202
4203template <>
4204struct GraphTraits<AADepGraph *> : public GraphTraits<AADepGraphNode *> {
4205 static NodeRef getEntryNode(AADepGraph *DG) { return DG->GetEntryNode(); }
4206
4207 using nodes_iterator =
4208 mapped_iterator<AADepGraphNode::DepSetTy::iterator, decltype(&DepGetVal)>;
4209
4210 static nodes_iterator nodes_begin(AADepGraph *DG) { return DG->begin(); }
4211
4212 static nodes_iterator nodes_end(AADepGraph *DG) { return DG->end(); }
4213};
4214
4215template <> struct DOTGraphTraits<AADepGraph *> : public DefaultDOTGraphTraits {
4216 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
4217
4218 static std::string getNodeLabel(const AADepGraphNode *Node,
4219 const AADepGraph *DG) {
4220 std::string AAString;
4221 raw_string_ostream O(AAString);
4222 Node->print(OS&: O);
4223 return AAString;
4224 }
4225};
4226
4227} // end namespace llvm
4228