LLVM 22.0.0git
InferAlignment.cpp
Go to the documentation of this file.
1//===- InferAlignment.cpp -------------------------------------------------===//
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// Infer alignment for load, stores and other memory operations based on
10// trailing zero known bits information.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
19#include "llvm/IR/Instruction.h"
26
27using namespace llvm;
28using namespace llvm::PatternMatch;
29
31 const DataLayout &DL, Instruction *I,
32 function_ref<Align(Value *PtrOp, Align OldAlign, Align PrefAlign)> Fn) {
33
34 if (auto *PtrOp = getLoadStorePointerOperand(I)) {
35 Align OldAlign = getLoadStoreAlignment(I);
36 Align PrefAlign = DL.getPrefTypeAlign(getLoadStoreType(I));
37
38 Align NewAlign = Fn(PtrOp, OldAlign, PrefAlign);
39 if (NewAlign > OldAlign) {
40 setLoadStoreAlignment(I, NewAlign);
41 return true;
42 }
43 }
44
45 Value *PtrOp;
46 const APInt *Const;
47 if (match(I, m_And(m_PtrToIntOrAddr(m_Value(PtrOp)), m_APInt(Const)))) {
48 Align ActualAlign = Fn(PtrOp, Align(1), Align(1));
49 if (Const->ult(ActualAlign.value())) {
50 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
51 return true;
52 }
53 if (Const->uge(
54 APInt::getBitsSetFrom(Const->getBitWidth(), Log2(ActualAlign)))) {
55 I->replaceAllUsesWith(I->getOperand(0));
56 return true;
57 }
58 }
59
61 if (!II)
62 return false;
63
64 // TODO: Handle more memory intrinsics.
65 switch (II->getIntrinsicID()) {
66 case Intrinsic::masked_load:
67 case Intrinsic::masked_store: {
68 unsigned PtrOpIdx = II->getIntrinsicID() == Intrinsic::masked_load ? 0 : 1;
69 Value *PtrOp = II->getArgOperand(PtrOpIdx);
70 Type *Type = II->getIntrinsicID() == Intrinsic::masked_load
71 ? II->getType()
72 : II->getArgOperand(0)->getType();
73
74 Align OldAlign = II->getParamAlign(PtrOpIdx).valueOrOne();
75 Align PrefAlign = DL.getPrefTypeAlign(Type);
76 Align NewAlign = Fn(PtrOp, OldAlign, PrefAlign);
77 if (NewAlign <= OldAlign)
78 return false;
79
80 II->addParamAttr(PtrOpIdx,
81 Attribute::getWithAlignment(II->getContext(), NewAlign));
82 return true;
83 }
84 default:
85 return false;
86 }
87}
88
90 const DataLayout &DL = F.getDataLayout();
91 bool Changed = false;
92
93 // Enforce preferred type alignment if possible. We do this as a separate
94 // pass first, because it may improve the alignments we infer below.
95 for (BasicBlock &BB : F) {
96 for (Instruction &I : BB) {
98 DL, &I, [&](Value *PtrOp, Align OldAlign, Align PrefAlign) {
99 if (PrefAlign > OldAlign)
100 return std::max(OldAlign,
101 tryEnforceAlignment(PtrOp, PrefAlign, DL));
102 return OldAlign;
103 });
104 }
105 }
106
107 // Compute alignment from known bits.
108 auto InferFromKnownBits = [&](Instruction &I, Value *PtrOp) {
109 KnownBits Known = computeKnownBits(PtrOp, DL, &AC, &I, &DT);
110 unsigned TrailZ =
112 return Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));
113 };
114
115 // Propagate alignment between loads and stores that originate from the
116 // same base pointer.
117 DenseMap<Value *, Align> BestBasePointerAligns;
118 auto InferFromBasePointer = [&](Value *PtrOp, Align LoadStoreAlign) {
119 APInt OffsetFromBase(DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
120 PtrOp = PtrOp->stripAndAccumulateConstantOffsets(DL, OffsetFromBase, true);
121 // Derive the base pointer alignment from the load/store alignment
122 // and the offset from the base pointer.
123 Align BasePointerAlign =
124 commonAlignment(LoadStoreAlign, OffsetFromBase.getLimitedValue());
125
126 auto [It, Inserted] =
127 BestBasePointerAligns.try_emplace(PtrOp, BasePointerAlign);
128 if (!Inserted) {
129 // If the stored base pointer alignment is better than the
130 // base pointer alignment we derived, we may be able to use it
131 // to improve the load/store alignment. If not, store the
132 // improved base pointer alignment for future iterations.
133 if (It->second > BasePointerAlign) {
134 Align BetterLoadStoreAlign =
135 commonAlignment(It->second, OffsetFromBase.getLimitedValue());
136 return BetterLoadStoreAlign;
137 }
138 It->second = BasePointerAlign;
139 }
140 return LoadStoreAlign;
141 };
142
143 for (BasicBlock &BB : F) {
144 // We need to reset the map for each block because alignment information
145 // can only be propagated from instruction A to B if A dominates B.
146 // This is because control flow (and exception throwing) could be dependent
147 // on the address (and its alignment) at runtime. Some sort of dominator
148 // tree approach could be better, but doing a simple forward pass through a
149 // single basic block is correct too.
150 BestBasePointerAligns.clear();
151
152 for (Instruction &I : BB) {
154 DL, &I, [&](Value *PtrOp, Align OldAlign, Align PrefAlign) {
155 return std::max(InferFromKnownBits(I, PtrOp),
156 InferFromBasePointer(PtrOp, OldAlign));
157 });
158 }
159 }
160
161 return Changed;
162}
163
168 inferAlignment(F, AC, DT);
169 // Changes to alignment shouldn't invalidated analyses.
170 return PreservedAnalyses::all();
171}
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool tryToImproveAlign(const DataLayout &DL, Instruction *I, function_ref< Align(Value *PtrOp, Align OldAlign, Align PrefAlign)> Fn)
bool inferAlignment(Function &F, AssumptionCache &AC, DominatorTree &DT)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:476
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:287
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
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
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:256
Analysis pass which computes a DominatorTree.
Definition Dominators.h:283
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
A wrapper class for inspecting calls to intrinsic functions.
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
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
Definition Value.h:829
An efficient, type-erasing, non-owning reference to a callable.
Changed
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI Align tryEnforceAlignment(Value *V, Align PrefAlign, const DataLayout &DL)
If the specified pointer points to an object that we control, try to modify the object's alignment to...
Definition Local.cpp:1517
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
void setLoadStoreAlignment(Value *I, Align NewAlign)
A helper function that set the alignment of load or store instruction.
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:242
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44