blob: c6730aa6b00d84ff378169320aa0e318435e3078 [file] [log] [blame]
Philip Reamesf27f3732015-01-15 19:29:42 +00001//===-- GCRootLowering.cpp - Garbage collection infrastructure ------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Philip Reamesf27f3732015-01-15 19:29:42 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the lowering for the gc.root mechanism.
10//
11//===----------------------------------------------------------------------===//
12
Philip Reames2b453952015-01-16 20:07:33 +000013#include "llvm/CodeGen/GCMetadata.h"
Chandler Carruth71f308a2015-02-13 09:09:03 +000014#include "llvm/CodeGen/GCStrategy.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000015#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"
David Blaikie3f833ed2017-11-08 01:01:31 +000020#include "llvm/CodeGen/TargetFrameLowering.h"
21#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000022#include "llvm/CodeGen/TargetRegisterInfo.h"
23#include "llvm/CodeGen/TargetSubtargetInfo.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000024#include "llvm/IR/Dominators.h"
25#include "llvm/IR/IntrinsicInst.h"
26#include "llvm/IR/Module.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080027#include "llvm/InitializePasses.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000031
32using namespace llvm;
33
34namespace {
35
Philip Reamesb8714412015-01-15 19:39:17 +000036/// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
37/// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
38/// directed by the GCStrategy. It also performs automatic root initialization
39/// and custom intrinsic lowering.
40class LowerIntrinsics : public FunctionPass {
Philip Reames18945d62018-11-11 21:13:09 +000041 bool DoLowering(Function &F, GCStrategy &S);
Philip Reamesf27f3732015-01-15 19:29:42 +000042
Philip Reamesb8714412015-01-15 19:39:17 +000043public:
44 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000045
Philip Reamesb8714412015-01-15 19:39:17 +000046 LowerIntrinsics();
Mehdi Amini117296c2016-10-01 02:56:57 +000047 StringRef getPassName() const override;
Philip Reamesb8714412015-01-15 19:39:17 +000048 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000049
Philip Reamesb8714412015-01-15 19:39:17 +000050 bool doInitialization(Module &M) override;
51 bool runOnFunction(Function &F) override;
52};
Philip Reamesf27f3732015-01-15 19:29:42 +000053
Philip Reamesb8714412015-01-15 19:39:17 +000054/// GCMachineCodeAnalysis - This is a target-independent pass over the machine
55/// function representation to identify safe points for the garbage collector
56/// in the machine code. It inserts labels at safe points and populates a
57/// GCMetadata record for each function.
58class GCMachineCodeAnalysis : public MachineFunctionPass {
Philip Reamesb8714412015-01-15 19:39:17 +000059 GCFunctionInfo *FI;
Philip Reamesb8714412015-01-15 19:39:17 +000060 const TargetInstrInfo *TII;
Philip Reamesf27f3732015-01-15 19:29:42 +000061
Philip Reamesb8714412015-01-15 19:39:17 +000062 void FindSafePoints(MachineFunction &MF);
Fangrui Songcb0bab82018-07-16 18:51:40 +000063 void VisitCallPoint(MachineBasicBlock::iterator CI);
Philip Reamesb8714412015-01-15 19:39:17 +000064 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +000065 const DebugLoc &DL) const;
Philip Reamesf27f3732015-01-15 19:29:42 +000066
Philip Reamesb8714412015-01-15 19:39:17 +000067 void FindStackOffsets(MachineFunction &MF);
Philip Reamesf27f3732015-01-15 19:29:42 +000068
Philip Reamesb8714412015-01-15 19:39:17 +000069public:
70 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000071
Philip Reamesb8714412015-01-15 19:39:17 +000072 GCMachineCodeAnalysis();
73 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000074
Philip Reamesb8714412015-01-15 19:39:17 +000075 bool runOnMachineFunction(MachineFunction &MF) override;
76};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000077}
Philip Reamesf27f3732015-01-15 19:29:42 +000078
79// -----------------------------------------------------------------------------
80
Philip Reamesb8714412015-01-15 19:39:17 +000081INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
82 false)
Philip Reamesf27f3732015-01-15 19:29:42 +000083INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
84INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
85
Philip Reamesb8714412015-01-15 19:39:17 +000086FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
Philip Reamesf27f3732015-01-15 19:29:42 +000087
88char LowerIntrinsics::ID = 0;
89
Philip Reamesb8714412015-01-15 19:39:17 +000090LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
91 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
92}
Philip Reamesf27f3732015-01-15 19:29:42 +000093
Mehdi Amini117296c2016-10-01 02:56:57 +000094StringRef LowerIntrinsics::getPassName() const {
Philip Reamesf27f3732015-01-15 19:29:42 +000095 return "Lower Garbage Collection Instructions";
96}
97
98void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
99 FunctionPass::getAnalysisUsage(AU);
100 AU.addRequired<GCModuleInfo>();
101 AU.addPreserved<DominatorTreeWrapperPass>();
102}
103
104/// doInitialization - If this module uses the GC intrinsics, find them now.
105bool LowerIntrinsics::doInitialization(Module &M) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000106 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.
111
Philip Reames23cf2e22015-01-28 19:28:03 +0000112 return false;
Philip Reamesf27f3732015-01-15 19:29:42 +0000113}
114
Philip Reames66c9fb02015-01-15 19:49:25 +0000115/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
116/// instruction could introduce a safe point.
117static bool CouldBecomeSafePoint(Instruction *I) {
118 // The natural definition of instructions which could introduce safe points
119 // are:
120 //
121 // - call, invoke (AfterCall, BeforeCall)
122 // - phis (Loops)
123 // - invoke, ret, unwind (Exit)
124 //
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.
128
129 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
130 isa<LoadInst>(I))
131 return false;
132
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())
Pete Cooper9e1d3352015-05-20 17:16:39 +0000136 if (Intrinsic::ID IID = F->getIntrinsicID())
Philip Reames66c9fb02015-01-15 19:49:25 +0000137 if (IID == Intrinsic::gcroot)
138 return false;
139
140 return true;
141}
142
Philip Reames15590212018-11-12 02:26:26 +0000143static bool InsertRootInitializers(Function &F, ArrayRef<AllocaInst *> Roots) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000144 // Scroll past alloca instructions.
145 BasicBlock::iterator IP = F.getEntryBlock().begin();
Philip Reamesb8714412015-01-15 19:39:17 +0000146 while (isa<AllocaInst>(IP))
147 ++IP;
Philip Reamesf27f3732015-01-15 19:29:42 +0000148
149 // Search for initializers in the initial BB.
Philip Reamesb8714412015-01-15 19:39:17 +0000150 SmallPtrSet<AllocaInst *, 16> InitedRoots;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000151 for (; !CouldBecomeSafePoint(&*IP); ++IP)
Philip Reamesf27f3732015-01-15 19:29:42 +0000152 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
153 if (AllocaInst *AI =
Philip Reamesb8714412015-01-15 19:39:17 +0000154 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Philip Reamesf27f3732015-01-15 19:29:42 +0000155 InitedRoots.insert(AI);
156
157 // Add root initializers.
158 bool MadeChange = false;
159
Philip Reames15590212018-11-12 02:26:26 +0000160 for (AllocaInst *Root : Roots)
161 if (!InitedRoots.count(Root)) {
Eli Friedman11aa3702020-05-14 14:48:10 -0700162 new StoreInst(
Philip Reames15590212018-11-12 02:26:26 +0000163 ConstantPointerNull::get(cast<PointerType>(Root->getAllocatedType())),
Eli Friedman11aa3702020-05-14 14:48:10 -0700164 Root, Root->getNextNode());
Philip Reamesf27f3732015-01-15 19:29:42 +0000165 MadeChange = true;
166 }
167
168 return MadeChange;
169}
170
Philip Reamesf27f3732015-01-15 19:29:42 +0000171/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
172/// Leave gcroot intrinsics; the code generator needs to see those.
173bool LowerIntrinsics::runOnFunction(Function &F) {
174 // Quick exit for functions that do not use GC.
175 if (!F.hasGC())
176 return false;
177
178 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
179 GCStrategy &S = FI.getStrategy();
180
Philip Reames18945d62018-11-11 21:13:09 +0000181 return DoLowering(F, S);
Philip Reamesf27f3732015-01-15 19:29:42 +0000182}
183
Philip Reames18945d62018-11-11 21:13:09 +0000184/// Lower barriers out of existance (if the associated GCStrategy hasn't
185/// already done so...), and insert initializing stores to roots as a defensive
186/// measure. Given we're going to report all roots live at all safepoints, we
187/// need to be able to ensure each root has been initialized by the point the
188/// first safepoint is reached. This really should have been done by the
189/// frontend, but the old API made this non-obvious, so we do a potentially
Jim Lin466f8842020-02-18 10:48:38 +0800190/// redundant store just in case.
Philip Reames18945d62018-11-11 21:13:09 +0000191bool LowerIntrinsics::DoLowering(Function &F, GCStrategy &S) {
Philip Reamesb8714412015-01-15 19:39:17 +0000192 SmallVector<AllocaInst *, 32> Roots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000193
194 bool MadeChange = false;
Jim Lin466f8842020-02-18 10:48:38 +0800195 for (BasicBlock &BB : F)
Philip Reames15590212018-11-12 02:26:26 +0000196 for (BasicBlock::iterator II = BB.begin(), E = BB.end(); II != E;) {
197 IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++);
198 if (!CI)
199 continue;
200
201 Function *F = CI->getCalledFunction();
202 switch (F->getIntrinsicID()) {
203 default: break;
204 case Intrinsic::gcwrite: {
205 // Replace a write barrier with a simple store.
206 Value *St = new StoreInst(CI->getArgOperand(0),
207 CI->getArgOperand(2), CI);
208 CI->replaceAllUsesWith(St);
209 CI->eraseFromParent();
210 MadeChange = true;
211 break;
212 }
213 case Intrinsic::gcread: {
214 // Replace a read barrier with a simple load.
James Y Knight14359ef2019-02-01 20:44:24 +0000215 Value *Ld = new LoadInst(CI->getType(), CI->getArgOperand(1), "", CI);
Philip Reames15590212018-11-12 02:26:26 +0000216 Ld->takeName(CI);
217 CI->replaceAllUsesWith(Ld);
218 CI->eraseFromParent();
219 MadeChange = true;
220 break;
221 }
222 case Intrinsic::gcroot: {
223 // Initialize the GC root, but do not delete the intrinsic. The
224 // backend needs the intrinsic to flag the stack slot.
225 Roots.push_back(
226 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
227 break;
228 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000229 }
230 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000231
232 if (Roots.size())
Philip Reames15590212018-11-12 02:26:26 +0000233 MadeChange |= InsertRootInitializers(F, Roots);
Philip Reamesf27f3732015-01-15 19:29:42 +0000234
235 return MadeChange;
236}
237
238// -----------------------------------------------------------------------------
239
240char GCMachineCodeAnalysis::ID = 0;
241char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
242
243INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
244 "Analyze Machine Code For Garbage Collection", false, false)
245
Philip Reamesb8714412015-01-15 19:39:17 +0000246GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
Philip Reamesf27f3732015-01-15 19:29:42 +0000247
248void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
249 MachineFunctionPass::getAnalysisUsage(AU);
250 AU.setPreservesAll();
Philip Reamesf27f3732015-01-15 19:29:42 +0000251 AU.addRequired<GCModuleInfo>();
252}
253
254MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
255 MachineBasicBlock::iterator MI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000256 const DebugLoc &DL) const {
Jim Grosbach6f482002015-05-18 18:43:14 +0000257 MCSymbol *Label = MBB.getParent()->getContext().createTempSymbol();
Philip Reamesf27f3732015-01-15 19:29:42 +0000258 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
259 return Label;
260}
261
262void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
Philip Reamesc75a0c32018-11-12 20:15:34 +0000263 // Find the return address (next instruction), since that's what will be on
264 // the stack when the call is suspended and we need to inspect the stack.
Philip Reamesf27f3732015-01-15 19:29:42 +0000265 MachineBasicBlock::iterator RAI = CI;
266 ++RAI;
267
Philip Reamese44a55d2018-11-12 22:03:53 +0000268 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
269 FI->addSafePoint(Label, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000270}
271
272void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
Philip Reames15590212018-11-12 02:26:26 +0000273 for (MachineBasicBlock &MBB : MF)
274 for (MachineBasicBlock::iterator MI = MBB.begin(), ME = MBB.end();
Philip Reamesb8714412015-01-15 19:39:17 +0000275 MI != ME; ++MI)
Philip Reames7de640a2015-01-16 19:33:28 +0000276 if (MI->isCall()) {
277 // Do not treat tail or sibling call sites as safe points. This is
278 // legal since any arguments passed to the callee which live in the
279 // remnants of the callers frame will be owned and updated by the
280 // callee if required.
281 if (MI->isTerminator())
282 continue;
Philip Reamesf27f3732015-01-15 19:29:42 +0000283 VisitCallPoint(MI);
Philip Reames7de640a2015-01-16 19:33:28 +0000284 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000285}
286
287void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
Eric Christopher1df0c512015-02-20 18:44:15 +0000288 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Philip Reamesf27f3732015-01-15 19:29:42 +0000289 assert(TFI && "TargetRegisterInfo not available!");
290
291 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
292 RI != FI->roots_end();) {
293 // If the root references a dead object, no need to keep it.
Matthias Braun941a7052016-07-28 18:40:00 +0000294 if (MF.getFrameInfo().isDeadObjectIndex(RI->Num)) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000295 RI = FI->removeStackRoot(RI);
296 } else {
Matt Arsenault2481f262020-04-07 16:33:58 -0400297 Register FrameReg; // FIXME: surely GCRoot ought to store the
James Y Knight5567baf2015-08-15 02:32:35 +0000298 // register that the offset is from?
299 RI->StackOffset = TFI->getFrameIndexReference(MF, RI->Num, FrameReg);
Philip Reamesf27f3732015-01-15 19:29:42 +0000300 ++RI;
301 }
302 }
303}
304
305bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
306 // Quick exit for functions that do not use GC.
Matthias Braunf1caa282017-12-15 22:22:58 +0000307 if (!MF.getFunction().hasGC())
Philip Reamesf27f3732015-01-15 19:29:42 +0000308 return false;
309
Matthias Braunf1caa282017-12-15 22:22:58 +0000310 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(MF.getFunction());
Eric Christopher1df0c512015-02-20 18:44:15 +0000311 TII = MF.getSubtarget().getInstrInfo();
Philip Reamesf27f3732015-01-15 19:29:42 +0000312
Philip Reames2df78272015-04-02 05:00:40 +0000313 // Find the size of the stack frame. There may be no correct static frame
314 // size, we use UINT64_MAX to represent this.
Matthias Braun941a7052016-07-28 18:40:00 +0000315 const MachineFrameInfo &MFI = MF.getFrameInfo();
Philip Reames2df78272015-04-02 05:00:40 +0000316 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Matthias Braun941a7052016-07-28 18:40:00 +0000317 const bool DynamicFrameSize = MFI.hasVarSizedObjects() ||
Philip Reames2df78272015-04-02 05:00:40 +0000318 RegInfo->needsStackRealignment(MF);
Matthias Braun941a7052016-07-28 18:40:00 +0000319 FI->setFrameSize(DynamicFrameSize ? UINT64_MAX : MFI.getStackSize());
Philip Reamesf27f3732015-01-15 19:29:42 +0000320
321 // Find all safe points.
Philip Reames2df78272015-04-02 05:00:40 +0000322 if (FI->getStrategy().needsSafePoints())
323 FindSafePoints(MF);
Philip Reamesf27f3732015-01-15 19:29:42 +0000324
Philip Reames2df78272015-04-02 05:00:40 +0000325 // Find the concrete stack offsets for all roots (stack slots)
Philip Reamesf27f3732015-01-15 19:29:42 +0000326 FindStackOffsets(MF);
327
328 return false;
329}