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