LLVM 20.0.0git
MoveAutoInit.cpp
Go to the documentation of this file.
1//===-- MoveAutoInit.cpp - move auto-init inst closer to their use site----===//
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 pass moves instruction maked as auto-init closer to the basic block that
10// use it, eventually removing it from some control path of the function.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/Statistic.h"
20#include "llvm/IR/DebugInfo.h"
21#include "llvm/IR/Dominators.h"
26
27using namespace llvm;
28
29#define DEBUG_TYPE "move-auto-init"
30
31STATISTIC(NumMoved, "Number of instructions moved");
32
34 "move-auto-init-threshold", cl::Hidden, cl::init(128),
35 cl::desc("Maximum instructions to analyze per moved initialization"));
36
37static bool hasAutoInitMetadata(const Instruction &I) {
38 return I.hasMetadata(LLVMContext::MD_annotation) &&
39 any_of(I.getMetadata(LLVMContext::MD_annotation)->operands(),
40 [](const MDOperand &Op) { return Op.equalsStr("auto-init"); });
41}
42
43static std::optional<MemoryLocation> writeToAlloca(const Instruction &I) {
45 if (auto *MI = dyn_cast<MemIntrinsic>(&I))
47 else if (auto *SI = dyn_cast<StoreInst>(&I))
49 else
50 return std::nullopt;
51
52 if (isa<AllocaInst>(getUnderlyingObject(ML.Ptr)))
53 return ML;
54 else
55 return {};
56}
57
58/// Finds a BasicBlock in the CFG where instruction `I` can be moved to while
59/// not changing the Memory SSA ordering and being guarded by at least one
60/// condition.
62 DominatorTree &DT, MemorySSA &MSSA) {
63 BasicBlock *CurrentDominator = nullptr;
64 MemoryUseOrDef &IMA = *MSSA.getMemoryAccess(I);
65 BatchAAResults AA(MSSA.getAA());
66
68
69 auto AsMemoryAccess = [](User *U) { return cast<MemoryAccess>(U); };
70 SmallVector<MemoryAccess *> WorkList(map_range(IMA.users(), AsMemoryAccess));
71
72 while (!WorkList.empty()) {
73 MemoryAccess *MA = WorkList.pop_back_val();
74 if (!Visited.insert(MA).second)
75 continue;
76
77 if (Visited.size() > MoveAutoInitThreshold)
78 return nullptr;
79
80 bool FoundClobberingUser = false;
81 if (auto *M = dyn_cast<MemoryUseOrDef>(MA)) {
82 Instruction *MI = M->getMemoryInst();
83
84 // If this memory instruction may not clobber `I`, we can skip it.
85 // LifetimeEnd is a valid user, but we do not want it in the user
86 // dominator.
87 if (AA.getModRefInfo(MI, ML) != ModRefInfo::NoModRef &&
88 !MI->isLifetimeStartOrEnd() && MI != I) {
89 FoundClobberingUser = true;
90 CurrentDominator = CurrentDominator
91 ? DT.findNearestCommonDominator(CurrentDominator,
92 MI->getParent())
93 : MI->getParent();
94 }
95 }
96 if (!FoundClobberingUser) {
97 auto UsersAsMemoryAccesses = map_range(MA->users(), AsMemoryAccess);
98 append_range(WorkList, UsersAsMemoryAccesses);
99 }
100 }
101 return CurrentDominator;
102}
103
105 BasicBlock &EntryBB = F.getEntryBlock();
107
108 //
109 // Compute movable instructions.
110 //
111 for (Instruction &I : EntryBB) {
113 continue;
114
115 std::optional<MemoryLocation> ML = writeToAlloca(I);
116 if (!ML)
117 continue;
118
119 if (I.isVolatile())
120 continue;
121
122 BasicBlock *UsersDominator = usersDominator(ML.value(), &I, DT, MSSA);
123 if (!UsersDominator)
124 continue;
125
126 if (UsersDominator == &EntryBB)
127 continue;
128
129 // Traverse the CFG to detect cycles `UsersDominator` would be part of.
130 SmallPtrSet<BasicBlock *, 8> TransitiveSuccessors;
131 SmallVector<BasicBlock *> WorkList(successors(UsersDominator));
132 bool HasCycle = false;
133 while (!WorkList.empty()) {
134 BasicBlock *CurrBB = WorkList.pop_back_val();
135 if (CurrBB == UsersDominator)
136 // No early exit because we want to compute the full set of transitive
137 // successors.
138 HasCycle = true;
139 for (BasicBlock *Successor : successors(CurrBB)) {
140 if (!TransitiveSuccessors.insert(Successor).second)
141 continue;
142 WorkList.push_back(Successor);
143 }
144 }
145
146 // Don't insert if that could create multiple execution of I,
147 // but we can insert it in the non back-edge predecessors, if it exists.
148 if (HasCycle) {
149 BasicBlock *UsersDominatorHead = UsersDominator;
150 while (BasicBlock *UniquePredecessor =
151 UsersDominatorHead->getUniquePredecessor())
152 UsersDominatorHead = UniquePredecessor;
153
154 if (UsersDominatorHead == &EntryBB)
155 continue;
156
157 BasicBlock *DominatingPredecessor = nullptr;
158 for (BasicBlock *Pred : predecessors(UsersDominatorHead)) {
159 // If one of the predecessor of the dominator also transitively is a
160 // successor, moving to the dominator would do the inverse of loop
161 // hoisting, and we don't want that.
162 if (TransitiveSuccessors.count(Pred))
163 continue;
164
165 if (!DT.isReachableFromEntry(Pred))
166 continue;
167
168 DominatingPredecessor =
169 DominatingPredecessor
170 ? DT.findNearestCommonDominator(DominatingPredecessor, Pred)
171 : Pred;
172 }
173
174 if (!DominatingPredecessor || DominatingPredecessor == &EntryBB)
175 continue;
176
177 UsersDominator = DominatingPredecessor;
178 }
179
180 // CatchSwitchInst blocks can only have one instruction, so they are not
181 // good candidates for insertion.
182 while (isa<CatchSwitchInst>(UsersDominator->getFirstNonPHI())) {
183 for (BasicBlock *Pred : predecessors(UsersDominator))
184 if (DT.isReachableFromEntry(Pred))
185 UsersDominator = DT.findNearestCommonDominator(UsersDominator, Pred);
186 }
187
188 // We finally found a place where I can be moved while not introducing extra
189 // execution, and guarded by at least one condition.
190 if (UsersDominator != &EntryBB)
191 JobList.emplace_back(&I, UsersDominator);
192 }
193
194 //
195 // Perform the actual substitution.
196 //
197 if (JobList.empty())
198 return false;
199
200 MemorySSAUpdater MSSAU(&MSSA);
201
202 // Reverse insertion to respect relative order between instructions:
203 // if two instructions are moved from the same BB to the same BB, we insert
204 // the second one in the front, then the first on top of it.
205 for (auto &Job : reverse(JobList)) {
206 Job.first->moveBefore(*Job.second, Job.second->getFirstInsertionPt());
207 MSSAU.moveToPlace(MSSA.getMemoryAccess(Job.first), Job.first->getParent(),
208 MemorySSA::InsertionPlace::Beginning);
209 }
210
211 if (VerifyMemorySSA)
212 MSSA.verifyMemorySSA();
213
214 NumMoved += JobList.size();
215
216 return true;
217}
218
221
222 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
223 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
224 if (!runMoveAutoInit(F, DT, MSSA))
225 return PreservedAnalyses::all();
226
231 return PA;
232}
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
static cl::opt< unsigned > MoveAutoInitThreshold("move-auto-init-threshold", cl::Hidden, cl::init(128), cl::desc("Maximum instructions to analyze per moved initialization"))
static bool runMoveAutoInit(Function &F, DominatorTree &DT, MemorySSA &MSSA)
static BasicBlock * usersDominator(const MemoryLocation &ML, Instruction *I, DominatorTree &DT, MemorySSA &MSSA)
Finds a BasicBlock in the CFG where instruction I can be moved to while not changing the Memory SSA o...
static bool hasAutoInitMetadata(const Instruction &I)
static std::optional< MemoryLocation > writeToAlloca(const Instruction &I)
This file contains some templates that are useful if you are working with the STL at all.
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:166
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:367
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:467
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
This class represents an Operation in the Expression.
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
Definition: Dominators.cpp:344
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:891
Representation for a specific memory location.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
An analysis that produces MemorySSA for a function.
Definition: MemorySSA.h:928
void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:701
AliasAnalysis & getAA()
Definition: MemorySSA.h:799
void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
Definition: MemorySSA.cpp:1905
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition: MemorySSA.h:719
Class that has the common methods + fields of memory uses/defs.
Definition: MemorySSA.h:249
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:146
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:131
size_type size() const
Definition: SmallPtrSet.h:94
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:452
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:384
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:937
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
iterator_range< user_iterator > users()
Definition: Value.h:421
const ParentTy * getParent() const
Definition: ilist_node.h:32
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto successors(const MachineBasicBlock *BB)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2115
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
auto map_range(ContainerTy &&C, FuncTy F)
Definition: STLExtras.h:377
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:1746
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition: MemorySSA.cpp:84
auto predecessors(const MachineBasicBlock *BB)