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