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 // The returned position of the callee does not describe the call if
1373 // the call uses a different return type.
1374 bool SameType = Callee->getReturnType() == CB->getType();
1375 if (SameType)
1376 IRPositions.emplace_back(IRPosition::returned(*Callee));
1377 IRPositions.emplace_back(IRPosition::function(*Callee));
1378 for (const Argument &Arg : Callee->args())
1379 if (SameType && Arg.hasReturnedAttr()) {
1380 IRPositions.emplace_back(
1381 IRPosition::callsite_argument(*CB, Arg.getArgNo()));
1382 IRPositions.emplace_back(
1383 IRPosition::value(*CB->getArgOperand(Arg.getArgNo())));
1384 IRPositions.emplace_back(IRPosition::argument(Arg));
1385 }
1386 }
1387 }
1388 IRPositions.emplace_back(IRPosition::callsite_function(*CB));
1389 return;
1391 assert(CB && "Expected call site!");
1392 // TODO: We need to look at the operand bundles similar to the redirection
1393 // in CallBase.
1394 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
1395 auto *Callee = dyn_cast_if_present<Function>(CB->getCalledOperand());
1396 if (Callee) {
1397 if (Argument *Arg = IRP.getAssociatedArgument())
1398 IRPositions.emplace_back(IRPosition::argument(*Arg));
1399 IRPositions.emplace_back(IRPosition::function(*Callee));
1400 }
1401 }
1402 IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue()));
1403 return;
1404 }
1405 }
1406}
1407
1408void IRPosition::verify() {
1409#ifdef EXPENSIVE_CHECKS
1410 switch (getPositionKind()) {
1411 case IRP_INVALID:
1412 assert((CBContext == nullptr) &&
1413 "Invalid position must not have CallBaseContext!");
1414 assert(!Enc.getOpaqueValue() &&
1415 "Expected a nullptr for an invalid position!");
1416 return;
1417 case IRP_FLOAT:
1419 "Expected specialized kind for argument values!");
1420 return;
1421 case IRP_RETURNED:
1422 assert(isa<Function>(getAsValuePtr()) &&
1423 "Expected function for a 'returned' position!");
1424 assert(getAsValuePtr() == &getAssociatedValue() &&
1425 "Associated value mismatch!");
1426 return;
1428 assert((CBContext == nullptr) &&
1429 "'call site returned' position must not have CallBaseContext!");
1430 assert((isa<CallBase>(getAsValuePtr())) &&
1431 "Expected call base for 'call site returned' position!");
1432 assert(getAsValuePtr() == &getAssociatedValue() &&
1433 "Associated value mismatch!");
1434 return;
1435 case IRP_CALL_SITE:
1436 assert((CBContext == nullptr) &&
1437 "'call site function' position must not have CallBaseContext!");
1438 assert((isa<CallBase>(getAsValuePtr())) &&
1439 "Expected call base for 'call site function' position!");
1440 assert(getAsValuePtr() == &getAssociatedValue() &&
1441 "Associated value mismatch!");
1442 return;
1443 case IRP_FUNCTION:
1444 assert(isa<Function>(getAsValuePtr()) &&
1445 "Expected function for a 'function' position!");
1446 assert(getAsValuePtr() == &getAssociatedValue() &&
1447 "Associated value mismatch!");
1448 return;
1449 case IRP_ARGUMENT:
1450 assert(isa<Argument>(getAsValuePtr()) &&
1451 "Expected argument for a 'argument' position!");
1452 assert(getAsValuePtr() == &getAssociatedValue() &&
1453 "Associated value mismatch!");
1454 return;
1456 assert((CBContext == nullptr) &&
1457 "'call site argument' position must not have CallBaseContext!");
1458 Use *U = getAsUsePtr();
1459 (void)U; // Silence unused variable warning.
1460 assert(U && "Expected use for a 'call site argument' position!");
1461 assert(isa<CallBase>(U->getUser()) &&
1462 "Expected call base user for a 'call site argument' position!");
1463 assert(cast<CallBase>(U->getUser())->isArgOperand(U) &&
1464 "Expected call base argument operand for a 'call site argument' "
1465 "position");
1466 assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) ==
1467 unsigned(getCallSiteArgNo()) &&
1468 "Argument number mismatch!");
1469 assert(U->get() == &getAssociatedValue() && "Associated value mismatch!");
1470 return;
1471 }
1472 }
1473#endif
1474}
1475
1476std::optional<Constant *>
1478 const AbstractAttribute &AA,
1479 bool &UsedAssumedInformation) {
1480 // First check all callbacks provided by outside AAs. If any of them returns
1481 // a non-null value that is different from the associated value, or
1482 // std::nullopt, we assume it's simplified.
1483 for (auto &CB : SimplificationCallbacks.lookup(IRP)) {
1484 std::optional<Value *> SimplifiedV = CB(IRP, &AA, UsedAssumedInformation);
1485 if (!SimplifiedV)
1486 return std::nullopt;
1487 if (isa_and_nonnull<Constant>(*SimplifiedV))
1488 return cast<Constant>(*SimplifiedV);
1489 return nullptr;
1490 }
1491 if (auto *C = dyn_cast<Constant>(&IRP.getAssociatedValue()))
1492 return C;
1496 UsedAssumedInformation)) {
1497 if (Values.empty())
1498 return std::nullopt;
1499 if (auto *C = dyn_cast_or_null<Constant>(
1501 return C;
1502 }
1503 return nullptr;
1504}
1505
1507 const IRPosition &IRP, const AbstractAttribute *AA,
1508 bool &UsedAssumedInformation, AA::ValueScope S) {
1509 // First check all callbacks provided by outside AAs. If any of them returns
1510 // a non-null value that is different from the associated value, or
1511 // std::nullopt, we assume it's simplified.
1512 for (auto &CB : SimplificationCallbacks.lookup(IRP))
1513 return CB(IRP, AA, UsedAssumedInformation);
1514
1516 if (!getAssumedSimplifiedValues(IRP, AA, Values, S, UsedAssumedInformation))
1517 return &IRP.getAssociatedValue();
1518 if (Values.empty())
1519 return std::nullopt;
1520 if (AA)
1521 if (Value *V = AAPotentialValues::getSingleValue(*this, *AA, IRP, Values))
1522 return V;
1525 return nullptr;
1526 return &IRP.getAssociatedValue();
1527}
1528
1530 const IRPosition &InitialIRP, const AbstractAttribute *AA,
1532 bool &UsedAssumedInformation, bool RecurseForSelectAndPHI) {
1535 Worklist.push_back(InitialIRP);
1536 while (!Worklist.empty()) {
1537 const IRPosition &IRP = Worklist.pop_back_val();
1538
1539 // First check all callbacks provided by outside AAs. If any of them returns
1540 // a non-null value that is different from the associated value, or
1541 // std::nullopt, we assume it's simplified.
1542 int NV = Values.size();
1543 const auto &SimplificationCBs = SimplificationCallbacks.lookup(IRP);
1544 for (const auto &CB : SimplificationCBs) {
1545 std::optional<Value *> CBResult = CB(IRP, AA, UsedAssumedInformation);
1546 if (!CBResult.has_value())
1547 continue;
1548 Value *V = *CBResult;
1549 if (!V)
1550 return false;
1553 Values.push_back(AA::ValueAndContext{*V, nullptr});
1554 else
1555 return false;
1556 }
1557 if (SimplificationCBs.empty()) {
1558 // If no high-level/outside simplification occurred, use
1559 // AAPotentialValues.
1560 const auto *PotentialValuesAA =
1562 if (PotentialValuesAA &&
1563 PotentialValuesAA->getAssumedSimplifiedValues(*this, Values, S)) {
1564 UsedAssumedInformation |= !PotentialValuesAA->isAtFixpoint();
1565 } else if (IRP.getPositionKind() != IRPosition::IRP_RETURNED) {
1566 Values.push_back({IRP.getAssociatedValue(), IRP.getCtxI()});
1567 } else {
1568 // TODO: We could visit all returns and add the operands.
1569 return false;
1570 }
1571 }
1572
1573 if (!RecurseForSelectAndPHI)
1574 break;
1575
1576 for (int I = NV, E = Values.size(); I < E; ++I) {
1577 Value *V = Values[I].getValue();
1578 if (!isa<PHINode>(V) && !isa<SelectInst>(V))
1579 continue;
1580 if (!Seen.insert(V).second)
1581 continue;
1582 // Move the last element to this slot.
1583 Values[I] = Values[E - 1];
1584 // Eliminate the last slot, adjust the indices.
1585 Values.pop_back();
1586 --E;
1587 --I;
1588 // Add a new value (select or phi) to the worklist.
1589 Worklist.push_back(IRPosition::value(*V));
1590 }
1591 }
1592 return true;
1593}
1594
1596 std::optional<Value *> V, CallBase &CB, const AbstractAttribute &AA,
1597 bool &UsedAssumedInformation) {
1598 if (!V)
1599 return V;
1600 if (*V == nullptr || isa<Constant>(*V))
1601 return V;
1602 if (auto *Arg = dyn_cast<Argument>(*V))
1603 if (CB.getCalledOperand() == Arg->getParent() &&
1604 CB.arg_size() > Arg->getArgNo())
1605 if (!Arg->hasPointeeInMemoryValueAttr())
1606 return getAssumedSimplified(
1607 IRPosition::callsite_argument(CB, Arg->getArgNo()), AA,
1608 UsedAssumedInformation, AA::Intraprocedural);
1609 return nullptr;
1610}
1611
1613 // The abstract attributes are allocated via the BumpPtrAllocator Allocator,
1614 // thus we cannot delete them. We can, and want to, destruct them though.
1615 for (auto &It : AAMap) {
1616 AbstractAttribute *AA = It.getSecond();
1617 AA->~AbstractAttribute();
1618 }
1619}
1620
1622 const AAIsDead *FnLivenessAA,
1623 bool &UsedAssumedInformation,
1624 bool CheckBBLivenessOnly, DepClassTy DepClass) {
1625 if (!Configuration.UseLiveness)
1626 return false;
1627 const IRPosition &IRP = AA.getIRPosition();
1628 if (!Functions.count(IRP.getAnchorScope()))
1629 return false;
1630 return isAssumedDead(IRP, &AA, FnLivenessAA, UsedAssumedInformation,
1631 CheckBBLivenessOnly, DepClass);
1632}
1633
1635 const AbstractAttribute *QueryingAA,
1636 const AAIsDead *FnLivenessAA,
1637 bool &UsedAssumedInformation,
1638 bool CheckBBLivenessOnly, DepClassTy DepClass) {
1639 if (!Configuration.UseLiveness)
1640 return false;
1641 Instruction *UserI = dyn_cast<Instruction>(U.getUser());
1642 if (!UserI)
1643 return isAssumedDead(IRPosition::value(*U.get()), QueryingAA, FnLivenessAA,
1644 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1645
1646 if (auto *CB = dyn_cast<CallBase>(UserI)) {
1647 // For call site argument uses we can check if the argument is
1648 // unused/dead.
1649 if (CB->isArgOperand(&U)) {
1650 const IRPosition &CSArgPos =
1651 IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
1652 return isAssumedDead(CSArgPos, QueryingAA, FnLivenessAA,
1653 UsedAssumedInformation, CheckBBLivenessOnly,
1654 DepClass);
1655 }
1656 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) {
1657 const IRPosition &RetPos = IRPosition::returned(*RI->getFunction());
1658 return isAssumedDead(RetPos, QueryingAA, FnLivenessAA,
1659 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1660 } else if (PHINode *PHI = dyn_cast<PHINode>(UserI)) {
1661 BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
1662 return isAssumedDead(*IncomingBB->getTerminator(), QueryingAA, FnLivenessAA,
1663 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1664 } else if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
1665 if (!CheckBBLivenessOnly && SI->getPointerOperand() != U.get()) {
1666 const IRPosition IRP = IRPosition::inst(*SI);
1667 const AAIsDead *IsDeadAA =
1669 if (IsDeadAA && IsDeadAA->isRemovableStore()) {
1670 if (QueryingAA)
1671 recordDependence(*IsDeadAA, *QueryingAA, DepClass);
1672 if (!IsDeadAA->isKnown(AAIsDead::IS_REMOVABLE))
1673 UsedAssumedInformation = true;
1674 return true;
1675 }
1676 }
1677 }
1678
1679 return isAssumedDead(IRPosition::inst(*UserI), QueryingAA, FnLivenessAA,
1680 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1681}
1682
1684 const AbstractAttribute *QueryingAA,
1685 const AAIsDead *FnLivenessAA,
1686 bool &UsedAssumedInformation,
1687 bool CheckBBLivenessOnly, DepClassTy DepClass,
1688 bool CheckForDeadStore) {
1689 if (!Configuration.UseLiveness)
1690 return false;
1691 const IRPosition::CallBaseContext *CBCtx =
1692 QueryingAA ? QueryingAA->getCallBaseContext() : nullptr;
1693
1694 if (ManifestAddedBlocks.contains(I.getParent()))
1695 return false;
1696
1697 const Function &F = *I.getFunction();
1698 if (!FnLivenessAA || FnLivenessAA->getAnchorScope() != &F)
1699 FnLivenessAA = getOrCreateAAFor<AAIsDead>(IRPosition::function(F, CBCtx),
1700 QueryingAA, DepClassTy::NONE);
1701
1702 // Don't use recursive reasoning.
1703 if (!FnLivenessAA || QueryingAA == FnLivenessAA)
1704 return false;
1705
1706 // If we have a context instruction and a liveness AA we use it.
1707 if (CheckBBLivenessOnly ? FnLivenessAA->isAssumedDead(I.getParent())
1708 : FnLivenessAA->isAssumedDead(&I)) {
1709 if (QueryingAA)
1710 recordDependence(*FnLivenessAA, *QueryingAA, DepClass);
1711 if (!FnLivenessAA->isKnownDead(&I))
1712 UsedAssumedInformation = true;
1713 return true;
1714 }
1715
1716 if (CheckBBLivenessOnly)
1717 return false;
1718
1719 const IRPosition IRP = IRPosition::inst(I, CBCtx);
1720 const AAIsDead *IsDeadAA =
1722
1723 // Don't use recursive reasoning.
1724 if (!IsDeadAA || QueryingAA == IsDeadAA)
1725 return false;
1726
1727 if (IsDeadAA->isAssumedDead()) {
1728 if (QueryingAA)
1729 recordDependence(*IsDeadAA, *QueryingAA, DepClass);
1730 if (!IsDeadAA->isKnownDead())
1731 UsedAssumedInformation = true;
1732 return true;
1733 }
1734
1735 if (CheckForDeadStore && isa<StoreInst>(I) && IsDeadAA->isRemovableStore()) {
1736 if (QueryingAA)
1737 recordDependence(*IsDeadAA, *QueryingAA, DepClass);
1738 if (!IsDeadAA->isKnownDead())
1739 UsedAssumedInformation = true;
1740 return true;
1741 }
1742
1743 return false;
1744}
1745
1747 const AbstractAttribute *QueryingAA,
1748 const AAIsDead *FnLivenessAA,
1749 bool &UsedAssumedInformation,
1750 bool CheckBBLivenessOnly, DepClassTy DepClass) {
1751 if (!Configuration.UseLiveness)
1752 return false;
1753 // Don't check liveness for constants, e.g. functions, used as (floating)
1754 // values since the context instruction and such is here meaningless.
1757 return false;
1758 }
1759
1760 Instruction *CtxI = IRP.getCtxI();
1761 if (CtxI &&
1762 isAssumedDead(*CtxI, QueryingAA, FnLivenessAA, UsedAssumedInformation,
1763 /* CheckBBLivenessOnly */ true,
1764 CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL))
1765 return true;
1766
1767 if (CheckBBLivenessOnly)
1768 return false;
1769
1770 // If we haven't succeeded we query the specific liveness info for the IRP.
1771 const AAIsDead *IsDeadAA;
1773 IsDeadAA = getOrCreateAAFor<AAIsDead>(
1775 QueryingAA, DepClassTy::NONE);
1776 else
1777 IsDeadAA = getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClassTy::NONE);
1778
1779 // Don't use recursive reasoning.
1780 if (!IsDeadAA || QueryingAA == IsDeadAA)
1781 return false;
1782
1783 if (IsDeadAA->isAssumedDead()) {
1784 if (QueryingAA)
1785 recordDependence(*IsDeadAA, *QueryingAA, DepClass);
1786 if (!IsDeadAA->isKnownDead())
1787 UsedAssumedInformation = true;
1788 return true;
1789 }
1790
1791 return false;
1792}
1793
1795 const AbstractAttribute *QueryingAA,
1796 const AAIsDead *FnLivenessAA,
1797 DepClassTy DepClass) {
1798 if (!Configuration.UseLiveness)
1799 return false;
1800 const Function &F = *BB.getParent();
1801 if (!FnLivenessAA || FnLivenessAA->getAnchorScope() != &F)
1803 QueryingAA, DepClassTy::NONE);
1804
1805 // Don't use recursive reasoning.
1806 if (!FnLivenessAA || QueryingAA == FnLivenessAA)
1807 return false;
1808
1809 if (FnLivenessAA->isAssumedDead(&BB)) {
1810 if (QueryingAA)
1811 recordDependence(*FnLivenessAA, *QueryingAA, DepClass);
1812 return true;
1813 }
1814
1815 return false;
1816}
1817
1820 const AbstractAttribute &QueryingAA, const CallBase &CB) {
1821 if (const Function *Callee = dyn_cast<Function>(CB.getCalledOperand()))
1822 return Pred(Callee);
1823
1824 const auto *CallEdgesAA = getAAFor<AACallEdges>(
1826 if (!CallEdgesAA || CallEdgesAA->hasUnknownCallee())
1827 return false;
1828
1829 const auto &Callees = CallEdgesAA->getOptimisticEdges();
1830 return Pred(Callees.getArrayRef());
1831}
1832
1833bool canMarkAsVisited(const User *Usr) {
1834 return isa<PHINode>(Usr) || !isa<Instruction>(Usr);
1835}
1836
1838 function_ref<bool(const Use &, bool &)> Pred,
1839 const AbstractAttribute &QueryingAA, const Value &V,
1840 bool CheckBBLivenessOnly, DepClassTy LivenessDepClass,
1841 bool IgnoreDroppableUses,
1842 function_ref<bool(const Use &OldU, const Use &NewU)> EquivalentUseCB) {
1843
1844 // Check virtual uses first.
1845 for (VirtualUseCallbackTy &CB : VirtualUseCallbacks.lookup(&V))
1846 if (!CB(*this, &QueryingAA))
1847 return false;
1848
1849 if (isa<ConstantData>(V))
1850 return false;
1851
1852 // Check the trivial case first as it catches void values.
1853 if (V.use_empty())
1854 return true;
1855
1856 const IRPosition &IRP = QueryingAA.getIRPosition();
1859
1860 auto AddUsers = [&](const Value &V, const Use *OldUse) {
1861 for (const Use &UU : V.uses()) {
1862 if (OldUse && EquivalentUseCB && !EquivalentUseCB(*OldUse, UU)) {
1863 LLVM_DEBUG(dbgs() << "[Attributor] Potential copy was "
1864 "rejected by the equivalence call back: "
1865 << *UU << "!\n");
1866 return false;
1867 }
1868
1869 Worklist.push_back(&UU);
1870 }
1871 return true;
1872 };
1873
1874 AddUsers(V, /* OldUse */ nullptr);
1875
1876 LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size()
1877 << " initial uses to check\n");
1878
1879 const Function *ScopeFn = IRP.getAnchorScope();
1880 const auto *LivenessAA =
1881 ScopeFn ? getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*ScopeFn),
1883 : nullptr;
1884
1885 while (!Worklist.empty()) {
1886 const Use *U = Worklist.pop_back_val();
1887 if (canMarkAsVisited(U->getUser()) && !Visited.insert(U).second)
1888 continue;
1890 if (auto *Fn = dyn_cast<Function>(U->getUser()))
1891 dbgs() << "[Attributor] Check use: " << **U << " in " << Fn->getName()
1892 << "\n";
1893 else
1894 dbgs() << "[Attributor] Check use: " << **U << " in " << *U->getUser()
1895 << "\n";
1896 });
1897 bool UsedAssumedInformation = false;
1898 if (isAssumedDead(*U, &QueryingAA, LivenessAA, UsedAssumedInformation,
1899 CheckBBLivenessOnly, LivenessDepClass)) {
1901 dbgs() << "[Attributor] Dead use, skip!\n");
1902 continue;
1903 }
1904 if (IgnoreDroppableUses && U->getUser()->isDroppable()) {
1906 dbgs() << "[Attributor] Droppable user, skip!\n");
1907 continue;
1908 }
1909
1910 if (auto *SI = dyn_cast<StoreInst>(U->getUser())) {
1911 if (&SI->getOperandUse(0) == U) {
1912 if (!Visited.insert(U).second)
1913 continue;
1914 SmallSetVector<Value *, 4> PotentialCopies;
1916 *this, *SI, PotentialCopies, QueryingAA, UsedAssumedInformation,
1917 /* OnlyExact */ true)) {
1919 dbgs()
1920 << "[Attributor] Value is stored, continue with "
1921 << PotentialCopies.size()
1922 << " potential copies instead!\n");
1923 for (Value *PotentialCopy : PotentialCopies)
1924 if (!AddUsers(*PotentialCopy, U))
1925 return false;
1926 continue;
1927 }
1928 }
1929 }
1930
1931 bool Follow = false;
1932 if (!Pred(*U, Follow))
1933 return false;
1934 if (!Follow)
1935 continue;
1936
1937 User &Usr = *U->getUser();
1938 AddUsers(Usr, /* OldUse */ nullptr);
1939 }
1940
1941 return true;
1942}
1943
1945 const AbstractAttribute &QueryingAA,
1946 bool RequireAllCallSites,
1947 bool &UsedAssumedInformation) {
1948 // We can try to determine information from
1949 // the call sites. However, this is only possible all call sites are known,
1950 // hence the function has internal linkage.
1951 const IRPosition &IRP = QueryingAA.getIRPosition();
1952 const Function *AssociatedFunction = IRP.getAssociatedFunction();
1953 if (!AssociatedFunction) {
1954 LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP
1955 << "\n");
1956 return false;
1957 }
1958
1959 return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites,
1960 &QueryingAA, UsedAssumedInformation);
1961}
1962
1964 const Function &Fn,
1965 bool RequireAllCallSites,
1966 const AbstractAttribute *QueryingAA,
1967 bool &UsedAssumedInformation,
1968 bool CheckPotentiallyDead) {
1969 if (RequireAllCallSites && !Fn.hasLocalLinkage()) {
1970 LLVM_DEBUG(
1971 dbgs()
1972 << "[Attributor] Function " << Fn.getName()
1973 << " has no internal linkage, hence not all call sites are known\n");
1974 return false;
1975 }
1976 // Check virtual uses first.
1977 for (VirtualUseCallbackTy &CB : VirtualUseCallbacks.lookup(&Fn))
1978 if (!CB(*this, QueryingAA))
1979 return false;
1980
1982 for (unsigned u = 0; u < Uses.size(); ++u) {
1983 const Use &U = *Uses[u];
1985 if (auto *Fn = dyn_cast<Function>(U))
1986 dbgs() << "[Attributor] Check use: " << Fn->getName() << " in "
1987 << *U.getUser() << "\n";
1988 else
1989 dbgs() << "[Attributor] Check use: " << *U << " in " << *U.getUser()
1990 << "\n";
1991 });
1992 if (!CheckPotentiallyDead &&
1993 isAssumedDead(U, QueryingAA, nullptr, UsedAssumedInformation,
1994 /* CheckBBLivenessOnly */ true)) {
1996 dbgs() << "[Attributor] Dead use, skip!\n");
1997 continue;
1998 }
1999 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
2000 if (CE->isCast() && CE->getType()->isPointerTy()) {
2002 dbgs() << "[Attributor] Use, is constant cast expression, add "
2003 << CE->getNumUses() << " uses of that expression instead!\n";
2004 });
2005 for (const Use &CEU : CE->uses())
2006 Uses.push_back(&CEU);
2007 continue;
2008 }
2009 }
2010
2011 AbstractCallSite ACS(&U);
2012 if (!ACS) {
2013 LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName()
2014 << " has non call site use " << *U.get() << " in "
2015 << *U.getUser() << "\n");
2016 return false;
2017 }
2018
2019 const Use *EffectiveUse =
2020 ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U;
2021 if (!ACS.isCallee(EffectiveUse)) {
2022 if (!RequireAllCallSites) {
2023 LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
2024 << " is not a call of " << Fn.getName()
2025 << ", skip use\n");
2026 continue;
2027 }
2028 LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
2029 << " is an invalid use of " << Fn.getName() << "\n");
2030 return false;
2031 }
2032
2033 // Make sure the arguments that can be matched between the call site and the
2034 // callee argee on their type. It is unlikely they do not and it doesn't
2035 // make sense for all attributes to know/care about this.
2036 assert(&Fn == ACS.getCalledFunction() && "Expected known callee");
2037 unsigned MinArgsParams =
2038 std::min(size_t(ACS.getNumArgOperands()), Fn.arg_size());
2039 for (unsigned u = 0; u < MinArgsParams; ++u) {
2040 Value *CSArgOp = ACS.getCallArgOperand(u);
2041 if (CSArgOp && Fn.getArg(u)->getType() != CSArgOp->getType()) {
2042 LLVM_DEBUG(
2043 dbgs() << "[Attributor] Call site / callee argument type mismatch ["
2044 << u << "@" << Fn.getName() << ": "
2045 << *Fn.getArg(u)->getType() << " vs. "
2046 << *ACS.getCallArgOperand(u)->getType() << "\n");
2047 return false;
2048 }
2049 }
2050
2051 if (Pred(ACS))
2052 continue;
2053
2054 LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for "
2055 << *ACS.getInstruction() << "\n");
2056 return false;
2057 }
2058
2059 return true;
2060}
2061
2062bool Attributor::shouldPropagateCallBaseContext(const IRPosition &IRP) {
2063 // TODO: Maintain a cache of Values that are
2064 // on the pathway from a Argument to a Instruction that would effect the
2065 // liveness/return state etc.
2067}
2068
2070 const AbstractAttribute &QueryingAA,
2072 bool RecurseForSelectAndPHI) {
2073
2074 const IRPosition &IRP = QueryingAA.getIRPosition();
2075 const Function *AssociatedFunction = IRP.getAssociatedFunction();
2076 if (!AssociatedFunction)
2077 return false;
2078
2079 bool UsedAssumedInformation = false;
2082 IRPosition::returned(*AssociatedFunction), &QueryingAA, Values, S,
2083 UsedAssumedInformation, RecurseForSelectAndPHI))
2084 return false;
2085
2086 return llvm::all_of(Values, [&](const AA::ValueAndContext &VAC) {
2087 return Pred(*VAC.getValue());
2088 });
2089}
2090
2093 function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA,
2094 const AAIsDead *LivenessAA, ArrayRef<unsigned> Opcodes,
2095 bool &UsedAssumedInformation, bool CheckBBLivenessOnly = false,
2096 bool CheckPotentiallyDead = false) {
2097 for (unsigned Opcode : Opcodes) {
2098 // Check if we have instructions with this opcode at all first.
2099 auto *Insts = OpcodeInstMap.lookup(Opcode);
2100 if (!Insts)
2101 continue;
2102
2103 for (Instruction *I : *Insts) {
2104 // Skip dead instructions.
2105 if (A && !CheckPotentiallyDead &&
2106 A->isAssumedDead(IRPosition::inst(*I), QueryingAA, LivenessAA,
2107 UsedAssumedInformation, CheckBBLivenessOnly)) {
2109 dbgs() << "[Attributor] Instruction " << *I
2110 << " is potentially dead, skip!\n";);
2111 continue;
2112 }
2113
2114 if (!Pred(*I))
2115 return false;
2116 }
2117 }
2118 return true;
2119}
2120
2122 const Function *Fn,
2123 const AbstractAttribute *QueryingAA,
2124 ArrayRef<unsigned> Opcodes,
2125 bool &UsedAssumedInformation,
2126 bool CheckBBLivenessOnly,
2127 bool CheckPotentiallyDead) {
2128 // Since we need to provide instructions we have to have an exact definition.
2129 if (!Fn || Fn->isDeclaration())
2130 return false;
2131
2132 const IRPosition &QueryIRP = IRPosition::function(*Fn);
2133 const auto *LivenessAA =
2134 CheckPotentiallyDead && QueryingAA
2135 ? (getAAFor<AAIsDead>(*QueryingAA, QueryIRP, DepClassTy::NONE))
2136 : nullptr;
2137
2138 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
2139 if (!checkForAllInstructionsImpl(this, OpcodeInstMap, Pred, QueryingAA,
2140 LivenessAA, Opcodes, UsedAssumedInformation,
2141 CheckBBLivenessOnly, CheckPotentiallyDead))
2142 return false;
2143
2144 return true;
2145}
2146
2148 const AbstractAttribute &QueryingAA,
2149 ArrayRef<unsigned> Opcodes,
2150 bool &UsedAssumedInformation,
2151 bool CheckBBLivenessOnly,
2152 bool CheckPotentiallyDead) {
2153 const IRPosition &IRP = QueryingAA.getIRPosition();
2154 const Function *AssociatedFunction = IRP.getAssociatedFunction();
2155 return checkForAllInstructions(Pred, AssociatedFunction, &QueryingAA, Opcodes,
2156 UsedAssumedInformation, CheckBBLivenessOnly,
2157 CheckPotentiallyDead);
2158}
2159
2161 function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA,
2162 bool &UsedAssumedInformation) {
2163 TimeTraceScope TS("checkForAllReadWriteInstructions");
2164
2165 const Function *AssociatedFunction =
2166 QueryingAA.getIRPosition().getAssociatedFunction();
2167 if (!AssociatedFunction)
2168 return false;
2169
2170 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
2171 const auto *LivenessAA =
2172 getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE);
2173
2174 for (Instruction *I :
2175 InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) {
2176 // Skip dead instructions.
2177 if (isAssumedDead(IRPosition::inst(*I), &QueryingAA, LivenessAA,
2178 UsedAssumedInformation))
2179 continue;
2180
2181 if (!Pred(*I))
2182 return false;
2183 }
2184
2185 return true;
2186}
2187
2188void Attributor::runTillFixpoint() {
2189 TimeTraceScope TimeScope("Attributor::runTillFixpoint");
2190 LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
2191 << DG.SyntheticRoot.Deps.size()
2192 << " abstract attributes.\n");
2193
2194 // Now that all abstract attributes are collected and initialized we start
2195 // the abstract analysis.
2196
2197 unsigned IterationCounter = 1;
2198 unsigned MaxIterations =
2199 Configuration.MaxFixpointIterations.value_or(SetFixpointIterations);
2200
2202 SetVector<AbstractAttribute *> Worklist, InvalidAAs;
2203 Worklist.insert_range(DG.SyntheticRoot);
2204
2205 do {
2206 // Remember the size to determine new attributes.
2207 size_t NumAAs = DG.SyntheticRoot.Deps.size();
2208 LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
2209 << ", Worklist size: " << Worklist.size() << "\n");
2210
2211 // For invalid AAs we can fix dependent AAs that have a required dependence,
2212 // thereby folding long dependence chains in a single step without the need
2213 // to run updates.
2214 for (unsigned u = 0; u < InvalidAAs.size(); ++u) {
2215 AbstractAttribute *InvalidAA = InvalidAAs[u];
2216
2217 // Check the dependences to fast track invalidation.
2219 dbgs() << "[Attributor] InvalidAA: " << *InvalidAA
2220 << " has " << InvalidAA->Deps.size()
2221 << " required & optional dependences\n");
2222 for (auto &DepIt : InvalidAA->Deps) {
2223 AbstractAttribute *DepAA = cast<AbstractAttribute>(DepIt.getPointer());
2224 if (DepIt.getInt() == unsigned(DepClassTy::OPTIONAL)) {
2226 dbgs() << " - recompute: " << *DepAA);
2227 Worklist.insert(DepAA);
2228 continue;
2229 }
2231 << " - invalidate: " << *DepAA);
2233 assert(DepAA->getState().isAtFixpoint() && "Expected fixpoint state!");
2234 if (!DepAA->getState().isValidState())
2235 InvalidAAs.insert(DepAA);
2236 else
2237 ChangedAAs.push_back(DepAA);
2238 }
2239 InvalidAA->Deps.clear();
2240 }
2241
2242 // Add all abstract attributes that are potentially dependent on one that
2243 // changed to the work list.
2244 for (AbstractAttribute *ChangedAA : ChangedAAs) {
2245 for (auto &DepIt : ChangedAA->Deps)
2246 Worklist.insert(cast<AbstractAttribute>(DepIt.getPointer()));
2247 ChangedAA->Deps.clear();
2248 }
2249
2250 LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter
2251 << ", Worklist+Dependent size: " << Worklist.size()
2252 << "\n");
2253
2254 // Reset the changed and invalid set.
2255 ChangedAAs.clear();
2256 InvalidAAs.clear();
2257
2258 // Update all abstract attribute in the work list and record the ones that
2259 // changed.
2260 for (AbstractAttribute *AA : Worklist) {
2261 const auto &AAState = AA->getState();
2262 if (!AAState.isAtFixpoint())
2263 if (updateAA(*AA) == ChangeStatus::CHANGED)
2264 ChangedAAs.push_back(AA);
2265
2266 // Use the InvalidAAs vector to propagate invalid states fast transitively
2267 // without requiring updates.
2268 if (!AAState.isValidState())
2269 InvalidAAs.insert(AA);
2270 }
2271
2272 // Add attributes to the changed set if they have been created in the last
2273 // iteration.
2274 ChangedAAs.append(DG.SyntheticRoot.begin() + NumAAs,
2275 DG.SyntheticRoot.end());
2276
2277 // Reset the work list and repopulate with the changed abstract attributes.
2278 // Note that dependent ones are added above.
2279 Worklist.clear();
2280 Worklist.insert_range(ChangedAAs);
2281 Worklist.insert_range(QueryAAsAwaitingUpdate);
2282 QueryAAsAwaitingUpdate.clear();
2283
2284 } while (!Worklist.empty() && (IterationCounter++ < MaxIterations));
2285
2286 if (IterationCounter > MaxIterations && !Functions.empty()) {
2287 auto Remark = [&](OptimizationRemarkMissed ORM) {
2288 return ORM << "Attributor did not reach a fixpoint after "
2289 << ore::NV("Iterations", MaxIterations) << " iterations.";
2290 };
2291 Function *F = Functions.front();
2293 }
2294
2295 LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
2296 << IterationCounter << "/" << MaxIterations
2297 << " iterations\n");
2298
2299 // Reset abstract arguments not settled in a sound fixpoint by now. This
2300 // happens when we stopped the fixpoint iteration early. Note that only the
2301 // ones marked as "changed" *and* the ones transitively depending on them
2302 // need to be reverted to a pessimistic state. Others might not be in a
2303 // fixpoint state but we can use the optimistic results for them anyway.
2304 SmallPtrSet<AbstractAttribute *, 32> Visited;
2305 for (unsigned u = 0; u < ChangedAAs.size(); u++) {
2306 AbstractAttribute *ChangedAA = ChangedAAs[u];
2307 if (!Visited.insert(ChangedAA).second)
2308 continue;
2309
2310 AbstractState &State = ChangedAA->getState();
2311 if (!State.isAtFixpoint()) {
2313
2314 NumAttributesTimedOut++;
2315 }
2316
2317 for (auto &DepIt : ChangedAA->Deps)
2318 ChangedAAs.push_back(cast<AbstractAttribute>(DepIt.getPointer()));
2319 ChangedAA->Deps.clear();
2320 }
2321
2322 LLVM_DEBUG({
2323 if (!Visited.empty())
2324 dbgs() << "\n[Attributor] Finalized " << Visited.size()
2325 << " abstract attributes.\n";
2326 });
2327}
2328
2330 assert(AA.isQueryAA() &&
2331 "Non-query AAs should not be required to register for updates!");
2332 QueryAAsAwaitingUpdate.insert(&AA);
2333}
2334
2335ChangeStatus Attributor::manifestAttributes() {
2336 TimeTraceScope TimeScope("Attributor::manifestAttributes");
2337 size_t NumFinalAAs = DG.SyntheticRoot.Deps.size();
2338
2339 unsigned NumManifested = 0;
2340 unsigned NumAtFixpoint = 0;
2341 ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
2342 for (auto &DepAA : DG.SyntheticRoot.Deps) {
2343 AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer());
2344 AbstractState &State = AA->getState();
2345
2346 // If there is not already a fixpoint reached, we can now take the
2347 // optimistic state. This is correct because we enforced a pessimistic one
2348 // on abstract attributes that were transitively dependent on a changed one
2349 // already above.
2350 if (!State.isAtFixpoint())
2351 State.indicateOptimisticFixpoint();
2352
2353 // We must not manifest Attributes that use Callbase info.
2354 if (AA->hasCallBaseContext())
2355 continue;
2356 // If the state is invalid, we do not try to manifest it.
2357 if (!State.isValidState())
2358 continue;
2359
2360 if (AA->getCtxI() && !isRunOn(*AA->getAnchorScope()))
2361 continue;
2362
2363 // Skip dead code.
2364 bool UsedAssumedInformation = false;
2365 if (isAssumedDead(*AA, nullptr, UsedAssumedInformation,
2366 /* CheckBBLivenessOnly */ true))
2367 continue;
2368 // Check if the manifest debug counter that allows skipping manifestation of
2369 // AAs
2370 if (!DebugCounter::shouldExecute(ManifestDBGCounter))
2371 continue;
2372 // Manifest the state and record if we changed the IR.
2373 ChangeStatus LocalChange = AA->manifest(*this);
2374 if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
2375 AA->trackStatistics();
2376 LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA
2377 << "\n");
2378
2379 ManifestChange = ManifestChange | LocalChange;
2380
2381 NumAtFixpoint++;
2382 NumManifested += (LocalChange == ChangeStatus::CHANGED);
2383 }
2384
2385 (void)NumManifested;
2386 (void)NumAtFixpoint;
2387 LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
2388 << " arguments while " << NumAtFixpoint
2389 << " were in a valid fixpoint state\n");
2390
2391 NumAttributesManifested += NumManifested;
2392 NumAttributesValidFixpoint += NumAtFixpoint;
2393
2394 (void)NumFinalAAs;
2395 if (NumFinalAAs != DG.SyntheticRoot.Deps.size()) {
2396 auto DepIt = DG.SyntheticRoot.Deps.begin();
2397 for (unsigned u = 0; u < NumFinalAAs; ++u)
2398 ++DepIt;
2399 for (unsigned u = NumFinalAAs; u < DG.SyntheticRoot.Deps.size();
2400 ++u, ++DepIt) {
2401 errs() << "Unexpected abstract attribute: "
2402 << cast<AbstractAttribute>(DepIt->getPointer()) << " :: "
2403 << cast<AbstractAttribute>(DepIt->getPointer())
2404 ->getIRPosition()
2405 .getAssociatedValue()
2406 << "\n";
2407 }
2408 llvm_unreachable("Expected the final number of abstract attributes to "
2409 "remain unchanged!");
2410 }
2411
2412 for (auto &It : AttrsMap) {
2413 AttributeList &AL = It.getSecond();
2414 const IRPosition &IRP =
2415 isa<Function>(It.getFirst())
2416 ? IRPosition::function(*cast<Function>(It.getFirst()))
2417 : IRPosition::callsite_function(*cast<CallBase>(It.getFirst()));
2418 IRP.setAttrList(AL);
2419 }
2420
2421 return ManifestChange;
2422}
2423
2424void Attributor::identifyDeadInternalFunctions() {
2425 // Early exit if we don't intend to delete functions.
2426 if (!Configuration.DeleteFns)
2427 return;
2428
2429 // To avoid triggering an assertion in the lazy call graph we will not delete
2430 // any internal library functions. We should modify the assertion though and
2431 // allow internals to be deleted.
2432 const auto *TLI =
2433 isModulePass()
2434 ? nullptr
2435 : getInfoCache().getTargetLibraryInfoForFunction(*Functions.back());
2436
2437 // Identify dead internal functions and delete them. This happens outside
2438 // the other fixpoint analysis as we might treat potentially dead functions
2439 // as live to lower the number of iterations. If they happen to be dead, the
2440 // below fixpoint loop will identify and eliminate them.
2441
2442 SmallVector<Function *, 8> InternalFns;
2443 for (Function *F : Functions)
2444 if (F->hasLocalLinkage() &&
2445 (isModulePass() || TLI->getLibFunc(*F) == NotLibFunc))
2446 InternalFns.push_back(F);
2447
2448 SmallPtrSet<Function *, 8> LiveInternalFns;
2449 bool FoundLiveInternal = true;
2450 while (FoundLiveInternal) {
2451 FoundLiveInternal = false;
2452 for (Function *&F : InternalFns) {
2453 if (!F)
2454 continue;
2455
2456 bool UsedAssumedInformation = false;
2458 [&](AbstractCallSite ACS) {
2460 return ToBeDeletedFunctions.count(Callee) ||
2461 (Functions.count(Callee) && Callee->hasLocalLinkage() &&
2462 !LiveInternalFns.count(Callee));
2463 },
2464 *F, true, nullptr, UsedAssumedInformation)) {
2465 continue;
2466 }
2467
2468 LiveInternalFns.insert(F);
2469 F = nullptr;
2470 FoundLiveInternal = true;
2471 }
2472 }
2473
2474 for (Function *F : InternalFns)
2475 if (F)
2476 ToBeDeletedFunctions.insert(F);
2477}
2478
2479ChangeStatus Attributor::cleanupIR() {
2480 TimeTraceScope TimeScope("Attributor::cleanupIR");
2481 // Delete stuff at the end to avoid invalid references and a nice order.
2482 LLVM_DEBUG(dbgs() << "\n[Attributor] Delete/replace at least "
2483 << ToBeDeletedFunctions.size() << " functions and "
2484 << ToBeDeletedBlocks.size() << " blocks and "
2485 << ToBeDeletedInsts.size() << " instructions and "
2486 << ToBeChangedValues.size() << " values and "
2487 << ToBeChangedUses.size() << " uses. To insert "
2488 << ToBeChangedToUnreachableInsts.size()
2489 << " unreachables.\n"
2490 << "Preserve manifest added " << ManifestAddedBlocks.size()
2491 << " blocks\n");
2492
2494 SmallVector<Instruction *, 32> TerminatorsToFold;
2495
2496 auto ReplaceUse = [&](Use *U, Value *NewV) {
2497 Value *OldV = U->get();
2498
2499 // If we plan to replace NewV we need to update it at this point.
2500 do {
2501 const auto &Entry = ToBeChangedValues.lookup(NewV);
2502 if (!get<0>(Entry))
2503 break;
2504 NewV = get<0>(Entry);
2505 } while (true);
2506
2507 Instruction *I = dyn_cast<Instruction>(U->getUser());
2508 assert((!I || isRunOn(*I->getFunction())) &&
2509 "Cannot replace an instruction outside the current SCC!");
2510
2511 // Do not replace uses in returns if the value is a must-tail call we will
2512 // not delete.
2513 if (auto *RI = dyn_cast_or_null<ReturnInst>(I)) {
2514 if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts()))
2515 if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI))
2516 return;
2517 // If we rewrite a return and the new value is not an argument, strip the
2518 // `returned` attribute as it is wrong now.
2519 if (!isa<Argument>(NewV))
2520 for (auto &Arg : RI->getFunction()->args())
2521 Arg.removeAttr(Attribute::Returned);
2522 }
2523
2524 LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser()
2525 << " instead of " << *OldV << "\n");
2526 U->set(NewV);
2527
2528 // The new value may reference a function, e.g., if an argument is replaced
2529 // by a function pointer, so the call graph of the user's function changes.
2530 if (I)
2531 CGModifiedFunctions.insert(I->getFunction());
2532 if (Instruction *OldI = dyn_cast<Instruction>(OldV)) {
2533 if (!isa<PHINode>(OldI) && !ToBeDeletedInsts.count(OldI) &&
2535 DeadInsts.push_back(OldI);
2536 }
2537 if (isa<UndefValue>(NewV) && isa<CallBase>(U->getUser())) {
2538 auto *CB = cast<CallBase>(U->getUser());
2539 if (CB->isArgOperand(U)) {
2540 unsigned Idx = CB->getArgOperandNo(U);
2541 // Drop all attributes that make passing undef UB, e.g., dereferenceable
2542 // implies noundef.
2543 AttributeMask UBImplying = AttributeFuncs::getUBImplyingAttributes();
2544 CB->removeParamAttrs(Idx, UBImplying);
2545 auto *Callee = dyn_cast_if_present<Function>(CB->getCalledOperand());
2546 if (Callee && Callee->arg_size() > Idx)
2547 Callee->removeParamAttrs(Idx, UBImplying);
2548 }
2549 }
2550 if (isa<Constant>(NewV) && isa<CondBrInst>(U->getUser())) {
2551 Instruction *UserI = cast<Instruction>(U->getUser());
2552 if (isa<UndefValue>(NewV)) {
2553 ToBeChangedToUnreachableInsts.insert(UserI);
2554 } else {
2555 TerminatorsToFold.push_back(UserI);
2556 }
2557 }
2558 };
2559
2560 for (auto &It : ToBeChangedUses) {
2561 Use *U = It.first;
2562 Value *NewV = It.second;
2563 ReplaceUse(U, NewV);
2564 }
2565
2567 for (auto &It : ToBeChangedValues) {
2568 Value *OldV = It.first;
2569 auto [NewV, Done] = It.second;
2570 Uses.clear();
2571 for (auto &U : OldV->uses())
2572 if (Done || !U.getUser()->isDroppable())
2573 Uses.push_back(&U);
2574 for (Use *U : Uses) {
2575 if (auto *I = dyn_cast<Instruction>(U->getUser()))
2576 if (!isRunOn(*I->getFunction()))
2577 continue;
2578 ReplaceUse(U, NewV);
2579 }
2580 }
2581
2582 for (const auto &V : InvokeWithDeadSuccessor)
2583 if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) {
2584 assert(isRunOn(*II->getFunction()) &&
2585 "Cannot replace an invoke outside the current SCC!");
2586 bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind);
2587 bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn);
2588 bool Invoke2CallAllowed =
2590 assert((UnwindBBIsDead || NormalBBIsDead) &&
2591 "Invoke does not have dead successors!");
2592 BasicBlock *BB = II->getParent();
2593 BasicBlock *NormalDestBB = II->getNormalDest();
2594 if (UnwindBBIsDead) {
2595 Instruction *NormalNextIP = &NormalDestBB->front();
2596 if (Invoke2CallAllowed) {
2598 NormalNextIP = BB->getTerminator();
2599 }
2600 if (NormalBBIsDead)
2601 ToBeChangedToUnreachableInsts.insert(NormalNextIP);
2602 } else {
2603 assert(NormalBBIsDead && "Broken invariant!");
2604 if (!NormalDestBB->getUniquePredecessor())
2605 NormalDestBB = SplitBlockPredecessors(NormalDestBB, {BB}, ".dead");
2606 ToBeChangedToUnreachableInsts.insert(&NormalDestBB->front());
2607 }
2608 }
2609 for (Instruction *I : TerminatorsToFold) {
2610 assert(isRunOn(*I->getFunction()) &&
2611 "Cannot replace a terminator outside the current SCC!");
2612 CGModifiedFunctions.insert(I->getFunction());
2613 ConstantFoldTerminator(I->getParent());
2614 }
2615 for (const auto &V : ToBeChangedToUnreachableInsts)
2616 if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
2617 LLVM_DEBUG(dbgs() << "[Attributor] Change to unreachable: " << *I
2618 << "\n");
2619 assert(isRunOn(*I->getFunction()) &&
2620 "Cannot replace an instruction outside the current SCC!");
2621 CGModifiedFunctions.insert(I->getFunction());
2623 }
2624
2625 for (const auto &V : ToBeDeletedInsts) {
2626 if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
2628 isRunOn(*I->getFunction())) &&
2629 "Cannot delete an instruction outside the current SCC!");
2630 I->dropDroppableUses();
2631 CGModifiedFunctions.insert(I->getFunction());
2632 if (!I->getType()->isVoidTy())
2633 I->replaceAllUsesWith(UndefValue::get(I->getType()));
2635 DeadInsts.push_back(I);
2636 else
2637 I->eraseFromParent();
2638 }
2639 }
2640
2641 llvm::erase_if(DeadInsts, [&](WeakTrackingVH I) { return !I; });
2642
2643 LLVM_DEBUG({
2644 dbgs() << "[Attributor] DeadInsts size: " << DeadInsts.size() << "\n";
2645 for (auto &I : DeadInsts)
2646 if (I)
2647 dbgs() << " - " << *I << "\n";
2648 });
2649
2651
2652 if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
2653 SmallVector<BasicBlock *, 8> ToBeDeletedBBs;
2654 ToBeDeletedBBs.reserve(NumDeadBlocks);
2655 for (BasicBlock *BB : ToBeDeletedBlocks) {
2656 assert(isRunOn(*BB->getParent()) &&
2657 "Cannot delete a block outside the current SCC!");
2658 CGModifiedFunctions.insert(BB->getParent());
2659 // Do not delete BBs added during manifests of AAs.
2660 if (ManifestAddedBlocks.contains(BB))
2661 continue;
2662 ToBeDeletedBBs.push_back(BB);
2663 }
2664 // Actually we do not delete the blocks but squash them into a single
2665 // unreachable but untangling branches that jump here is something we need
2666 // to do in a more generic way.
2667 detachDeadBlocks(ToBeDeletedBBs, nullptr);
2668 }
2669
2670 identifyDeadInternalFunctions();
2671
2672 // Rewrite the functions as requested during manifest.
2673 ChangeStatus ManifestChange = rewriteFunctionSignatures(CGModifiedFunctions);
2674
2675 for (Function *Fn : CGModifiedFunctions)
2676 if (!ToBeDeletedFunctions.count(Fn) && Functions.count(Fn))
2677 Configuration.CGUpdater.reanalyzeFunction(*Fn);
2678
2679 for (Function *Fn : ToBeDeletedFunctions) {
2680 if (!Functions.count(Fn))
2681 continue;
2682 Configuration.CGUpdater.removeFunction(*Fn);
2683 }
2684
2685 if (!ToBeChangedUses.empty())
2686 ManifestChange = ChangeStatus::CHANGED;
2687
2688 if (!ToBeChangedToUnreachableInsts.empty())
2689 ManifestChange = ChangeStatus::CHANGED;
2690
2691 if (!ToBeDeletedFunctions.empty())
2692 ManifestChange = ChangeStatus::CHANGED;
2693
2694 if (!ToBeDeletedBlocks.empty())
2695 ManifestChange = ChangeStatus::CHANGED;
2696
2697 if (!ToBeDeletedInsts.empty())
2698 ManifestChange = ChangeStatus::CHANGED;
2699
2700 if (!InvokeWithDeadSuccessor.empty())
2701 ManifestChange = ChangeStatus::CHANGED;
2702
2703 if (!DeadInsts.empty())
2704 ManifestChange = ChangeStatus::CHANGED;
2705
2706 NumFnDeleted += ToBeDeletedFunctions.size();
2707
2708 LLVM_DEBUG(dbgs() << "[Attributor] Deleted " << ToBeDeletedFunctions.size()
2709 << " functions after manifest.\n");
2710
2711#ifdef EXPENSIVE_CHECKS
2712 for (Function *F : Functions) {
2713 if (ToBeDeletedFunctions.count(F))
2714 continue;
2715 assert(!verifyFunction(*F, &errs()) && "Module verification failed!");
2716 }
2717#endif
2718
2719 return ManifestChange;
2720}
2721
2723 TimeTraceScope TimeScope("Attributor::run");
2724 AttributorCallGraph ACallGraph(*this);
2725
2726 if (PrintCallGraph)
2727 ACallGraph.populateAll();
2728
2729 Phase = AttributorPhase::UPDATE;
2730 runTillFixpoint();
2731
2732 // dump graphs on demand
2733 if (DumpDepGraph)
2734 DG.dumpGraph();
2735
2736 if (ViewDepGraph)
2737 DG.viewGraph();
2738
2740 DG.print();
2741
2742 Phase = AttributorPhase::MANIFEST;
2743 ChangeStatus ManifestChange = manifestAttributes();
2744
2745 Phase = AttributorPhase::CLEANUP;
2746 ChangeStatus CleanupChange = cleanupIR();
2747
2748 if (PrintCallGraph)
2749 ACallGraph.print();
2750
2751 return ManifestChange | CleanupChange;
2752}
2753
2754ChangeStatus Attributor::updateAA(AbstractAttribute &AA) {
2755 TimeTraceScope TimeScope("updateAA", [&]() {
2756 return AA.getName().str() +
2757 std::to_string(AA.getIRPosition().getPositionKind());
2758 });
2759 assert(Phase == AttributorPhase::UPDATE &&
2760 "We can update AA only in the update stage!");
2761
2762 // Use a new dependence vector for this update.
2763 DependenceVector DV;
2764 DependenceStack.push_back(&DV);
2765
2766 auto &AAState = AA.getState();
2768 bool UsedAssumedInformation = false;
2769 if (!isAssumedDead(AA, nullptr, UsedAssumedInformation,
2770 /* CheckBBLivenessOnly */ true))
2771 CS = AA.update(*this);
2772
2773 if (!AA.isQueryAA() && DV.empty() && !AA.getState().isAtFixpoint()) {
2774 // If the AA did not rely on outside information but changed, we run it
2775 // again to see if it found a fixpoint. Most AAs do but we don't require
2776 // them to. Hence, it might take the AA multiple iterations to get to a
2777 // fixpoint even if it does not rely on outside information, which is fine.
2779 if (CS == ChangeStatus::CHANGED)
2780 RerunCS = AA.update(*this);
2781
2782 // If the attribute did not change during the run or rerun, and it still did
2783 // not query any non-fix information, the state will not change and we can
2784 // indicate that right at this point.
2785 if (RerunCS == ChangeStatus::UNCHANGED && !AA.isQueryAA() && DV.empty())
2786 AAState.indicateOptimisticFixpoint();
2787 }
2788
2789 if (!AAState.isAtFixpoint())
2790 rememberDependences();
2791
2792 // Verify the stack was used properly, that is we pop the dependence vector we
2793 // put there earlier.
2794 DependenceVector *PoppedDV = DependenceStack.pop_back_val();
2795 (void)PoppedDV;
2796 assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!");
2797
2798 return CS;
2799}
2800
2802 assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!");
2803
2804 Module &M = *F.getParent();
2805 LLVMContext &Ctx = M.getContext();
2806 FunctionType *FnTy = F.getFunctionType();
2807
2808 Function *Wrapper =
2809 Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), F.getName());
2810 F.setName(""); // set the inside function anonymous
2811 M.getFunctionList().insert(F.getIterator(), Wrapper);
2812
2813 F.setLinkage(GlobalValue::InternalLinkage);
2814
2815 F.replaceAllUsesWith(Wrapper);
2816 assert(F.use_empty() && "Uses remained after wrapper was created!");
2817
2818 // Move the COMDAT section to the wrapper.
2819 // TODO: Check if we need to keep it for F as well.
2820 Wrapper->setComdat(F.getComdat());
2821 F.setComdat(nullptr);
2822
2823 // Copy all metadata and attributes but keep them on F as well.
2825 F.getAllMetadata(MDs);
2826 for (auto MDIt : MDs)
2827 Wrapper->addMetadata(MDIt.first, *MDIt.second);
2828 Wrapper->setAttributes(F.getAttributes());
2829
2830 // Create the call in the wrapper.
2831 BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Wrapper);
2832
2834 Argument *FArgIt = F.arg_begin();
2835 for (Argument &Arg : Wrapper->args()) {
2836 Args.push_back(&Arg);
2837 Arg.setName((FArgIt++)->getName());
2838 }
2839
2840 CallInst *CI = CallInst::Create(&F, Args, "", EntryBB);
2841 CI->setTailCall(true);
2842 CI->addFnAttr(Attribute::NoInline);
2843 ReturnInst::Create(Ctx, CI->getType()->isVoidTy() ? nullptr : CI, EntryBB);
2844
2845 NumFnShallowWrappersCreated++;
2846}
2847
2849 if (F.isDeclaration() || F.hasLocalLinkage() ||
2851 return false;
2852 return true;
2853}
2854
2856 if (!AllowDeepWrapper && !Force)
2857 return nullptr;
2858 if (!isInternalizable(F))
2859 return nullptr;
2860
2861 SmallPtrSet<Function *, 2> FnSet = {&F};
2862 DenseMap<Function *, Function *> InternalizedFns;
2863 internalizeFunctions(FnSet, InternalizedFns);
2864
2865 return InternalizedFns[&F];
2866}
2867
2870 for (Function *F : FnSet)
2872 return false;
2873
2874 FnMap.clear();
2875 // Generate the internalized version of each function.
2876 for (Function *F : FnSet) {
2877 Module &M = *F->getParent();
2878 FunctionType *FnTy = F->getFunctionType();
2879
2880 // Create a copy of the current function
2881 Function *Copied =
2882 Function::Create(FnTy, F->getLinkage(), F->getAddressSpace(),
2883 F->getName() + ".internalized");
2884 ValueToValueMapTy VMap;
2885 auto *NewFArgIt = Copied->arg_begin();
2886 for (auto &Arg : F->args()) {
2887 auto ArgName = Arg.getName();
2888 NewFArgIt->setName(ArgName);
2889 VMap[&Arg] = &(*NewFArgIt++);
2890 }
2892
2893 // Copy the body of the original function to the new one
2894 CloneFunctionInto(Copied, F, VMap,
2896
2897 // Set the linakage and visibility late as CloneFunctionInto has some
2898 // implicit requirements.
2901
2902 // Copy metadata
2904 F->getAllMetadata(MDs);
2905 for (auto MDIt : MDs)
2906 if (!Copied->hasMetadata())
2907 Copied->addMetadata(MDIt.first, *MDIt.second);
2908
2909 M.getFunctionList().insert(F->getIterator(), Copied);
2910 Copied->setDSOLocal(true);
2911 FnMap[F] = Copied;
2912 }
2913
2914 // Replace all uses of the old function with the new internalized function
2915 // unless the caller is a function that was just internalized.
2916 for (Function *F : FnSet) {
2917 auto &InternalizedFn = FnMap[F];
2918 auto IsNotInternalized = [&](Use &U) -> bool {
2919 if (auto *CB = dyn_cast<CallBase>(U.getUser()))
2920 return !FnMap.lookup(CB->getCaller());
2921 return false;
2922 };
2923 F->replaceUsesWithIf(InternalizedFn, IsNotInternalized);
2924 }
2925
2926 return true;
2927}
2928
2930 Argument &Arg, ArrayRef<Type *> ReplacementTypes) {
2931
2932 if (!Configuration.RewriteSignatures)
2933 return false;
2934
2935 Function *Fn = Arg.getParent();
2936 auto CallSiteCanBeChanged = [Fn](AbstractCallSite ACS) {
2937 // Forbid the call site to cast the function return type. If we need to
2938 // rewrite these functions we need to re-create a cast for the new call site
2939 // (if the old had uses).
2940 if (!ACS.getCalledFunction() ||
2941 ACS.getInstruction()->getType() !=
2943 return false;
2944 if (cast<CallBase>(ACS.getInstruction())->getCalledOperand()->getType() !=
2945 Fn->getType())
2946 return false;
2947 if (ACS.getNumArgOperands() != Fn->arg_size())
2948 return false;
2949 // Forbid must-tail calls for now.
2950 return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall();
2951 };
2952
2953 // Avoid var-arg functions for now.
2954 if (Fn->isVarArg()) {
2955 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n");
2956 return false;
2957 }
2958
2959 // Avoid functions with complicated argument passing semantics.
2960 AttributeList FnAttributeList = Fn->getAttributes();
2961 if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) ||
2962 FnAttributeList.hasAttrSomewhere(Attribute::StructRet) ||
2963 FnAttributeList.hasAttrSomewhere(Attribute::InAlloca) ||
2964 FnAttributeList.hasAttrSomewhere(Attribute::Preallocated)) {
2965 LLVM_DEBUG(
2966 dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n");
2967 return false;
2968 }
2969
2970 // Avoid callbacks for now.
2971 bool UsedAssumedInformation = false;
2972 if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn, true, nullptr,
2973 UsedAssumedInformation,
2974 /* CheckPotentiallyDead */ true)) {
2975 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n");
2976 return false;
2977 }
2978
2979 auto InstPred = [](Instruction &I) {
2980 if (auto *CI = dyn_cast<CallInst>(&I))
2981 return !CI->isMustTailCall();
2982 return true;
2983 };
2984
2985 // Forbid must-tail calls for now.
2986 // TODO:
2987 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
2988 if (!checkForAllInstructionsImpl(nullptr, OpcodeInstMap, InstPred, nullptr,
2989 nullptr, {Instruction::Call},
2990 UsedAssumedInformation)) {
2991 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n");
2992 return false;
2993 }
2994
2995 return true;
2996}
2997
2999 Argument &Arg, ArrayRef<Type *> ReplacementTypes,
3002 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
3003 << Arg.getParent()->getName() << " with "
3004 << ReplacementTypes.size() << " replacements\n");
3005 assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) &&
3006 "Cannot register an invalid rewrite");
3007
3008 Function *Fn = Arg.getParent();
3010 ArgumentReplacementMap[Fn];
3011 if (ARIs.empty())
3012 ARIs.resize(Fn->arg_size());
3013
3014 // If we have a replacement already with less than or equal new arguments,
3015 // ignore this request.
3016 std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()];
3017 if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) {
3018 LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n");
3019 return false;
3020 }
3021
3022 // If we have a replacement already but we like the new one better, delete
3023 // the old.
3024 ARI.reset();
3025
3026 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
3027 << Arg.getParent()->getName() << " with "
3028 << ReplacementTypes.size() << " replacements\n");
3029
3030 // Remember the replacement.
3031 ARI.reset(new ArgumentReplacementInfo(*this, Arg, ReplacementTypes,
3032 std::move(CalleeRepairCB),
3033 std::move(ACSRepairCB)));
3034
3035 return true;
3036}
3037
3038bool Attributor::shouldSeedAttribute(AbstractAttribute &AA) {
3039 bool Result = true;
3040#ifndef NDEBUG
3041 if (SeedAllowList.size() != 0)
3042 Result = llvm::is_contained(SeedAllowList, AA.getName());
3043 Function *Fn = AA.getAnchorScope();
3044 if (FunctionSeedAllowList.size() != 0 && Fn)
3046#endif
3047 return Result;
3048}
3049
3050ChangeStatus Attributor::rewriteFunctionSignatures(
3051 SmallSetVector<Function *, 8> &ModifiedFns) {
3053
3054 for (auto &It : ArgumentReplacementMap) {
3055 Function *OldFn = It.first;
3056
3057 // Deleted functions do not require rewrites.
3058 if (!Functions.count(OldFn) || ToBeDeletedFunctions.count(OldFn))
3059 continue;
3060
3062 It.second;
3063 assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!");
3064
3065 SmallVector<Type *, 16> NewArgumentTypes;
3066 SmallVector<AttributeSet, 16> NewArgumentAttributes;
3067
3068 // Collect replacement argument types and copy over existing attributes.
3069 AttributeList OldFnAttributeList = OldFn->getAttributes();
3070 for (Argument &Arg : OldFn->args()) {
3071 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3072 ARIs[Arg.getArgNo()]) {
3073 NewArgumentTypes.append(ARI->ReplacementTypes.begin(),
3074 ARI->ReplacementTypes.end());
3075 NewArgumentAttributes.append(ARI->getNumReplacementArgs(),
3076 AttributeSet());
3077 } else {
3078 NewArgumentTypes.push_back(Arg.getType());
3079 NewArgumentAttributes.push_back(
3080 OldFnAttributeList.getParamAttrs(Arg.getArgNo()));
3081 }
3082 }
3083
3084 uint64_t LargestVectorWidth = 0;
3085 for (auto *I : NewArgumentTypes)
3086 if (auto *VT = dyn_cast<llvm::VectorType>(I))
3087 LargestVectorWidth =
3088 std::max(LargestVectorWidth,
3089 VT->getPrimitiveSizeInBits().getKnownMinValue());
3090
3091 FunctionType *OldFnTy = OldFn->getFunctionType();
3092 Type *RetTy = OldFnTy->getReturnType();
3093
3094 // Construct the new function type using the new arguments types.
3095 FunctionType *NewFnTy =
3096 FunctionType::get(RetTy, NewArgumentTypes, OldFnTy->isVarArg());
3097
3098 LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName()
3099 << "' from " << *OldFn->getFunctionType() << " to "
3100 << *NewFnTy << "\n");
3101
3102 // Create the new function body and insert it into the module.
3103 Function *NewFn = Function::Create(NewFnTy, OldFn->getLinkage(),
3104 OldFn->getAddressSpace(), "");
3105 Functions.insert(NewFn);
3106 OldFn->getParent()->getFunctionList().insert(OldFn->getIterator(), NewFn);
3107 NewFn->takeName(OldFn);
3108 NewFn->copyAttributesFrom(OldFn);
3109
3110 // Patch the pointer to LLVM function in debug info descriptor.
3111 NewFn->setSubprogram(OldFn->getSubprogram());
3112 OldFn->setSubprogram(nullptr);
3113
3114 // Recompute the parameter attributes list based on the new arguments for
3115 // the function.
3116 LLVMContext &Ctx = OldFn->getContext();
3117 NewFn->setAttributes(AttributeList::get(
3118 Ctx, OldFnAttributeList.getFnAttrs(), OldFnAttributeList.getRetAttrs(),
3119 NewArgumentAttributes));
3120 AttributeFuncs::updateMinLegalVectorWidthAttr(*NewFn, LargestVectorWidth);
3121
3122 // Remove argmem from the memory effects if we have no more pointer
3123 // arguments, or they are readnone.
3124 MemoryEffects ME = NewFn->getMemoryEffects();
3125 int ArgNo = -1;
3126 if (ME.doesAccessArgPointees() && all_of(NewArgumentTypes, [&](Type *T) {
3127 ++ArgNo;
3128 return !T->isPtrOrPtrVectorTy() ||
3129 NewFn->hasParamAttribute(ArgNo, Attribute::ReadNone);
3130 })) {
3132 }
3133
3134 // Since we have now created the new function, splice the body of the old
3135 // function right into the new function, leaving the old rotting hulk of the
3136 // function empty.
3137 NewFn->splice(NewFn->begin(), OldFn);
3138
3139 // Set of all "call-like" instructions that invoke the old function mapped
3140 // to their new replacements.
3142
3143 // Callback to create a new "call-like" instruction for a given one.
3144 auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) {
3145 CallBase *OldCB = cast<CallBase>(ACS.getInstruction());
3146 const AttributeList &OldCallAttributeList = OldCB->getAttributes();
3147
3148 // Collect the new argument operands for the replacement call site.
3149 SmallVector<Value *, 16> NewArgOperands;
3150 SmallVector<AttributeSet, 16> NewArgOperandAttributes;
3151 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) {
3152 unsigned NewFirstArgNum = NewArgOperands.size();
3153 (void)NewFirstArgNum; // only used inside assert.
3154 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3155 ARIs[OldArgNum]) {
3156 if (ARI->ACSRepairCB)
3157 ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
3158 assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
3159 NewArgOperands.size() &&
3160 "ACS repair callback did not provide as many operand as new "
3161 "types were registered!");
3162 // TODO: Exose the attribute set to the ACS repair callback
3163 NewArgOperandAttributes.append(ARI->ReplacementTypes.size(),
3164 AttributeSet());
3165 } else {
3166 NewArgOperands.push_back(ACS.getCallArgOperand(OldArgNum));
3167 NewArgOperandAttributes.push_back(
3168 OldCallAttributeList.getParamAttrs(OldArgNum));
3169 }
3170 }
3171
3172 assert(NewArgOperands.size() == NewArgOperandAttributes.size() &&
3173 "Mismatch # argument operands vs. # argument operand attributes!");
3174 assert(NewArgOperands.size() == NewFn->arg_size() &&
3175 "Mismatch # argument operands vs. # function arguments!");
3176
3177 SmallVector<OperandBundleDef, 4> OperandBundleDefs;
3178 OldCB->getOperandBundlesAsDefs(OperandBundleDefs);
3179
3180 // Create a new call or invoke instruction to replace the old one.
3181 CallBase *NewCB;
3182 if (InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) {
3183 NewCB = InvokeInst::Create(NewFn, II->getNormalDest(),
3184 II->getUnwindDest(), NewArgOperands,
3185 OperandBundleDefs, "", OldCB->getIterator());
3186 } else {
3187 auto *NewCI = CallInst::Create(NewFn, NewArgOperands, OperandBundleDefs,
3188 "", OldCB->getIterator());
3189 NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind());
3190 NewCB = NewCI;
3191 }
3192
3193 // Copy over various properties and the new attributes.
3194 NewCB->copyProfileAndDebugMetadata(*OldCB);
3195 NewCB->setCallingConv(OldCB->getCallingConv());
3196 NewCB->takeName(OldCB);
3197 NewCB->setAttributes(AttributeList::get(
3198 Ctx, OldCallAttributeList.getFnAttrs(),
3199 OldCallAttributeList.getRetAttrs(), NewArgOperandAttributes));
3200
3201 AttributeFuncs::updateMinLegalVectorWidthAttr(*NewCB->getCaller(),
3202 LargestVectorWidth);
3203
3204 CallSitePairs.push_back({OldCB, NewCB});
3205 return true;
3206 };
3207
3208 // Use the CallSiteReplacementCreator to create replacement call sites.
3209 bool UsedAssumedInformation = false;
3210 bool Success = checkForAllCallSites(CallSiteReplacementCreator, *OldFn,
3211 true, nullptr, UsedAssumedInformation,
3212 /* CheckPotentiallyDead */ true);
3213 (void)Success;
3214 assert(Success && "Assumed call site replacement to succeed!");
3215
3216 // Rewire the arguments.
3217 Argument *OldFnArgIt = OldFn->arg_begin();
3218 Argument *NewFnArgIt = NewFn->arg_begin();
3219 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size();
3220 ++OldArgNum, ++OldFnArgIt) {
3221 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3222 ARIs[OldArgNum]) {
3223 if (ARI->CalleeRepairCB)
3224 ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
3225 if (ARI->ReplacementTypes.empty())
3226 OldFnArgIt->replaceAllUsesWith(
3227 PoisonValue::get(OldFnArgIt->getType()));
3228 NewFnArgIt += ARI->ReplacementTypes.size();
3229 } else {
3230 NewFnArgIt->takeName(&*OldFnArgIt);
3231 OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt);
3232 ++NewFnArgIt;
3233 }
3234 }
3235
3236 // Eliminate the instructions *after* we visited all of them.
3237 for (auto &CallSitePair : CallSitePairs) {
3238 CallBase &OldCB = *CallSitePair.first;
3239 CallBase &NewCB = *CallSitePair.second;
3240 assert(OldCB.getType() == NewCB.getType() &&
3241 "Cannot handle call sites with different types!");
3242 ModifiedFns.insert(OldCB.getFunction());
3243 OldCB.replaceAllUsesWith(&NewCB);
3244 OldCB.eraseFromParent();
3245 }
3246
3247 // Replace the function in the call graph (if any).
3248 Configuration.CGUpdater.replaceFunctionWith(*OldFn, *NewFn);
3249
3250 // If the old function was modified and needed to be reanalyzed, the new one
3251 // does now.
3252 if (ModifiedFns.remove(OldFn))
3253 ModifiedFns.insert(NewFn);
3254
3256 }
3257
3258 return Changed;
3259}
3260
3261void InformationCache::initializeInformationCache(const Function &CF,
3262 FunctionInfo &FI) {
3263 // As we do not modify the function here we can remove the const
3264 // withouth breaking implicit assumptions. At the end of the day, we could
3265 // initialize the cache eagerly which would look the same to the users.
3266 Function &F = const_cast<Function &>(CF);
3267
3268 FI.IsKernel = F.hasFnAttribute("kernel");
3269
3270 // Walk all instructions to find interesting instructions that might be
3271 // queried by abstract attributes during their initialization or update.
3272 // This has to happen before we create attributes.
3273
3274 DenseMap<const Value *, std::optional<short>> AssumeUsesMap;
3275
3276 // Add \p V to the assume uses map which track the number of uses outside of
3277 // "visited" assumes. If no outside uses are left the value is added to the
3278 // assume only use vector.
3279 auto AddToAssumeUsesMap = [&](const Value &V) -> void {
3280 SmallVector<const Instruction *> Worklist;
3281 if (auto *I = dyn_cast<Instruction>(&V))
3282 Worklist.push_back(I);
3283 while (!Worklist.empty()) {
3284 const Instruction *I = Worklist.pop_back_val();
3285 std::optional<short> &NumUses = AssumeUsesMap[I];
3286 if (!NumUses)
3287 NumUses = I->getNumUses();
3288 NumUses = *NumUses - /* this assume */ 1;
3289 if (*NumUses != 0)
3290 continue;
3291 AssumeOnlyValues.insert(I);
3292 for (const Value *Op : I->operands())
3293 if (auto *OpI = dyn_cast<Instruction>(Op))
3294 Worklist.push_back(OpI);
3295 }
3296 };
3297
3298 for (Instruction &I : instructions(&F)) {
3299 bool IsInterestingOpcode = false;
3300
3301 // To allow easy access to all instructions in a function with a given
3302 // opcode we store them in the InfoCache. As not all opcodes are interesting
3303 // to concrete attributes we only cache the ones that are as identified in
3304 // the following switch.
3305 // Note: There are no concrete attributes now so this is initially empty.
3306 switch (I.getOpcode()) {
3307 default:
3308 assert(!isa<CallBase>(&I) &&
3309 "New call base instruction type needs to be known in the "
3310 "Attributor.");
3311 break;
3312 case Instruction::Call:
3313 // Calls are interesting on their own, additionally:
3314 // For `llvm.assume` calls we also fill the KnowledgeMap as we find them.
3315 // For `must-tail` calls we remember the caller and callee.
3316 if (auto *Assume = dyn_cast<AssumeInst>(&I)) {
3317 AssumeOnlyValues.insert(Assume);
3318 fillMapFromAssume(*Assume, KnowledgeMap);
3319 AddToAssumeUsesMap(*Assume->getArgOperand(0));
3320 } else if (cast<CallInst>(I).isMustTailCall()) {
3321 FI.ContainsMustTailCall = true;
3322 if (auto *Callee = dyn_cast_if_present<Function>(
3323 cast<CallInst>(I).getCalledOperand()))
3324 getFunctionInfo(*Callee).CalledViaMustTail = true;
3325 }
3326 [[fallthrough]];
3327 case Instruction::CallBr:
3328 case Instruction::Invoke:
3329 case Instruction::CleanupRet:
3330 case Instruction::CatchSwitch:
3331 case Instruction::AtomicRMW:
3332 case Instruction::AtomicCmpXchg:
3333 case Instruction::UncondBr:
3334 case Instruction::CondBr:
3335 case Instruction::Resume:
3336 case Instruction::Ret:
3337 case Instruction::Load:
3338 // The alignment of a pointer is interesting for loads.
3339 case Instruction::Store:
3340 // The alignment of a pointer is interesting for stores.
3341 case Instruction::Alloca:
3342 case Instruction::AddrSpaceCast:
3343 IsInterestingOpcode = true;
3344 }
3345 if (IsInterestingOpcode) {
3346 auto *&Insts = FI.OpcodeInstMap[I.getOpcode()];
3347 if (!Insts)
3348 Insts = new (Allocator) InstructionVectorTy();
3349 Insts->push_back(&I);
3350 }
3351 if (I.mayReadOrWriteMemory())
3352 FI.RWInsts.push_back(&I);
3353 }
3354
3355 if (F.hasFnAttribute(Attribute::AlwaysInline) &&
3356 isInlineViable(F).isSuccess())
3357 InlineableFunctions.insert(&F);
3358}
3359
3360InformationCache::FunctionInfo::~FunctionInfo() {
3361 // The instruction vectors are allocated using a BumpPtrAllocator, we need to
3362 // manually destroy them.
3363 for (auto &It : OpcodeInstMap)
3364 It.getSecond()->~InstructionVectorTy();
3365}
3366
3369 assert(A.isClosedWorldModule() && "Cannot see all indirect callees!");
3370 return IndirectlyCallableFunctions;
3371}
3372
3373std::optional<unsigned> InformationCache::getFlatAddressSpace() const {
3374 if (IsTargetGPU())
3375 return 0;
3376 return std::nullopt;
3377}
3378
3380 const AbstractAttribute &ToAA,
3381 DepClassTy DepClass) {
3382 if (DepClass == DepClassTy::NONE)
3383 return;
3384 // If we are outside of an update, thus before the actual fixpoint iteration
3385 // started (= when we create AAs), we do not track dependences because we will
3386 // put all AAs into the initial worklist anyway.
3387 if (DependenceStack.empty())
3388 return;
3389 if (FromAA.getState().isAtFixpoint())
3390 return;
3391 DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass});
3392}
3393
3394void Attributor::rememberDependences() {
3395 assert(!DependenceStack.empty() && "No dependences to remember!");
3396
3397 for (DepInfo &DI : *DependenceStack.back()) {
3398 assert((DI.DepClass == DepClassTy::REQUIRED ||
3399 DI.DepClass == DepClassTy::OPTIONAL) &&
3400 "Expected required or optional dependence (1 bit)!");
3401 auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps;
3402 DepAAs.insert(AbstractAttribute::DepTy(
3403 const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass)));
3404 }
3405}
3406
3407template <Attribute::AttrKind AK, typename AAType>
3408void Attributor::checkAndQueryIRAttr(const IRPosition &IRP, AttributeSet Attrs,
3409 bool SkipHasAttrCheck) {
3410 bool IsKnown;
3411 if (SkipHasAttrCheck || !Attrs.hasAttribute(AK))
3412 if (!Configuration.Allowed || Configuration.Allowed->count(&AAType::ID))
3413 if (!AA::hasAssumedIRAttr<AK>(*this, nullptr, IRP, DepClassTy::NONE,
3414 IsKnown))
3415 getOrCreateAAFor<AAType>(IRP);
3416}
3417
3419 assert(!F.isDeclaration());
3420
3421 if (!VisitedFunctions.insert(&F).second)
3422 return;
3423
3424 // In non-module runs we need to look at the call sites of a function to
3425 // determine if it is part of a must-tail call edge. This will influence what
3426 // attributes we can derive.
3427 InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F);
3428 if (!isModulePass() && !FI.CalledViaMustTail) {
3429 for (const Use &U : F.uses())
3430 if (const auto *CB = dyn_cast<CallBase>(U.getUser()))
3431 if (CB->isCallee(&U) && CB->isMustTailCall())
3432 FI.CalledViaMustTail = true;
3433 }
3434
3436 bool IsIPOAmendable = isFunctionIPOAmendable(F);
3437 auto Attrs = F.getAttributes();
3438 auto FnAttrs = Attrs.getFnAttrs();
3439
3440 // Check for dead BasicBlocks in every function.
3441 // We need dead instruction detection because we do not want to deal with
3442 // broken IR in which SSA rules do not apply.
3444
3445 // Every function might contain instructions that cause "undefined
3446 // behavior".
3448
3449 // Every function might be applicable for Heap-To-Stack conversion.
3452
3453 // Every function might be "must-progress".
3454 checkAndQueryIRAttr<Attribute::MustProgress, AAMustProgress>(FPos, FnAttrs);
3455
3456 // Every function might be "no-free".
3457 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(FPos, FnAttrs);
3458
3459 // Every function might be "will-return".
3460 checkAndQueryIRAttr<Attribute::WillReturn, AAWillReturn>(FPos, FnAttrs);
3461
3462 // Every function might be marked "nosync"
3463 checkAndQueryIRAttr<Attribute::NoSync, AANoSync>(FPos, FnAttrs);
3464
3465 // Everything that is visible from the outside (=function, argument, return
3466 // positions), cannot be changed if the function is not IPO amendable. We can
3467 // however analyse the code inside.
3468 if (IsIPOAmendable) {
3469
3470 // Every function can be nounwind.
3471 checkAndQueryIRAttr<Attribute::NoUnwind, AANoUnwind>(FPos, FnAttrs);
3472
3473 // Every function might be "no-return".
3474 checkAndQueryIRAttr<Attribute::NoReturn, AANoReturn>(FPos, FnAttrs);
3475
3476 // Every function might be "no-recurse".
3477 checkAndQueryIRAttr<Attribute::NoRecurse, AANoRecurse>(FPos, FnAttrs);
3478
3479 // Every function can be "non-convergent".
3480 if (Attrs.hasFnAttr(Attribute::Convergent))
3482
3483 // Every function might be "readnone/readonly/writeonly/...".
3485
3486 // Every function can be "readnone/argmemonly/inaccessiblememonly/...".
3488
3489 // Every function can track active assumptions.
3491
3492 // If we're not using a dynamic mode for float, there's nothing worthwhile
3493 // to infer. This misses the edge case denormal-fp-math="dynamic" and
3494 // denormal-fp-math-f32=something, but that likely has no real world use.
3495 DenormalMode Mode = F.getDenormalMode(APFloat::IEEEsingle());
3496 if (Mode.Input == DenormalMode::Dynamic ||
3497 Mode.Output == DenormalMode::Dynamic)
3499
3500 // Return attributes are only appropriate if the return type is non void.
3501 Type *ReturnType = F.getReturnType();
3502 if (!ReturnType->isVoidTy()) {
3504 AttributeSet RetAttrs = Attrs.getRetAttrs();
3505
3506 // Every returned value might be dead.
3508
3509 // Every function might be simplified.
3510 bool UsedAssumedInformation = false;
3511 getAssumedSimplified(RetPos, nullptr, UsedAssumedInformation,
3513
3514 // Every returned value might be marked noundef.
3515 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(RetPos, RetAttrs);
3516
3517 if (ReturnType->isPointerTy()) {
3518
3519 // Every function with pointer return type might be marked align.
3521
3522 // Every function with pointer return type might be marked nonnull.
3523 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(RetPos, RetAttrs);
3524
3525 // Every function with pointer return type might be marked noalias.
3526 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(RetPos, RetAttrs);
3527
3528 // Every function with pointer return type might be marked
3529 // dereferenceable.
3531 } else if (AttributeFuncs::isNoFPClassCompatibleType(ReturnType)) {
3533 }
3534 }
3535 }
3536
3537 for (Argument &Arg : F.args()) {
3538 IRPosition ArgPos = IRPosition::argument(Arg);
3539 auto ArgNo = Arg.getArgNo();
3540 AttributeSet ArgAttrs = Attrs.getParamAttrs(ArgNo);
3541
3542 if (!IsIPOAmendable) {
3543 if (Arg.getType()->isPointerTy())
3544 // Every argument with pointer type might be marked nofree.
3545 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(ArgPos, ArgAttrs);
3546 continue;
3547 }
3548
3549 // Every argument might be simplified. We have to go through the
3550 // Attributor interface though as outside AAs can register custom
3551 // simplification callbacks.
3552 bool UsedAssumedInformation = false;
3553 getAssumedSimplified(ArgPos, /* AA */ nullptr, UsedAssumedInformation,
3555
3556 // Every argument might be dead.
3558
3559 // Every argument might be marked noundef.
3560 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(ArgPos, ArgAttrs);
3561
3562 if (Arg.getType()->isPointerTy()) {
3563 // Every argument with pointer type might be marked nonnull.
3564 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(ArgPos, ArgAttrs);
3565
3566 // Every argument with pointer type might be marked noalias.
3567 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(ArgPos, ArgAttrs);
3568
3569 // Every argument with pointer type might be marked dereferenceable.
3571
3572 // Every argument with pointer type might be marked align.
3574
3575 // Every argument with pointer type might be marked nocapture.
3576 checkAndQueryIRAttr<Attribute::Captures, AANoCapture>(
3577 ArgPos, ArgAttrs, /*SkipHasAttrCheck=*/true);
3578
3579 // Every argument with pointer type might be marked
3580 // "readnone/readonly/writeonly/..."
3582
3583 // Every argument with pointer type might be marked nofree.
3584 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(ArgPos, ArgAttrs);
3585
3586 // Every argument with pointer type might be privatizable (or
3587 // promotable)
3589 } else if (AttributeFuncs::isNoFPClassCompatibleType(Arg.getType())) {
3591 }
3592 }
3593
3594 auto CallSitePred = [&](Instruction &I) -> bool {
3595 auto &CB = cast<CallBase>(I);
3596 IRPosition CBInstPos = IRPosition::inst(CB);
3598
3599 // Call sites might be dead if they do not have side effects and no live
3600 // users. The return value might be dead if there are no live users.
3601 getOrCreateAAFor<AAIsDead>(CBInstPos);
3602
3603 Function *Callee = dyn_cast_if_present<Function>(CB.getCalledOperand());
3604 // TODO: Even if the callee is not known now we might be able to simplify
3605 // the call/callee.
3606 if (!Callee) {
3608 return true;
3609 }
3610
3611 // Every call site can track active assumptions.
3613
3614 // Skip declarations except if annotations on their call sites were
3615 // explicitly requested.
3616 if (!AnnotateDeclarationCallSites && Callee->isDeclaration() &&
3617 !Callee->hasMetadata(LLVMContext::MD_callback))
3618 return true;
3619
3620 if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) {
3622 bool UsedAssumedInformation = false;
3623 getAssumedSimplified(CBRetPos, nullptr, UsedAssumedInformation,
3625
3626 if (AttributeFuncs::isNoFPClassCompatibleType(Callee->getReturnType()))
3628 }
3629
3630 const AttributeList &CBAttrs = CBFnPos.getAttrList();
3631 for (int I = 0, E = CB.arg_size(); I < E; ++I) {
3632
3634 AttributeSet CBArgAttrs = CBAttrs.getParamAttrs(I);
3635
3636 // Every call site argument might be dead.
3638
3639 // Call site argument might be simplified. We have to go through the
3640 // Attributor interface though as outside AAs can register custom
3641 // simplification callbacks.
3642 bool UsedAssumedInformation = false;
3643 getAssumedSimplified(CBArgPos, /* AA */ nullptr, UsedAssumedInformation,
3645
3646 // Every call site argument might be marked "noundef".
3647 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(CBArgPos, CBArgAttrs);
3648
3649 Type *ArgTy = CB.getArgOperand(I)->getType();
3650
3651 if (!ArgTy->isPointerTy()) {
3652 if (AttributeFuncs::isNoFPClassCompatibleType(ArgTy))
3654
3655 continue;
3656 }
3657
3658 // Call site argument attribute "non-null".
3659 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(CBArgPos, CBArgAttrs);
3660
3661 // Call site argument attribute "captures(none)".
3662 checkAndQueryIRAttr<Attribute::Captures, AANoCapture>(
3663 CBArgPos, CBArgAttrs, /*SkipHasAttrCheck=*/true);
3664
3665 // Call site argument attribute "no-alias".
3666 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(CBArgPos, CBArgAttrs);
3667
3668 // Call site argument attribute "dereferenceable".
3670
3671 // Call site argument attribute "align".
3672 getOrCreateAAFor<AAAlign>(CBArgPos);
3673
3674 // Call site argument attribute
3675 // "readnone/readonly/writeonly/..."
3676 if (!CBAttrs.hasParamAttr(I, Attribute::ReadNone))
3678
3679 // Call site argument attribute "nofree".
3680 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(CBArgPos, CBArgAttrs);
3681 }
3682 return true;
3683 };
3684
3685 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
3686 [[maybe_unused]] bool Success;
3687 bool UsedAssumedInformation = false;
3689 nullptr, OpcodeInstMap, CallSitePred, nullptr, nullptr,
3690 {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
3691 (unsigned)Instruction::Call},
3692 UsedAssumedInformation);
3693 assert(Success && "Expected the check call to be successful!");
3694
3695 auto LoadStorePred = [&](Instruction &I) -> bool {
3696 if (auto *LI = dyn_cast<LoadInst>(&I)) {
3697 getOrCreateAAFor<AAAlign>(IRPosition::value(*LI->getPointerOperand()));
3698 if (SimplifyAllLoads)
3700 UsedAssumedInformation, AA::Intraprocedural);
3702 IRPosition::value(*LI->getPointerOperand()));
3704 IRPosition::value(*LI->getPointerOperand()));
3705 } else {
3706 auto &SI = cast<StoreInst>(I);
3708 getAssumedSimplified(IRPosition::value(*SI.getValueOperand()), nullptr,
3709 UsedAssumedInformation, AA::Intraprocedural);
3710 getOrCreateAAFor<AAAlign>(IRPosition::value(*SI.getPointerOperand()));
3712 IRPosition::value(*SI.getPointerOperand()));
3713 }
3714 return true;
3715 };
3717 nullptr, OpcodeInstMap, LoadStorePred, nullptr, nullptr,
3718 {(unsigned)Instruction::Load, (unsigned)Instruction::Store},
3719 UsedAssumedInformation);
3720 assert(Success && "Expected the check call to be successful!");
3721
3722 // AllocaInstPredicate
3723 auto AAAllocationInfoPred = [&](Instruction &I) -> bool {
3725 return true;
3726 };
3727
3729 nullptr, OpcodeInstMap, AAAllocationInfoPred, nullptr, nullptr,
3730 {(unsigned)Instruction::Alloca}, UsedAssumedInformation);
3731 assert(Success && "Expected the check call to be successful!");
3732}
3733
3735 if (CloseWorldAssumption.getNumOccurrences())
3736 return CloseWorldAssumption;
3737 return isModulePass() && Configuration.IsClosedWorldModule;
3738}
3739
3740/// Helpers to ease debugging through output streams and print calls.
3741///
3742///{
3744 return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
3745}
3746
3748 switch (AP) {
3750 return OS << "inv";
3752 return OS << "flt";
3754 return OS << "fn_ret";
3756 return OS << "cs_ret";
3758 return OS << "fn";
3760 return OS << "cs";
3762 return OS << "arg";
3764 return OS << "cs_arg";
3765 }
3766 llvm_unreachable("Unknown attribute position!");
3767}
3768
3770 const Value &AV = Pos.getAssociatedValue();
3771 OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " ["
3772 << Pos.getAnchorValue().getName() << "@" << Pos.getCallSiteArgNo() << "]";
3773
3774 if (Pos.hasCallBaseContext())
3775 OS << "[cb_context:" << *Pos.getCallBaseContext() << "]";
3776 return OS << "}";
3777}
3778
3780 OS << "range-state(" << S.getBitWidth() << ")<";
3781 S.getKnown().print(OS);
3782 OS << " / ";
3783 S.getAssumed().print(OS);
3784 OS << ">";
3785
3786 return OS << static_cast<const AbstractState &>(S);
3787}
3788
3790 return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
3791}
3792
3794 AA.print(OS);
3795 return OS;
3796}
3797
3800 OS << "set-state(< {";
3801 if (!S.isValidState())
3802 OS << "full-set";
3803 else {
3804 for (const auto &It : S.getAssumedSet())
3805 OS << It << ", ";
3806 if (S.undefIsContained())
3807 OS << "undef ";
3808 }
3809 OS << "} >)";
3810
3811 return OS;
3812}
3813
3815 const PotentialLLVMValuesState &S) {
3816 OS << "set-state(< {";
3817 if (!S.isValidState())
3818 OS << "full-set";
3819 else {
3820 for (const auto &It : S.getAssumedSet()) {
3821 if (auto *F = dyn_cast<Function>(It.first.getValue()))
3822 OS << "@" << F->getName() << "[" << int(It.second) << "], ";
3823 else
3824 OS << *It.first.getValue() << "[" << int(It.second) << "], ";
3825 }
3826 if (S.undefIsContained())
3827 OS << "undef ";
3828 }
3829 OS << "} >)";
3830
3831 return OS;
3832}
3833
3835 OS << "[";
3836 OS << getName();
3837 OS << "] for CtxI ";
3838
3839 if (auto *I = getCtxI()) {
3840 OS << "'";
3841 I->print(OS);
3842 OS << "'";
3843 } else
3844 OS << "<<null inst>>";
3845
3846 OS << " at position " << getIRPosition() << " with state " << getAsStr(A)
3847 << '\n';
3848}
3849
3851 print(OS);
3852
3853 for (const auto &DepAA : Deps) {
3854 auto *AA = DepAA.getPointer();
3855 OS << " updates ";
3856 AA->print(OS);
3857 }
3858
3859 OS << '\n';
3860}
3861
3863 const AAPointerInfo::Access &Acc) {
3864 OS << " [" << Acc.getKind() << "] " << *Acc.getRemoteInst();
3865 if (Acc.getLocalInst() != Acc.getRemoteInst())
3866 OS << " via " << *Acc.getLocalInst();
3867 if (Acc.getContent()) {
3868 if (*Acc.getContent())
3869 OS << " [" << **Acc.getContent() << "]";
3870 else
3871 OS << " [ <unknown> ]";
3872 }
3873 return OS;
3874}
3875///}
3876
3877/// ----------------------------------------------------------------------------
3878/// Pass (Manager) Boilerplate
3879/// ----------------------------------------------------------------------------
3880
3882 SetVector<Function *> &Functions,
3883 CallGraphUpdater &CGUpdater,
3885 bool DeleteFns, bool IsModulePass) {
3886 if (Functions.empty())
3887 return false;
3888
3889 LLVM_DEBUG({
3890 dbgs() << "[Attributor] Run on module with " << Functions.size()
3891 << " functions:\n";
3892 for (Function *Fn : Functions)
3893 dbgs() << " - " << Fn->getName() << "\n";
3894 });
3895
3896 // Create an Attributor and initially empty information cache that is filled
3897 // while we identify default attribute opportunities.
3898 AttributorConfig AC(CGUpdater);
3899 AC.IsModulePass = IsModulePass;
3900 AC.DeleteFns = DeleteFns;
3901 auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
3902 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
3903 };
3904 AC.OREGetter = OREGetter;
3905 AC.PassName = DEBUG_TYPE;
3906
3907 /// Tracking callback for specialization of indirect calls.
3909 IndirectCalleeTrackingMap;
3910 if (MaxSpecializationPerCB.getNumOccurrences()) {
3911 AC.IndirectCalleeSpecializationCallback =
3912 [&](Attributor &, const AbstractAttribute &AA, CallBase &CB,
3913 Function &Callee, unsigned) {
3914 if (MaxSpecializationPerCB == 0)
3915 return false;
3916 auto &Set = IndirectCalleeTrackingMap[&CB];
3917 if (!Set)
3918 Set = std::make_unique<SmallPtrSet<Function *, 8>>();
3919 if (Set->size() >= MaxSpecializationPerCB)
3920 return Set->contains(&Callee);
3921 Set->insert(&Callee);
3922 return true;
3923 };
3924 }
3925
3926 Attributor A(Functions, InfoCache, AC);
3927
3928 // Create shallow wrappers for all functions that are not IPO amendable
3930 for (Function *F : Functions)
3931 if (!A.isFunctionIPOAmendable(*F))
3933
3934 // Internalize non-exact functions
3935 // TODO: for now we eagerly internalize functions without calculating the
3936 // cost, we need a cost interface to determine whether internalizing
3937 // a function is "beneficial"
3938 if (AllowDeepWrapper) {
3939 unsigned FunSize = Functions.size();
3940 for (unsigned u = 0; u < FunSize; u++) {
3941 Function *F = Functions[u];
3942 if (!F->isDeclaration() && !F->isDefinitionExact() && !F->use_empty() &&
3943 !GlobalValue::isInterposableLinkage(F->getLinkage())) {
3945 assert(NewF && "Could not internalize function.");
3946 Functions.insert(NewF);
3947
3948 // Update call graph
3949 CGUpdater.replaceFunctionWith(*F, *NewF);
3950 for (const Use &U : NewF->uses())
3951 if (CallBase *CB = dyn_cast<CallBase>(U.getUser())) {
3952 auto *CallerF = CB->getCaller();
3953 CGUpdater.reanalyzeFunction(*CallerF);
3954 }
3955 }
3956 }
3957 }
3958
3959 for (Function *F : Functions) {
3960 if (F->isDeclaration())
3961 continue;
3962
3963 if (F->hasExactDefinition())
3964 NumFnWithExactDefinition++;
3965 else
3966 NumFnWithoutExactDefinition++;
3967
3968 // We look at internal functions only on-demand but if any use is not a
3969 // direct call or outside the current set of analyzed functions, we have
3970 // to do it eagerly.
3971 if (F->hasLocalLinkage()) {
3972 if (llvm::all_of(F->uses(), [&Functions](const Use &U) {
3973 const auto *CB = dyn_cast<CallBase>(U.getUser());
3974 return CB && CB->isCallee(&U) &&
3975 Functions.count(const_cast<Function *>(CB->getCaller()));
3976 }))
3977 continue;
3978 }
3979
3980 // Populate the Attributor with abstract attribute opportunities in the
3981 // function and the information cache with IR information.
3982 A.identifyDefaultAbstractAttributes(*F);
3983 }
3984
3985 ChangeStatus Changed = A.run();
3986
3987 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
3988 << " functions, result: " << Changed << ".\n");
3990}
3991
3993 SetVector<Function *> &Functions,
3994 CallGraphUpdater &CGUpdater,
3996 bool IsModulePass) {
3997 if (Functions.empty())
3998 return false;
3999
4000 LLVM_DEBUG({
4001 dbgs() << "[AttributorLight] Run on module with " << Functions.size()
4002 << " functions:\n";
4003 for (Function *Fn : Functions)
4004 dbgs() << " - " << Fn->getName() << "\n";
4005 });
4006
4007 // Create an Attributor and initially empty information cache that is filled
4008 // while we identify default attribute opportunities.
4009 AttributorConfig AC(CGUpdater);
4010 AC.IsModulePass = IsModulePass;
4011 AC.DeleteFns = false;
4012 DenseSet<const char *> Allowed(
4019 AC.Allowed = &Allowed;
4020 AC.UseLiveness = false;
4021
4022 Attributor A(Functions, InfoCache, AC);
4023
4024 for (Function *F : Functions) {
4025 if (F->isDeclaration())
4026 continue;
4027
4028 if (F->hasExactDefinition())
4029 NumFnWithExactDefinition++;
4030 else
4031 NumFnWithoutExactDefinition++;
4032
4033 // We look at internal functions only on-demand but if any use is not a
4034 // direct call or outside the current set of analyzed functions, we have
4035 // to do it eagerly.
4036 if (AC.UseLiveness && F->hasLocalLinkage()) {
4037 if (llvm::all_of(F->uses(), [&Functions](const Use &U) {
4038 const auto *CB = dyn_cast<CallBase>(U.getUser());
4039 return CB && CB->isCallee(&U) &&
4040 Functions.count(const_cast<Function *>(CB->getCaller()));
4041 }))
4042 continue;
4043 }
4044
4045 // Populate the Attributor with abstract attribute opportunities in the
4046 // function and the information cache with IR information.
4047 A.identifyDefaultAbstractAttributes(*F);
4048 }
4049
4050 ChangeStatus Changed = A.run();
4051
4053 // Invalidate analyses for modified functions so that we don't have to
4054 // invalidate all analyses for all functions in this SCC.
4055 PreservedAnalyses FuncPA;
4056 // We haven't changed the CFG for modified functions.
4057 FuncPA.preserveSet<CFGAnalyses>();
4058 for (Function *Changed : A.getModifiedFunctions()) {
4059 FAM.invalidate(*Changed, FuncPA);
4060 // Also invalidate any direct callers of changed functions since analyses
4061 // may care about attributes of direct callees. For example, MemorySSA
4062 // cares about whether or not a call's callee modifies memory and queries
4063 // that through function attributes.
4064 for (auto *U : Changed->users()) {
4065 if (auto *Call = dyn_cast<CallBase>(U)) {
4066 if (Call->getCalledFunction() == Changed)
4067 FAM.invalidate(*Call->getFunction(), FuncPA);
4068 }
4069 }
4070 }
4071 }
4072 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
4073 << " functions, result: " << Changed << ".\n");
4075}
4076
4077void AADepGraph::viewGraph() { llvm::ViewGraph(this, "Dependency Graph"); }
4078
4080 static std::atomic<int> CallTimes;
4081 std::string Prefix;
4082
4083 if (!DepGraphDotFileNamePrefix.empty())
4085 else
4086 Prefix = "dep_graph";
4087 std::string Filename =
4088 Prefix + "_" + std::to_string(CallTimes.load()) + ".dot";
4089
4090 outs() << "Dependency graph dump to " << Filename << ".\n";
4091
4092 std::error_code EC;
4093
4095 if (!EC)
4096 llvm::WriteGraph(File, this);
4097
4098 CallTimes++;
4099}
4100
4102 for (auto DepAA : SyntheticRoot.Deps)
4103 cast<AbstractAttribute>(DepAA.getPointer())->printWithDeps(outs());
4104}
4105
4109 AnalysisGetter AG(FAM);
4110
4111 SetVector<Function *> Functions;
4112 Functions.reserve(M.size());
4113 for (Function &F : M)
4114 Functions.insert(&F);
4115
4116 CallGraphUpdater CGUpdater;
4117 BumpPtrAllocator Allocator;
4118 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
4119 if (runAttributorOnFunctions(InfoCache, Functions, CGUpdater, FAM,
4120 /* DeleteFns */ true, /* IsModulePass */ true)) {
4121 // FIXME: Think about passes we will preserve and add them here.
4122 return PreservedAnalyses::none();
4123 }
4124 return PreservedAnalyses::all();
4125}
4126
4129 LazyCallGraph &CG,
4130 CGSCCUpdateResult &UR) {
4132 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
4133 AnalysisGetter AG(FAM);
4134
4135 SetVector<Function *> Functions;
4136 Functions.reserve(C.size());
4137 for (LazyCallGraph::Node &N : C)
4138 Functions.insert(&N.getFunction());
4139
4140 if (Functions.empty())
4141 return PreservedAnalyses::all();
4142
4143 Module &M = *Functions.back()->getParent();
4144 CallGraphUpdater CGUpdater;
4145 CGUpdater.initialize(CG, C, AM, UR);
4146 BumpPtrAllocator Allocator;
4147 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
4148 if (runAttributorOnFunctions(InfoCache, Functions, CGUpdater, FAM,
4149 /* DeleteFns */ false,
4150 /* IsModulePass */ false)) {
4151 // FIXME: Think about passes we will preserve and add them here.
4154 return PA;
4155 }
4156 return PreservedAnalyses::all();
4157}
4158
4163 AnalysisGetter AG(FAM, /* CachedOnly */ true);
4164
4165 SetVector<Function *> Functions;
4166 Functions.reserve(M.size());
4167 for (Function &F : M)
4168 Functions.insert(&F);
4169
4170 CallGraphUpdater CGUpdater;
4171 BumpPtrAllocator Allocator;
4172 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
4173 if (runAttributorLightOnFunctions(InfoCache, Functions, CGUpdater, FAM,
4174 /* IsModulePass */ true)) {
4176 // We have not added or removed functions.
4178 // We already invalidated all relevant function analyses above.
4180 return PA;
4181 }
4182 return PreservedAnalyses::all();
4183}
4184
4187 LazyCallGraph &CG,
4188 CGSCCUpdateResult &UR) {
4190 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
4191 AnalysisGetter AG(FAM);
4192
4193 SetVector<Function *> Functions;
4194 for (LazyCallGraph::Node &N : C)
4195 Functions.insert(&N.getFunction());
4196
4197 if (Functions.empty())
4198 return PreservedAnalyses::all();
4199
4200 Module &M = *Functions.back()->getParent();
4201 CallGraphUpdater CGUpdater;
4202 CGUpdater.initialize(CG, C, AM, UR);
4203 BumpPtrAllocator Allocator;
4204 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
4205 if (runAttributorLightOnFunctions(InfoCache, Functions, CGUpdater, FAM,
4206 /* IsModulePass */ false)) {
4208 // We have not added or removed functions.
4210 // We already invalidated all relevant function analyses above.
4212 return PA;
4213 }
4214 return PreservedAnalyses::all();
4215}
4216namespace llvm {
4217
4234
4235template <>
4237 static NodeRef getEntryNode(AADepGraph *DG) { return DG->GetEntryNode(); }
4238
4241
4242 static nodes_iterator nodes_begin(AADepGraph *DG) { return DG->begin(); }
4243
4244 static nodes_iterator nodes_end(AADepGraph *DG) { return DG->end(); }
4245};
4246
4247template <> struct DOTGraphTraits<AADepGraph *> : public DefaultDOTGraphTraits {
4249
4250 static std::string getNodeLabel(const AADepGraphNode *Node,
4251 const AADepGraph *DG) {
4252 std::string AAString;
4253 raw_string_ostream O(AAString);
4254 Node->print(O);
4255 return AAString;
4256 }
4257};
4258
4259} // 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
#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:2610
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:2545
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
Return if this abstract state is in a valid state.
const SetTy & getAssumedSet() const
Return this set.