LLVM 24.0.0git
AssumeBundleBuilder.cpp
Go to the documentation of this file.
1//===- AssumeBundleBuilder.cpp - tools to preserve informations -*- C++ -*-===//
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
11#include "llvm/ADT/MapVector.h"
12#include "llvm/ADT/Statistic.h"
16#include "llvm/IR/Dominators.h"
17#include "llvm/IR/Function.h"
20#include "llvm/IR/Module.h"
21#include "llvm/IR/Operator.h"
25
26using namespace llvm;
27
28namespace llvm {
30 "enable-knowledge-retention", cl::init(false), cl::Hidden,
32 "enable preservation of attributes throughout code transformation"));
33} // namespace llvm
34
35#define DEBUG_TYPE "assume-builder"
36
37STATISTIC(NumAssumeBuilt, "Number of assume built by the assume builder");
38STATISTIC(NumBundlesInAssumes, "Total number of Bundles in the assume built");
39
40DEBUG_COUNTER(BuildAssumeCounter, "assume-builder-counter",
41 "Controls which assumes gets created");
42
43namespace {
44
45bool isUsefullToPreserve(Attribute::AttrKind Kind) {
46 switch (Kind) {
47 case Attribute::NonNull:
48 case Attribute::NoUndef:
49 case Attribute::Alignment:
50 case Attribute::Dereferenceable:
51 case Attribute::DereferenceableOrNull:
52 case Attribute::Cold:
53 return true;
54 default:
55 return false;
56 }
57}
58
59/// This function will try to transform the given knowledge into a more
60/// canonical one. the canonical knowledge maybe the given one.
61RetainedKnowledge canonicalizedKnowledge(RetainedKnowledge RK,
62 const DataLayout &DL) {
63 switch (RK.AttrKind) {
64 default:
65 return RK;
66 case Attribute::NonNull:
68 return RK;
69 case Attribute::Alignment: {
70 Value *V = RK.WasOn->stripInBoundsOffsets([&](const Value *Strip) {
71 if (auto *GEP = dyn_cast<GEPOperator>(Strip))
72 RK.ArgValue =
73 MinAlign(RK.ArgValue, GEP->getMaxPreservedAlignment(DL).value());
74 });
75 RK.WasOn = V;
76 return RK;
77 }
78 case Attribute::Dereferenceable:
79 case Attribute::DereferenceableOrNull: {
80 int64_t Offset = 0;
82 /*AllowNonInBounds*/ false);
83 if (Offset < 0)
84 return RK;
85 RK.ArgValue = RK.ArgValue + Offset;
86 RK.WasOn = V;
87 }
88 }
89 return RK;
90}
91
92/// This class contain all knowledge that have been gather while building an
93/// llvm.assume and the function to manipulate it.
94struct AssumeBuilderState {
95 Module *M;
96
97 using MapKey = std::pair<Value *, Attribute::AttrKind>;
98 SmallMapVector<MapKey, uint64_t, 8> AssumedKnowledgeMap;
99 Instruction *InstBeingModified = nullptr;
100 AssumptionCache* AC = nullptr;
101 DominatorTree* DT = nullptr;
102
103 AssumeBuilderState(Module *M, Instruction *I = nullptr,
104 AssumptionCache *AC = nullptr, DominatorTree *DT = nullptr)
105 : M(M), InstBeingModified(I), AC(AC), DT(DT) {}
106
107 bool tryToPreserveWithoutAddingAssume(RetainedKnowledge RK) {
108 if (!InstBeingModified || !RK.WasOn || !AC)
109 return false;
110 bool HasBeenPreserved = false;
111 Use* ToUpdate = nullptr;
113 RK.WasOn, {RK.AttrKind}, *AC,
114 [&](RetainedKnowledge RKOther, Instruction *Assume,
115 const CallInst::BundleOpInfo *Bundle) {
116 if (!isValidAssumeForContext(Assume, InstBeingModified, DT))
117 return false;
118 if (RKOther.ArgValue >= RK.ArgValue) {
119 HasBeenPreserved = true;
120 return true;
121 } else if (isValidAssumeForContext(InstBeingModified, Assume, DT)) {
122 HasBeenPreserved = true;
123 IntrinsicInst *Intr = cast<IntrinsicInst>(Assume);
124 ToUpdate = &Intr->op_begin()[Bundle->Begin + ABA_Argument];
125 return true;
126 }
127 return false;
128 });
129 if (ToUpdate)
130 ToUpdate->set(
131 ConstantInt::get(Type::getInt64Ty(M->getContext()), RK.ArgValue));
132 return HasBeenPreserved;
133 }
134
135 bool isKnowledgeWorthPreserving(RetainedKnowledge RK) {
136 if (!RK)
137 return false;
138 if (!RK.WasOn)
139 return true;
140 if (RK.WasOn->getType()->isPointerTy()) {
141 Value *UnderlyingPtr = getUnderlyingObject(RK.WasOn);
142 if (isa<AllocaInst>(UnderlyingPtr) || isa<GlobalValue>(UnderlyingPtr))
143 return false;
144 }
145 if (auto *Arg = dyn_cast<Argument>(RK.WasOn)) {
146 if (Arg->hasAttribute(RK.AttrKind) &&
148 Arg->getAttribute(RK.AttrKind).getValueAsInt() >= RK.ArgValue))
149 return false;
150 return true;
151 }
152 if (auto *Inst = dyn_cast<Instruction>(RK.WasOn))
154 if (RK.WasOn->use_empty())
155 return false;
156 Use *SingleUse = RK.WasOn->getSingleUndroppableUse();
157 if (SingleUse && SingleUse->getUser() == InstBeingModified)
158 return false;
159 }
160 return true;
161 }
162
163 void addKnowledge(RetainedKnowledge RK) {
164 RK = canonicalizedKnowledge(RK, M->getDataLayout());
165
166 if (!isKnowledgeWorthPreserving(RK))
167 return;
168
169 if (tryToPreserveWithoutAddingAssume(RK))
170 return;
171 MapKey Key{RK.WasOn, RK.AttrKind};
172 auto [Lookup, Inserted] = AssumedKnowledgeMap.try_emplace(Key, RK.ArgValue);
173 if (Inserted)
174 return;
175 assert(((Lookup->second == 0 && RK.ArgValue == 0) ||
176 (Lookup->second != 0 && RK.ArgValue != 0)) &&
177 "inconsistent argument value");
178
179 /// This is only desirable because for all attributes taking an argument
180 /// higher is better.
181 Lookup->second = std::max(Lookup->second, RK.ArgValue);
182 }
183
184 void addAttribute(Attribute Attr, Value *WasOn) {
185 if (Attr.isTypeAttribute() || Attr.isStringAttribute() ||
186 !isUsefullToPreserve(Attr.getKindAsEnum()))
187 return;
188 uint64_t AttrArg = 0;
189 if (Attr.isIntAttribute())
190 AttrArg = Attr.getValueAsInt();
191 addKnowledge({Attr.getKindAsEnum(), AttrArg, WasOn});
192 }
193
194 void addCall(const CallBase *Call) {
195 auto addAttrList = [&](AttributeList AttrList, unsigned NumArgs) {
196 for (unsigned Idx = 0; Idx < NumArgs; Idx++)
197 for (Attribute Attr : AttrList.getParamAttrs(Idx)) {
198 bool IsPoisonAttr = Attr.hasAttribute(Attribute::NonNull) ||
199 Attr.hasAttribute(Attribute::Alignment);
200 if (!IsPoisonAttr || Call->isPassingUndefUB(Idx))
201 addAttribute(Attr, Call->getArgOperand(Idx));
202 }
203 for (Attribute Attr : AttrList.getFnAttrs())
204 addAttribute(Attr, nullptr);
205 };
206 addAttrList(Call->getAttributes(), Call->arg_size());
207 if (Function *Fn = Call->getCalledFunction())
208 addAttrList(Fn->getAttributes(), Fn->arg_size());
209 }
210
211 AssumeInst *build() {
212 if (AssumedKnowledgeMap.empty())
213 return nullptr;
214 if (!DebugCounter::shouldExecute(BuildAssumeCounter))
215 return nullptr;
216 Function *FnAssume =
217 Intrinsic::getOrInsertDeclaration(M, Intrinsic::assume);
218 LLVMContext &C = M->getContext();
220 for (auto &MapElem : AssumedKnowledgeMap) {
222 if (MapElem.first.first)
223 Args.push_back(MapElem.first.first);
224
225 /// This is only valid because for all attribute that currently exist a
226 /// value of 0 is useless. and should not be preserved.
227 if (MapElem.second)
228 Args.push_back(ConstantInt::get(Type::getInt64Ty(M->getContext()),
229 MapElem.second));
231 std::string(Attribute::getNameFromAttrKind(MapElem.first.second)),
232 Args));
233 NumBundlesInAssumes++;
234 }
235 NumAssumeBuilt++;
237 FnAssume, ArrayRef<Value *>({ConstantInt::getTrue(C)}), OpBundle));
238 }
239
240 void addAccessedPtr(Instruction *MemInst, Value *Pointer, Type *AccType,
241 MaybeAlign MA) {
242 unsigned DerefSize = MemInst->getModule()
243 ->getDataLayout()
244 .getTypeStoreSize(AccType)
246 if (DerefSize != 0) {
247 addKnowledge({Attribute::Dereferenceable, DerefSize, Pointer});
248 if (!NullPointerIsDefined(MemInst->getFunction(),
249 Pointer->getType()->getPointerAddressSpace()))
250 addKnowledge({Attribute::NonNull, 0u, Pointer});
251 }
252 if (MA.valueOrOne() > 1)
253 addKnowledge({Attribute::Alignment, MA.valueOrOne().value(), Pointer});
254 }
255
256 void addInstruction(Instruction *I) {
257 if (auto *Call = dyn_cast<CallBase>(I))
258 return addCall(Call);
259 if (auto *Load = dyn_cast<LoadInst>(I))
260 return addAccessedPtr(I, Load->getPointerOperand(), Load->getType(),
261 Load->getAlign());
262 if (auto *Store = dyn_cast<StoreInst>(I))
263 return addAccessedPtr(I, Store->getPointerOperand(),
264 Store->getValueOperand()->getType(),
265 Store->getAlign());
266 if (auto *RMW = dyn_cast<AtomicRMWInst>(I))
267 return addAccessedPtr(I, RMW->getPointerOperand(),
268 RMW->getValOperand()->getType(), RMW->getAlign());
269 if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(I))
270 return addAccessedPtr(I, CmpXchg->getPointerOperand(),
271 CmpXchg->getCompareOperand()->getType(),
272 CmpXchg->getAlign());
273 // TODO: Maybe we should look around and merge with other llvm.assume.
274 }
275};
276
277} // namespace
278
281 return nullptr;
282 AssumeBuilderState Builder(I->getModule());
283 Builder.addInstruction(I);
284 return Builder.build();
285}
286
288 DominatorTree *DT) {
289 if (!EnableKnowledgeRetention || I->isTerminator())
290 return false;
291 bool Changed = false;
292 AssumeBuilderState Builder(I->getModule(), I, AC, DT);
293 Builder.addInstruction(I);
294 if (auto *Intr = Builder.build()) {
295 Intr->insertBefore(I->getIterator());
296 Changed = true;
297 if (AC)
298 AC->registerAssumption(Intr);
299 }
300 return Changed;
301}
302
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
if(PassOpts->AAPipeline)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:107
LLVM_ABI bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
LLVM_ABI bool 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 Attribute::AttrKind getKindAsEnum() const
Return the attribute's kind as an enum (Attribute::AttrKind).
static LLVM_ABI StringRef getNameFromAttrKind(Attribute::AttrKind AttrKind)
LLVM_ABI bool isTypeAttribute() const
Return true if the attribute is a type attribute.
static bool isIntAttrKind(AttrKind Kind)
Definition Attributes.h:143
LLVM_ABI bool hasAttribute(AttrKind Val) const
Return true if the attribute is present.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:126
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...
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:579
static bool shouldExecute(CounterInfo &Counter)
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
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:119
bool empty() const
Definition MapVector.h:80
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition Module.h:325
A container for an operand bundle being viewed as a set of values rather than a set of uses.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
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
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_iterator op_begin()
Definition User.h:259
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 const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:823
LLVM_ABI Use * getSingleUndroppableUse()
Return true if there is exactly one use of this value that cannot be dropped.
Definition Value.cpp:168
bool use_empty() const
Definition Value.h:348
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
initializer< Ty > init(const Ty &Val)
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
Definition IRSymtab.cpp:348
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > EnableKnowledgeRetention
@ Offset
Definition DWP.cpp:577
LLVM_ABI RetainedKnowledge getKnowledgeForValue(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, function_ref< bool(RetainedKnowledge, Instruction *, const CallBase::BundleOpInfo *)> Filter=[](auto...) { return true;})
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and it match...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:352
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
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 bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:415
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool salvageKnowledge(Instruction *I, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Calls BuildAssumeFromInst and if the resulting llvm.assume is valid insert if before I.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI AssumeInst * buildAssumeFromInst(Instruction *I)
Build a call to llvm.assume to preserve informations that can be derived from the given instruction.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
uint32_t Begin
The index in the Use& vector where operands for this operand bundle starts.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135
Represent one information held inside an operand bundle of an llvm.assume.
Attribute::AttrKind AttrKind