blob: 8e8917664af49d9418c13d38901c9f76c68743f0 [file] [log] [blame]
Philip Reamesf27f3732015-01-15 19:29:42 +00001//===-- GCRootLowering.cpp - Garbage collection infrastructure ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the lowering for the gc.root mechanism.
11//
12//===----------------------------------------------------------------------===//
13
Philip Reames2b453952015-01-16 20:07:33 +000014#include "llvm/CodeGen/GCMetadata.h"
Chandler Carruth71f308a2015-02-13 09:09:03 +000015#include "llvm/CodeGen/GCStrategy.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000016#include "llvm/CodeGen/MachineFrameInfo.h"
17#include "llvm/CodeGen/MachineFunctionPass.h"
18#include "llvm/CodeGen/MachineInstrBuilder.h"
19#include "llvm/CodeGen/MachineModuleInfo.h"
20#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000021#include "llvm/CodeGen/TargetFrameLowering.h"
22#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000023#include "llvm/CodeGen/TargetRegisterInfo.h"
24#include "llvm/CodeGen/TargetSubtargetInfo.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000025#include "llvm/IR/Dominators.h"
26#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/Module.h"
28#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;
60 MachineModuleInfo *MMI;
61 const TargetInstrInfo *TII;
Philip Reamesf27f3732015-01-15 19:29:42 +000062
Philip Reamesb8714412015-01-15 19:39:17 +000063 void FindSafePoints(MachineFunction &MF);
Fangrui Songcb0bab82018-07-16 18:51:40 +000064 void VisitCallPoint(MachineBasicBlock::iterator CI);
Philip Reamesb8714412015-01-15 19:39:17 +000065 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +000066 const DebugLoc &DL) const;
Philip Reamesf27f3732015-01-15 19:29:42 +000067
Philip Reamesb8714412015-01-15 19:39:17 +000068 void FindStackOffsets(MachineFunction &MF);
Philip Reamesf27f3732015-01-15 19:29:42 +000069
Philip Reamesb8714412015-01-15 19:39:17 +000070public:
71 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000072
Philip Reamesb8714412015-01-15 19:39:17 +000073 GCMachineCodeAnalysis();
74 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000075
Philip Reamesb8714412015-01-15 19:39:17 +000076 bool runOnMachineFunction(MachineFunction &MF) override;
77};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000078}
Philip Reamesf27f3732015-01-15 19:29:42 +000079
80// -----------------------------------------------------------------------------
81
Philip Reamesb8714412015-01-15 19:39:17 +000082INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
83 false)
Philip Reamesf27f3732015-01-15 19:29:42 +000084INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
85INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
86
Philip Reamesb8714412015-01-15 19:39:17 +000087FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
Philip Reamesf27f3732015-01-15 19:29:42 +000088
89char LowerIntrinsics::ID = 0;
90
Philip Reamesb8714412015-01-15 19:39:17 +000091LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
92 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
93}
Philip Reamesf27f3732015-01-15 19:29:42 +000094
Mehdi Amini117296c2016-10-01 02:56:57 +000095StringRef LowerIntrinsics::getPassName() const {
Philip Reamesf27f3732015-01-15 19:29:42 +000096 return "Lower Garbage Collection Instructions";
97}
98
99void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
100 FunctionPass::getAnalysisUsage(AU);
101 AU.addRequired<GCModuleInfo>();
102 AU.addPreserved<DominatorTreeWrapperPass>();
103}
104
105/// doInitialization - If this module uses the GC intrinsics, find them now.
106bool LowerIntrinsics::doInitialization(Module &M) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000107 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
108 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
109 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
110 if (!I->isDeclaration() && I->hasGC())
111 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
112
Philip Reames23cf2e22015-01-28 19:28:03 +0000113 return false;
Philip Reamesf27f3732015-01-15 19:29:42 +0000114}
115
Philip Reames66c9fb02015-01-15 19:49:25 +0000116/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
117/// instruction could introduce a safe point.
118static bool CouldBecomeSafePoint(Instruction *I) {
119 // The natural definition of instructions which could introduce safe points
120 // are:
121 //
122 // - call, invoke (AfterCall, BeforeCall)
123 // - phis (Loops)
124 // - invoke, ret, unwind (Exit)
125 //
126 // However, instructions as seemingly inoccuous as arithmetic can become
127 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
128 // it is necessary to take a conservative approach.
129
130 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
131 isa<LoadInst>(I))
132 return false;
133
134 // llvm.gcroot is safe because it doesn't do anything at runtime.
135 if (CallInst *CI = dyn_cast<CallInst>(I))
136 if (Function *F = CI->getCalledFunction())
Pete Cooper9e1d3352015-05-20 17:16:39 +0000137 if (Intrinsic::ID IID = F->getIntrinsicID())
Philip Reames66c9fb02015-01-15 19:49:25 +0000138 if (IID == Intrinsic::gcroot)
139 return false;
140
141 return true;
142}
143
144static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
145 unsigned Count) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000146 // Scroll past alloca instructions.
147 BasicBlock::iterator IP = F.getEntryBlock().begin();
Philip Reamesb8714412015-01-15 19:39:17 +0000148 while (isa<AllocaInst>(IP))
149 ++IP;
Philip Reamesf27f3732015-01-15 19:29:42 +0000150
151 // Search for initializers in the initial BB.
Philip Reamesb8714412015-01-15 19:39:17 +0000152 SmallPtrSet<AllocaInst *, 16> InitedRoots;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000153 for (; !CouldBecomeSafePoint(&*IP); ++IP)
Philip Reamesf27f3732015-01-15 19:29:42 +0000154 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
155 if (AllocaInst *AI =
Philip Reamesb8714412015-01-15 19:39:17 +0000156 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Philip Reamesf27f3732015-01-15 19:29:42 +0000157 InitedRoots.insert(AI);
158
159 // Add root initializers.
160 bool MadeChange = false;
161
162 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
163 if (!InitedRoots.count(*I)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000164 StoreInst *SI = new StoreInst(
Eduard Burtescu90c44492016-01-18 00:10:01 +0000165 ConstantPointerNull::get(cast<PointerType>((*I)->getAllocatedType())),
Philip Reamesb8714412015-01-15 19:39:17 +0000166 *I);
Philip Reamesf27f3732015-01-15 19:29:42 +0000167 SI->insertAfter(*I);
168 MadeChange = true;
169 }
170
171 return MadeChange;
172}
173
Philip Reamesf27f3732015-01-15 19:29:42 +0000174/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
175/// Leave gcroot intrinsics; the code generator needs to see those.
176bool LowerIntrinsics::runOnFunction(Function &F) {
177 // Quick exit for functions that do not use GC.
178 if (!F.hasGC())
179 return false;
180
181 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
182 GCStrategy &S = FI.getStrategy();
183
Philip Reames18945d62018-11-11 21:13:09 +0000184 return DoLowering(F, S);
Philip Reamesf27f3732015-01-15 19:29:42 +0000185}
186
Philip Reames18945d62018-11-11 21:13:09 +0000187/// Lower barriers out of existance (if the associated GCStrategy hasn't
188/// already done so...), and insert initializing stores to roots as a defensive
189/// measure. Given we're going to report all roots live at all safepoints, we
190/// need to be able to ensure each root has been initialized by the point the
191/// first safepoint is reached. This really should have been done by the
192/// frontend, but the old API made this non-obvious, so we do a potentially
193/// redundant store just in case.
194bool LowerIntrinsics::DoLowering(Function &F, GCStrategy &S) {
Philip Reamesb8714412015-01-15 19:39:17 +0000195 SmallVector<AllocaInst *, 32> Roots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000196
197 bool MadeChange = false;
198 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
199 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
200 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
201 Function *F = CI->getCalledFunction();
202 switch (F->getIntrinsicID()) {
Philip Reames18945d62018-11-11 21:13:09 +0000203 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;
Philip Reamesf27f3732015-01-15 19:29:42 +0000211 break;
Philip Reamesf27f3732015-01-15 19:29:42 +0000212 }
Philip Reames18945d62018-11-11 21:13:09 +0000213 case Intrinsic::gcread: {
214 // Replace a read barrier with a simple load.
215 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
216 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 }
229 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000230 }
231 }
232 }
233
234 if (Roots.size())
235 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
236
237 return MadeChange;
238}
239
240// -----------------------------------------------------------------------------
241
242char GCMachineCodeAnalysis::ID = 0;
243char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
244
245INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
246 "Analyze Machine Code For Garbage Collection", false, false)
247
Philip Reamesb8714412015-01-15 19:39:17 +0000248GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
Philip Reamesf27f3732015-01-15 19:29:42 +0000249
250void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
251 MachineFunctionPass::getAnalysisUsage(AU);
252 AU.setPreservesAll();
253 AU.addRequired<MachineModuleInfo>();
254 AU.addRequired<GCModuleInfo>();
255}
256
257MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
258 MachineBasicBlock::iterator MI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000259 const DebugLoc &DL) const {
Jim Grosbach6f482002015-05-18 18:43:14 +0000260 MCSymbol *Label = MBB.getParent()->getContext().createTempSymbol();
Philip Reamesf27f3732015-01-15 19:29:42 +0000261 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
262 return Label;
263}
264
265void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
266 // Find the return address (next instruction), too, so as to bracket the call
267 // instruction.
268 MachineBasicBlock::iterator RAI = CI;
269 ++RAI;
270
271 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000272 MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000273 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
274 }
275
276 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000277 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000278 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
279 }
280}
281
282void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
Philip Reamesb8714412015-01-15 19:39:17 +0000283 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
284 ++BBI)
285 for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
286 MI != ME; ++MI)
Philip Reames7de640a2015-01-16 19:33:28 +0000287 if (MI->isCall()) {
288 // Do not treat tail or sibling call sites as safe points. This is
289 // legal since any arguments passed to the callee which live in the
290 // remnants of the callers frame will be owned and updated by the
291 // callee if required.
292 if (MI->isTerminator())
293 continue;
Philip Reamesf27f3732015-01-15 19:29:42 +0000294 VisitCallPoint(MI);
Philip Reames7de640a2015-01-16 19:33:28 +0000295 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000296}
297
298void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
Eric Christopher1df0c512015-02-20 18:44:15 +0000299 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Philip Reamesf27f3732015-01-15 19:29:42 +0000300 assert(TFI && "TargetRegisterInfo not available!");
301
302 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
303 RI != FI->roots_end();) {
304 // If the root references a dead object, no need to keep it.
Matthias Braun941a7052016-07-28 18:40:00 +0000305 if (MF.getFrameInfo().isDeadObjectIndex(RI->Num)) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000306 RI = FI->removeStackRoot(RI);
307 } else {
James Y Knight5567baf2015-08-15 02:32:35 +0000308 unsigned FrameReg; // FIXME: surely GCRoot ought to store the
309 // register that the offset is from?
310 RI->StackOffset = TFI->getFrameIndexReference(MF, RI->Num, FrameReg);
Philip Reamesf27f3732015-01-15 19:29:42 +0000311 ++RI;
312 }
313 }
314}
315
316bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
317 // Quick exit for functions that do not use GC.
Matthias Braunf1caa282017-12-15 22:22:58 +0000318 if (!MF.getFunction().hasGC())
Philip Reamesf27f3732015-01-15 19:29:42 +0000319 return false;
320
Matthias Braunf1caa282017-12-15 22:22:58 +0000321 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(MF.getFunction());
Philip Reamesf27f3732015-01-15 19:29:42 +0000322 MMI = &getAnalysis<MachineModuleInfo>();
Eric Christopher1df0c512015-02-20 18:44:15 +0000323 TII = MF.getSubtarget().getInstrInfo();
Philip Reamesf27f3732015-01-15 19:29:42 +0000324
Philip Reames2df78272015-04-02 05:00:40 +0000325 // Find the size of the stack frame. There may be no correct static frame
326 // size, we use UINT64_MAX to represent this.
Matthias Braun941a7052016-07-28 18:40:00 +0000327 const MachineFrameInfo &MFI = MF.getFrameInfo();
Philip Reames2df78272015-04-02 05:00:40 +0000328 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Matthias Braun941a7052016-07-28 18:40:00 +0000329 const bool DynamicFrameSize = MFI.hasVarSizedObjects() ||
Philip Reames2df78272015-04-02 05:00:40 +0000330 RegInfo->needsStackRealignment(MF);
Matthias Braun941a7052016-07-28 18:40:00 +0000331 FI->setFrameSize(DynamicFrameSize ? UINT64_MAX : MFI.getStackSize());
Philip Reamesf27f3732015-01-15 19:29:42 +0000332
333 // Find all safe points.
Philip Reames2df78272015-04-02 05:00:40 +0000334 if (FI->getStrategy().needsSafePoints())
335 FindSafePoints(MF);
Philip Reamesf27f3732015-01-15 19:29:42 +0000336
Philip Reames2df78272015-04-02 05:00:40 +0000337 // Find the concrete stack offsets for all roots (stack slots)
Philip Reamesf27f3732015-01-15 19:29:42 +0000338 FindStackOffsets(MF);
339
340 return false;
341}