LLVM 23.0.0git
InlineAsmPrepare.cpp
Go to the documentation of this file.
1//===-- InlineAsmPrepare - Prepare inline asm for code generation ---------===//
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 lowers inline asm calls in LLVM IR in order to to assist
10// SelectionDAG's codegen.
11//
12// CallBrInst:
13//
14// Assists in inserting register copies for the output values of a callbr
15// along the edges leading to the indirect target blocks. Though the output
16// SSA value is defined by the callbr instruction itself in the IR
17// representation, the value cannot be copied to the appropriate virtual
18// registers prior to jumping to an indirect label, since the jump occurs
19// within the user-provided assembly blob.
20//
21// Instead, those copies must occur separately at the beginning of each
22// indirect target. That requires that we create a separate SSA definition in
23// each of them (via llvm.callbr.landingpad), and may require splitting
24// critical edges so we have a location to place the intrinsic. Finally, we
25// remap users of the original callbr output SSA value to instead point to
26// the appropriate llvm.callbr.landingpad value.
27//
28// Ideally, this could be done inside SelectionDAG, or in the
29// MachineInstruction representation, without the use of an IR-level
30// intrinsic. But, within the current framework, it’s simpler to implement
31// as an IR pass. (If support for callbr in GlobalISel is implemented, it’s
32// worth considering whether this is still required.)
33//
34//===----------------------------------------------------------------------===//
35
37#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/iterator.h"
41#include "llvm/Analysis/CFG.h"
42#include "llvm/CodeGen/Passes.h"
43#include "llvm/IR/BasicBlock.h"
44#include "llvm/IR/Dominators.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/IRBuilder.h"
49#include "llvm/IR/Intrinsics.h"
51#include "llvm/Pass.h"
54
55using namespace llvm;
56
57#define DEBUG_TYPE "inline-asm-prepare"
58
59namespace {
60
61class InlineAsmPrepare : public FunctionPass {
62public:
63 InlineAsmPrepare() : FunctionPass(ID) {}
64
65 void getAnalysisUsage(AnalysisUsage &AU) const override {
67 }
68 bool runOnFunction(Function &F) override;
69
70 static char ID;
71};
72
73char InlineAsmPrepare::ID = 0;
74
75} // end anonymous namespace
76
77INITIALIZE_PASS_BEGIN(InlineAsmPrepare, "inline-asm-prepare",
78 "Prepare inline asm insts", false, false)
80INITIALIZE_PASS_END(InlineAsmPrepare, "inline-asm-prepare",
81 "Prepare inline asm insts", false, false)
82
84 return new InlineAsmPrepare();
85}
86
87#ifndef NDEBUG
88static void printDebugDomInfo(const DominatorTree &DT, const Use &U,
89 const BasicBlock *BB, bool IsDefaultDest) {
90 if (isa<Instruction>(U.getUser()))
91 LLVM_DEBUG(dbgs() << "Use: " << *U.getUser() << ", in block "
92 << cast<Instruction>(U.getUser())->getParent()->getName()
93 << ", is " << (DT.dominates(BB, U) ? "" : "NOT ")
94 << "dominated by " << BB->getName() << " ("
95 << (IsDefaultDest ? "in" : "") << "direct)\n");
96}
97#endif
98
99/// The Use is in the same BasicBlock as the intrinsic call.
100static bool isInSameBasicBlock(const Use &U, const BasicBlock *BB) {
101 const auto *I = dyn_cast<Instruction>(U.getUser());
102 return I && I->getParent() == BB;
103}
104
106 SSAUpdater &SSAUpdate) {
107 SmallPtrSet<Use *, 4> Visited;
108 BasicBlock *DefaultDest = CBR->getDefaultDest();
109 BasicBlock *LandingPad = Intrinsic->getParent();
110
112 for (Use *U : Uses) {
113 if (!Visited.insert(U).second)
114 continue;
115
116#ifndef NDEBUG
117 printDebugDomInfo(DT, *U, LandingPad, /*IsDefaultDest*/ false);
118 printDebugDomInfo(DT, *U, DefaultDest, /*IsDefaultDest*/ true);
119#endif
120
121 // Don't rewrite the use in the newly inserted intrinsic.
122 if (const auto *II = dyn_cast<IntrinsicInst>(U->getUser()))
123 if (II->getIntrinsicID() == Intrinsic::callbr_landingpad)
124 continue;
125
126 // If the Use is in the same BasicBlock as the Intrinsic call, replace
127 // the Use with the value of the Intrinsic call.
128 if (isInSameBasicBlock(*U, LandingPad)) {
129 U->set(Intrinsic);
130 continue;
131 }
132
133 // If the Use is dominated by the default dest, do not touch it.
134 if (DT.dominates(DefaultDest, *U))
135 continue;
136
137 SSAUpdate.RewriteUse(*U);
138 }
139}
140
142 bool Changed = false;
143
145 Options.setMergeIdenticalEdges();
146
147 // The indirect destination might be duplicated between another parameter...
148 //
149 // %0 = callbr ... [label %x, label %x]
150 //
151 // ...hence MergeIdenticalEdges and AllowIndentical edges, but we don't need
152 // to split the default destination if it's duplicated between an indirect
153 // destination...
154 //
155 // %1 = callbr ... to label %x [label %x]
156 //
157 // ...hence starting at 1 and checking against successor 0 (aka the default
158 // destination).
159 for (unsigned I = 1, E = CBR->getNumSuccessors(); I != E; ++I)
160 if (CBR->getSuccessor(I) == CBR->getSuccessor(0) ||
161 isCriticalEdge(CBR, I, /*AllowIdenticalEdges*/ true))
163 Changed = true;
164
165 return Changed;
166}
167
168/// Create a separate SSA definition in each indirect target (via
169/// llvm.callbr.landingpad). This may require splitting critical edges so we
170/// have a location to place the intrinsic. Then remap users of the original
171/// callbr output SSA value to instead point to the appropriate
172/// llvm.callbr.landingpad value.
174 bool Changed = false;
176 IRBuilder<> Builder(CBR->getContext());
177
178 if (!CBR->getNumIndirectDests())
179 return false;
180
181 SSAUpdater SSAUpdate;
182 SSAUpdate.Initialize(CBR->getType(), CBR->getName());
183 SSAUpdate.AddAvailableValue(CBR->getParent(), CBR);
184 SSAUpdate.AddAvailableValue(CBR->getDefaultDest(), CBR);
185
186 for (BasicBlock *IndDest : CBR->getIndirectDests()) {
187 if (!Visited.insert(IndDest).second)
188 continue;
189
190 Builder.SetInsertPoint(&*IndDest->begin());
191 CallInst *Intrinsic = Builder.CreateIntrinsic(
192 CBR->getType(), Intrinsic::callbr_landingpad, {CBR});
193 SSAUpdate.AddAvailableValue(IndDest, Intrinsic);
194 updateSSA(DT, CBR, Intrinsic, SSAUpdate);
195 Changed = true;
196 }
197
198 return Changed;
199}
200
202 bool Changed = false;
203
204 Changed |= splitCriticalEdges(CBR, DT);
205 Changed |= insertIntrinsicCalls(CBR, *DT);
206
207 return Changed;
208}
209
212 for (BasicBlock &BB : F)
213 if (auto *CBR = dyn_cast<CallBrInst>(BB.getTerminator()))
214 if (!CBR->getType()->isVoidTy() && !CBR->use_empty())
215 CBRs.push_back(CBR);
216 return CBRs;
217}
218
220 DominatorTree *DT) {
221 bool Changed = false;
222
223 for (CallBrInst *CBR : CBRs)
224 Changed |= processCallBrInst(F, CBR, DT);
225
226 return Changed;
227}
228
229bool InlineAsmPrepare::runOnFunction(Function &F) {
231 if (CBRs.empty())
232 return false;
233
234 // It's highly likely that most programs do not contain CallBrInsts. Follow a
235 // similar pattern from SafeStackLegacyPass::runOnFunction to reuse previous
236 // domtree analysis if available, otherwise compute it lazily. This avoids
237 // forcing Dominator Tree Construction at -O0 for programs that likely do not
238 // contain CallBrInsts. It does pessimize programs with callbr at higher
239 // optimization levels, as the DominatorTree created here is not reused by
240 // subsequent passes.
241 DominatorTree *DT;
242 std::optional<DominatorTree> LazilyComputedDomTree;
243 if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
244 DT = &DTWP->getDomTree();
245 else {
246 LazilyComputedDomTree.emplace(F);
247 DT = &*LazilyComputedDomTree;
248 }
249
250 return runImpl(F, CBRs, DT);
251}
252
256 if (CBRs.empty())
257 return PreservedAnalyses::all();
258
259 auto *DT = &FAM.getResult<DominatorTreeAnalysis>(F);
260
261 if (runImpl(F, CBRs, DT)) {
264 return PA;
265 }
266
267 return PreservedAnalyses::all();
268}
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
static bool runImpl(Function &F, const TargetLowering &TLI, const LibcallLoweringInfo &Libcalls, AssumptionCache *AC)
static void printDebugDomInfo(const DominatorTree &DT, const Use &U, const BasicBlock *BB, bool IsDefaultDest)
static bool runImpl(Function &F, ArrayRef< CallBrInst * > CBRs, DominatorTree *DT)
static SmallVector< CallBrInst *, 2 > findCallBrs(Function &F)
static bool processCallBrInst(Function &F, CallBrInst *CBR, DominatorTree *DT)
static bool isInSameBasicBlock(const Use &U, const BasicBlock *BB)
The Use is in the same BasicBlock as the intrinsic call.
static bool splitCriticalEdges(CallBrInst *CBR, DominatorTree *DT)
static bool insertIntrinsicCalls(CallBrInst *CBR, DominatorTree &DT)
Create a separate SSA definition in each indirect target (via llvm.callbr.landingpad).
static void updateSSA(DominatorTree &DT, CallBrInst *CBR, CallInst *Intrinsic, SSAUpdater &SSAUpdate)
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
Remove Loads Into Fake Uses
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
SmallVector< BasicBlock *, 16 > getIndirectDests() const
BasicBlock * getSuccessor(unsigned i) const
unsigned getNumSuccessors() const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
This class represents a function call, abstracting a target machine's calling convention.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:278
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:316
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2811
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
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 & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
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.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
iterator_range< use_iterator > uses()
Definition Value.h:381
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
const ParentTy * getParent() const
Definition ilist_node.h:34
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
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
LLVM_ABI BasicBlock * SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If it is known that an edge is critical, SplitKnownCriticalEdge can be called directly,...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition CFG.cpp:106
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
LLVM_ABI FunctionPass * createInlineAsmPreparePass()
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
Option class for critical edge splitting.