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