1 //===-- GCRootLowering.cpp - Garbage collection infrastructure ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the lowering for the gc.root mechanism.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/GCMetadata.h"
14 #include "llvm/CodeGen/GCStrategy.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineFunctionPass.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/TargetFrameLowering.h"
21 #include "llvm/CodeGen/TargetInstrInfo.h"
22 #include "llvm/CodeGen/TargetRegisterInfo.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
35 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
36 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
37 /// directed by the GCStrategy. It also performs automatic root initialization
38 /// and custom intrinsic lowering.
39 class LowerIntrinsics
: public FunctionPass
{
40 bool DoLowering(Function
&F
, GCStrategy
&S
);
46 StringRef
getPassName() const override
;
47 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
49 bool doInitialization(Module
&M
) override
;
50 bool runOnFunction(Function
&F
) override
;
53 /// GCMachineCodeAnalysis - This is a target-independent pass over the machine
54 /// function representation to identify safe points for the garbage collector
55 /// in the machine code. It inserts labels at safe points and populates a
56 /// GCMetadata record for each function.
57 class GCMachineCodeAnalysis
: public MachineFunctionPass
{
59 MachineModuleInfo
*MMI
;
60 const TargetInstrInfo
*TII
;
62 void FindSafePoints(MachineFunction
&MF
);
63 void VisitCallPoint(MachineBasicBlock::iterator CI
);
64 MCSymbol
*InsertLabel(MachineBasicBlock
&MBB
, MachineBasicBlock::iterator MI
,
65 const DebugLoc
&DL
) const;
67 void FindStackOffsets(MachineFunction
&MF
);
72 GCMachineCodeAnalysis();
73 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
75 bool runOnMachineFunction(MachineFunction
&MF
) override
;
79 // -----------------------------------------------------------------------------
81 INITIALIZE_PASS_BEGIN(LowerIntrinsics
, "gc-lowering", "GC Lowering", false,
83 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo
)
84 INITIALIZE_PASS_END(LowerIntrinsics
, "gc-lowering", "GC Lowering", false, false)
86 FunctionPass
*llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
88 char LowerIntrinsics::ID
= 0;
90 LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID
) {
91 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
94 StringRef
LowerIntrinsics::getPassName() const {
95 return "Lower Garbage Collection Instructions";
98 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage
&AU
) const {
99 FunctionPass::getAnalysisUsage(AU
);
100 AU
.addRequired
<GCModuleInfo
>();
101 AU
.addPreserved
<DominatorTreeWrapperPass
>();
104 /// doInitialization - If this module uses the GC intrinsics, find them now.
105 bool LowerIntrinsics::doInitialization(Module
&M
) {
106 GCModuleInfo
*MI
= getAnalysisIfAvailable
<GCModuleInfo
>();
107 assert(MI
&& "LowerIntrinsics didn't require GCModuleInfo!?");
108 for (Module::iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
)
109 if (!I
->isDeclaration() && I
->hasGC())
110 MI
->getFunctionInfo(*I
); // Instantiate the GC strategy.
115 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
116 /// instruction could introduce a safe point.
117 static bool CouldBecomeSafePoint(Instruction
*I
) {
118 // The natural definition of instructions which could introduce safe points
121 // - call, invoke (AfterCall, BeforeCall)
123 // - invoke, ret, unwind (Exit)
125 // However, instructions as seemingly inoccuous as arithmetic can become
126 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
127 // it is necessary to take a conservative approach.
129 if (isa
<AllocaInst
>(I
) || isa
<GetElementPtrInst
>(I
) || isa
<StoreInst
>(I
) ||
133 // llvm.gcroot is safe because it doesn't do anything at runtime.
134 if (CallInst
*CI
= dyn_cast
<CallInst
>(I
))
135 if (Function
*F
= CI
->getCalledFunction())
136 if (Intrinsic::ID IID
= F
->getIntrinsicID())
137 if (IID
== Intrinsic::gcroot
)
143 static bool InsertRootInitializers(Function
&F
, ArrayRef
<AllocaInst
*> Roots
) {
144 // Scroll past alloca instructions.
145 BasicBlock::iterator IP
= F
.getEntryBlock().begin();
146 while (isa
<AllocaInst
>(IP
))
149 // Search for initializers in the initial BB.
150 SmallPtrSet
<AllocaInst
*, 16> InitedRoots
;
151 for (; !CouldBecomeSafePoint(&*IP
); ++IP
)
152 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(IP
))
154 dyn_cast
<AllocaInst
>(SI
->getOperand(1)->stripPointerCasts()))
155 InitedRoots
.insert(AI
);
157 // Add root initializers.
158 bool MadeChange
= false;
160 for (AllocaInst
*Root
: Roots
)
161 if (!InitedRoots
.count(Root
)) {
162 StoreInst
*SI
= new StoreInst(
163 ConstantPointerNull::get(cast
<PointerType
>(Root
->getAllocatedType())),
165 SI
->insertAfter(Root
);
172 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
173 /// Leave gcroot intrinsics; the code generator needs to see those.
174 bool LowerIntrinsics::runOnFunction(Function
&F
) {
175 // Quick exit for functions that do not use GC.
179 GCFunctionInfo
&FI
= getAnalysis
<GCModuleInfo
>().getFunctionInfo(F
);
180 GCStrategy
&S
= FI
.getStrategy();
182 return DoLowering(F
, S
);
185 /// Lower barriers out of existance (if the associated GCStrategy hasn't
186 /// already done so...), and insert initializing stores to roots as a defensive
187 /// measure. Given we're going to report all roots live at all safepoints, we
188 /// need to be able to ensure each root has been initialized by the point the
189 /// first safepoint is reached. This really should have been done by the
190 /// frontend, but the old API made this non-obvious, so we do a potentially
191 /// redundant store just in case.
192 bool LowerIntrinsics::DoLowering(Function
&F
, GCStrategy
&S
) {
193 SmallVector
<AllocaInst
*, 32> Roots
;
195 bool MadeChange
= false;
196 for (BasicBlock
&BB
: F
)
197 for (BasicBlock::iterator II
= BB
.begin(), E
= BB
.end(); II
!= E
;) {
198 IntrinsicInst
*CI
= dyn_cast
<IntrinsicInst
>(II
++);
202 Function
*F
= CI
->getCalledFunction();
203 switch (F
->getIntrinsicID()) {
205 case Intrinsic::gcwrite
: {
206 // Replace a write barrier with a simple store.
207 Value
*St
= new StoreInst(CI
->getArgOperand(0),
208 CI
->getArgOperand(2), CI
);
209 CI
->replaceAllUsesWith(St
);
210 CI
->eraseFromParent();
214 case Intrinsic::gcread
: {
215 // Replace a read barrier with a simple load.
216 Value
*Ld
= new LoadInst(CI
->getType(), CI
->getArgOperand(1), "", CI
);
218 CI
->replaceAllUsesWith(Ld
);
219 CI
->eraseFromParent();
223 case Intrinsic::gcroot
: {
224 // Initialize the GC root, but do not delete the intrinsic. The
225 // backend needs the intrinsic to flag the stack slot.
227 cast
<AllocaInst
>(CI
->getArgOperand(0)->stripPointerCasts()));
234 MadeChange
|= InsertRootInitializers(F
, Roots
);
239 // -----------------------------------------------------------------------------
241 char GCMachineCodeAnalysis::ID
= 0;
242 char &llvm::GCMachineCodeAnalysisID
= GCMachineCodeAnalysis::ID
;
244 INITIALIZE_PASS(GCMachineCodeAnalysis
, "gc-analysis",
245 "Analyze Machine Code For Garbage Collection", false, false)
247 GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID
) {}
249 void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage
&AU
) const {
250 MachineFunctionPass::getAnalysisUsage(AU
);
251 AU
.setPreservesAll();
252 AU
.addRequired
<MachineModuleInfo
>();
253 AU
.addRequired
<GCModuleInfo
>();
256 MCSymbol
*GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock
&MBB
,
257 MachineBasicBlock::iterator MI
,
258 const DebugLoc
&DL
) const {
259 MCSymbol
*Label
= MBB
.getParent()->getContext().createTempSymbol();
260 BuildMI(MBB
, MI
, DL
, TII
->get(TargetOpcode::GC_LABEL
)).addSym(Label
);
264 void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI
) {
265 // Find the return address (next instruction), since that's what will be on
266 // the stack when the call is suspended and we need to inspect the stack.
267 MachineBasicBlock::iterator RAI
= CI
;
270 MCSymbol
*Label
= InsertLabel(*CI
->getParent(), RAI
, CI
->getDebugLoc());
271 FI
->addSafePoint(Label
, CI
->getDebugLoc());
274 void GCMachineCodeAnalysis::FindSafePoints(MachineFunction
&MF
) {
275 for (MachineBasicBlock
&MBB
: MF
)
276 for (MachineBasicBlock::iterator MI
= MBB
.begin(), ME
= MBB
.end();
279 // Do not treat tail or sibling call sites as safe points. This is
280 // legal since any arguments passed to the callee which live in the
281 // remnants of the callers frame will be owned and updated by the
282 // callee if required.
283 if (MI
->isTerminator())
289 void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction
&MF
) {
290 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
291 assert(TFI
&& "TargetRegisterInfo not available!");
293 for (GCFunctionInfo::roots_iterator RI
= FI
->roots_begin();
294 RI
!= FI
->roots_end();) {
295 // If the root references a dead object, no need to keep it.
296 if (MF
.getFrameInfo().isDeadObjectIndex(RI
->Num
)) {
297 RI
= FI
->removeStackRoot(RI
);
299 unsigned FrameReg
; // FIXME: surely GCRoot ought to store the
300 // register that the offset is from?
301 RI
->StackOffset
= TFI
->getFrameIndexReference(MF
, RI
->Num
, FrameReg
);
307 bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction
&MF
) {
308 // Quick exit for functions that do not use GC.
309 if (!MF
.getFunction().hasGC())
312 FI
= &getAnalysis
<GCModuleInfo
>().getFunctionInfo(MF
.getFunction());
313 MMI
= &getAnalysis
<MachineModuleInfo
>();
314 TII
= MF
.getSubtarget().getInstrInfo();
316 // Find the size of the stack frame. There may be no correct static frame
317 // size, we use UINT64_MAX to represent this.
318 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
319 const TargetRegisterInfo
*RegInfo
= MF
.getSubtarget().getRegisterInfo();
320 const bool DynamicFrameSize
= MFI
.hasVarSizedObjects() ||
321 RegInfo
->needsStackRealignment(MF
);
322 FI
->setFrameSize(DynamicFrameSize
? UINT64_MAX
: MFI
.getStackSize());
324 // Find all safe points.
325 if (FI
->getStrategy().needsSafePoints())
328 // Find the concrete stack offsets for all roots (stack slots)
329 FindStackOffsets(MF
);