blob: e8ccd84b0b93e4ebe0c8798e49500c78d4916003 [file] [log] [blame]
Philip Reames71649b02015-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 Reames07fbc5c2015-01-16 20:07:33 +000014#include "llvm/CodeGen/GCMetadata.h"
Chandler Carruth02d62882015-02-13 09:09:03 +000015#include "llvm/CodeGen/GCStrategy.h"
Philip Reames71649b02015-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 Blaikie48319232017-11-08 01:01:31 +000021#include "llvm/CodeGen/TargetFrameLowering.h"
22#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000023#include "llvm/CodeGen/TargetRegisterInfo.h"
24#include "llvm/CodeGen/TargetSubtargetInfo.h"
Philip Reames71649b02015-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 Reames71649b02015-01-15 19:29:42 +000031
32using namespace llvm;
33
34namespace {
35
Philip Reamesb0a04ac2015-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 Reames4708fed2018-11-11 21:13:09 +000041 bool DoLowering(Function &F, GCStrategy &S);
Philip Reames71649b02015-01-15 19:29:42 +000042
Philip Reamesb0a04ac2015-01-15 19:39:17 +000043public:
44 static char ID;
Philip Reames71649b02015-01-15 19:29:42 +000045
Philip Reamesb0a04ac2015-01-15 19:39:17 +000046 LowerIntrinsics();
Mehdi Amini67f335d2016-10-01 02:56:57 +000047 StringRef getPassName() const override;
Philip Reamesb0a04ac2015-01-15 19:39:17 +000048 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reames71649b02015-01-15 19:29:42 +000049
Philip Reamesb0a04ac2015-01-15 19:39:17 +000050 bool doInitialization(Module &M) override;
51 bool runOnFunction(Function &F) override;
52};
Philip Reames71649b02015-01-15 19:29:42 +000053
Philip Reamesb0a04ac2015-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 Reamesb0a04ac2015-01-15 19:39:17 +000059 GCFunctionInfo *FI;
60 MachineModuleInfo *MMI;
61 const TargetInstrInfo *TII;
Philip Reames71649b02015-01-15 19:29:42 +000062
Philip Reamesb0a04ac2015-01-15 19:39:17 +000063 void FindSafePoints(MachineFunction &MF);
Fangrui Song7d882862018-07-16 18:51:40 +000064 void VisitCallPoint(MachineBasicBlock::iterator CI);
Philip Reamesb0a04ac2015-01-15 19:39:17 +000065 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
Benjamin Krameraf18e012016-06-12 15:39:02 +000066 const DebugLoc &DL) const;
Philip Reames71649b02015-01-15 19:29:42 +000067
Philip Reamesb0a04ac2015-01-15 19:39:17 +000068 void FindStackOffsets(MachineFunction &MF);
Philip Reames71649b02015-01-15 19:29:42 +000069
Philip Reamesb0a04ac2015-01-15 19:39:17 +000070public:
71 static char ID;
Philip Reames71649b02015-01-15 19:29:42 +000072
Philip Reamesb0a04ac2015-01-15 19:39:17 +000073 GCMachineCodeAnalysis();
74 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reames71649b02015-01-15 19:29:42 +000075
Philip Reamesb0a04ac2015-01-15 19:39:17 +000076 bool runOnMachineFunction(MachineFunction &MF) override;
77};
Alexander Kornienkocd52a7a2015-06-23 09:49:53 +000078}
Philip Reames71649b02015-01-15 19:29:42 +000079
80// -----------------------------------------------------------------------------
81
Philip Reamesb0a04ac2015-01-15 19:39:17 +000082INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
83 false)
Philip Reames71649b02015-01-15 19:29:42 +000084INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
85INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
86
Philip Reamesb0a04ac2015-01-15 19:39:17 +000087FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
Philip Reames71649b02015-01-15 19:29:42 +000088
89char LowerIntrinsics::ID = 0;
90
Philip Reamesb0a04ac2015-01-15 19:39:17 +000091LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
92 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
93}
Philip Reames71649b02015-01-15 19:29:42 +000094
Mehdi Amini67f335d2016-10-01 02:56:57 +000095StringRef LowerIntrinsics::getPassName() const {
Philip Reames71649b02015-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 Reames71649b02015-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 Reamesafe34982015-01-28 19:28:03 +0000113 return false;
Philip Reames71649b02015-01-15 19:29:42 +0000114}
115
Philip Reamesff0ce512015-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 Cooper9584e072015-05-20 17:16:39 +0000137 if (Intrinsic::ID IID = F->getIntrinsicID())
Philip Reamesff0ce512015-01-15 19:49:25 +0000138 if (IID == Intrinsic::gcroot)
139 return false;
140
141 return true;
142}
143
Philip Reames78a558a2018-11-12 02:26:26 +0000144static bool InsertRootInitializers(Function &F, ArrayRef<AllocaInst *> Roots) {
Philip Reames71649b02015-01-15 19:29:42 +0000145 // Scroll past alloca instructions.
146 BasicBlock::iterator IP = F.getEntryBlock().begin();
Philip Reamesb0a04ac2015-01-15 19:39:17 +0000147 while (isa<AllocaInst>(IP))
148 ++IP;
Philip Reames71649b02015-01-15 19:29:42 +0000149
150 // Search for initializers in the initial BB.
Philip Reamesb0a04ac2015-01-15 19:39:17 +0000151 SmallPtrSet<AllocaInst *, 16> InitedRoots;
Duncan P. N. Exon Smith030cf8e2015-10-09 18:44:40 +0000152 for (; !CouldBecomeSafePoint(&*IP); ++IP)
Philip Reames71649b02015-01-15 19:29:42 +0000153 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
154 if (AllocaInst *AI =
Philip Reamesb0a04ac2015-01-15 19:39:17 +0000155 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Philip Reames71649b02015-01-15 19:29:42 +0000156 InitedRoots.insert(AI);
157
158 // Add root initializers.
159 bool MadeChange = false;
160
Philip Reames78a558a2018-11-12 02:26:26 +0000161 for (AllocaInst *Root : Roots)
162 if (!InitedRoots.count(Root)) {
Philip Reamesb0a04ac2015-01-15 19:39:17 +0000163 StoreInst *SI = new StoreInst(
Philip Reames78a558a2018-11-12 02:26:26 +0000164 ConstantPointerNull::get(cast<PointerType>(Root->getAllocatedType())),
165 Root);
166 SI->insertAfter(Root);
Philip Reames71649b02015-01-15 19:29:42 +0000167 MadeChange = true;
168 }
169
170 return MadeChange;
171}
172
Philip Reames71649b02015-01-15 19:29:42 +0000173/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
174/// Leave gcroot intrinsics; the code generator needs to see those.
175bool LowerIntrinsics::runOnFunction(Function &F) {
176 // Quick exit for functions that do not use GC.
177 if (!F.hasGC())
178 return false;
179
180 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
181 GCStrategy &S = FI.getStrategy();
182
Philip Reames4708fed2018-11-11 21:13:09 +0000183 return DoLowering(F, S);
Philip Reames71649b02015-01-15 19:29:42 +0000184}
185
Philip Reames4708fed2018-11-11 21:13:09 +0000186/// Lower barriers out of existance (if the associated GCStrategy hasn't
187/// already done so...), and insert initializing stores to roots as a defensive
188/// measure. Given we're going to report all roots live at all safepoints, we
189/// need to be able to ensure each root has been initialized by the point the
190/// first safepoint is reached. This really should have been done by the
191/// frontend, but the old API made this non-obvious, so we do a potentially
192/// redundant store just in case.
193bool LowerIntrinsics::DoLowering(Function &F, GCStrategy &S) {
Philip Reamesb0a04ac2015-01-15 19:39:17 +0000194 SmallVector<AllocaInst *, 32> Roots;
Philip Reames71649b02015-01-15 19:29:42 +0000195
196 bool MadeChange = false;
Philip Reames78a558a2018-11-12 02:26:26 +0000197 for (BasicBlock &BB : F)
198 for (BasicBlock::iterator II = BB.begin(), E = BB.end(); II != E;) {
199 IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++);
200 if (!CI)
201 continue;
202
203 Function *F = CI->getCalledFunction();
204 switch (F->getIntrinsicID()) {
205 default: break;
206 case Intrinsic::gcwrite: {
207 // Replace a write barrier with a simple store.
208 Value *St = new StoreInst(CI->getArgOperand(0),
209 CI->getArgOperand(2), CI);
210 CI->replaceAllUsesWith(St);
211 CI->eraseFromParent();
212 MadeChange = true;
213 break;
214 }
215 case Intrinsic::gcread: {
216 // Replace a read barrier with a simple load.
217 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
218 Ld->takeName(CI);
219 CI->replaceAllUsesWith(Ld);
220 CI->eraseFromParent();
221 MadeChange = true;
222 break;
223 }
224 case Intrinsic::gcroot: {
225 // Initialize the GC root, but do not delete the intrinsic. The
226 // backend needs the intrinsic to flag the stack slot.
227 Roots.push_back(
228 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
229 break;
230 }
Philip Reames71649b02015-01-15 19:29:42 +0000231 }
232 }
Philip Reames71649b02015-01-15 19:29:42 +0000233
234 if (Roots.size())
Philip Reames78a558a2018-11-12 02:26:26 +0000235 MadeChange |= InsertRootInitializers(F, Roots);
Philip Reames71649b02015-01-15 19:29:42 +0000236
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 Reamesb0a04ac2015-01-15 19:39:17 +0000248GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
Philip Reames71649b02015-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 Krameraf18e012016-06-12 15:39:02 +0000259 const DebugLoc &DL) const {
Jim Grosbach19696da2015-05-18 18:43:14 +0000260 MCSymbol *Label = MBB.getParent()->getContext().createTempSymbol();
Philip Reames71649b02015-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) {
Philip Reamesb884de42018-11-12 20:15:34 +0000266 // Find the return address (next instruction), since that's what will be on
267 // the stack when the call is suspended and we need to inspect the stack.
Philip Reames71649b02015-01-15 19:29:42 +0000268 MachineBasicBlock::iterator RAI = CI;
269 ++RAI;
270
Philip Reames46063052018-11-12 22:03:53 +0000271 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
272 FI->addSafePoint(Label, CI->getDebugLoc());
Philip Reames71649b02015-01-15 19:29:42 +0000273}
274
275void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
Philip Reames78a558a2018-11-12 02:26:26 +0000276 for (MachineBasicBlock &MBB : MF)
277 for (MachineBasicBlock::iterator MI = MBB.begin(), ME = MBB.end();
Philip Reamesb0a04ac2015-01-15 19:39:17 +0000278 MI != ME; ++MI)
Philip Reames8a660bd2015-01-16 19:33:28 +0000279 if (MI->isCall()) {
280 // Do not treat tail or sibling call sites as safe points. This is
281 // legal since any arguments passed to the callee which live in the
282 // remnants of the callers frame will be owned and updated by the
283 // callee if required.
284 if (MI->isTerminator())
285 continue;
Philip Reames71649b02015-01-15 19:29:42 +0000286 VisitCallPoint(MI);
Philip Reames8a660bd2015-01-16 19:33:28 +0000287 }
Philip Reames71649b02015-01-15 19:29:42 +0000288}
289
290void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
Eric Christopher6de800e2015-02-20 18:44:15 +0000291 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Philip Reames71649b02015-01-15 19:29:42 +0000292 assert(TFI && "TargetRegisterInfo not available!");
293
294 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
295 RI != FI->roots_end();) {
296 // If the root references a dead object, no need to keep it.
Matthias Braunf79c57a2016-07-28 18:40:00 +0000297 if (MF.getFrameInfo().isDeadObjectIndex(RI->Num)) {
Philip Reames71649b02015-01-15 19:29:42 +0000298 RI = FI->removeStackRoot(RI);
299 } else {
James Y Knight276ea222015-08-15 02:32:35 +0000300 unsigned FrameReg; // FIXME: surely GCRoot ought to store the
301 // register that the offset is from?
302 RI->StackOffset = TFI->getFrameIndexReference(MF, RI->Num, FrameReg);
Philip Reames71649b02015-01-15 19:29:42 +0000303 ++RI;
304 }
305 }
306}
307
308bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
309 // Quick exit for functions that do not use GC.
Matthias Braund3181392017-12-15 22:22:58 +0000310 if (!MF.getFunction().hasGC())
Philip Reames71649b02015-01-15 19:29:42 +0000311 return false;
312
Matthias Braund3181392017-12-15 22:22:58 +0000313 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(MF.getFunction());
Philip Reames71649b02015-01-15 19:29:42 +0000314 MMI = &getAnalysis<MachineModuleInfo>();
Eric Christopher6de800e2015-02-20 18:44:15 +0000315 TII = MF.getSubtarget().getInstrInfo();
Philip Reames71649b02015-01-15 19:29:42 +0000316
Philip Reamesc47a3ae2015-04-02 05:00:40 +0000317 // Find the size of the stack frame. There may be no correct static frame
318 // size, we use UINT64_MAX to represent this.
Matthias Braunf79c57a2016-07-28 18:40:00 +0000319 const MachineFrameInfo &MFI = MF.getFrameInfo();
Philip Reamesc47a3ae2015-04-02 05:00:40 +0000320 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Matthias Braunf79c57a2016-07-28 18:40:00 +0000321 const bool DynamicFrameSize = MFI.hasVarSizedObjects() ||
Philip Reamesc47a3ae2015-04-02 05:00:40 +0000322 RegInfo->needsStackRealignment(MF);
Matthias Braunf79c57a2016-07-28 18:40:00 +0000323 FI->setFrameSize(DynamicFrameSize ? UINT64_MAX : MFI.getStackSize());
Philip Reames71649b02015-01-15 19:29:42 +0000324
325 // Find all safe points.
Philip Reamesc47a3ae2015-04-02 05:00:40 +0000326 if (FI->getStrategy().needsSafePoints())
327 FindSafePoints(MF);
Philip Reames71649b02015-01-15 19:29:42 +0000328
Philip Reamesc47a3ae2015-04-02 05:00:40 +0000329 // Find the concrete stack offsets for all roots (stack slots)
Philip Reames71649b02015-01-15 19:29:42 +0000330 FindStackOffsets(MF);
331
332 return false;
333}