blob: 10da4003684e024e359bba93047fd053877559a0 [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
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/IR/Dominators.h"
21#include "llvm/IR/IntrinsicInst.h"
22#include "llvm/IR/Module.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/ErrorHandling.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/Target/TargetFrameLowering.h"
27#include "llvm/Target/TargetInstrInfo.h"
28#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetRegisterInfo.h"
30#include "llvm/Target/TargetSubtargetInfo.h"
31
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 {
41 static bool NeedsDefaultLoweringPass(const GCStrategy &C);
42 static bool NeedsCustomLoweringPass(const GCStrategy &C);
43 static bool CouldBecomeSafePoint(Instruction *I);
44 bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
45 static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
46 unsigned Count);
Philip Reamesf27f3732015-01-15 19:29:42 +000047
Philip Reamesb8714412015-01-15 19:39:17 +000048public:
49 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000050
Philip Reamesb8714412015-01-15 19:39:17 +000051 LowerIntrinsics();
52 const char *getPassName() const override;
53 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000054
Philip Reamesb8714412015-01-15 19:39:17 +000055 bool doInitialization(Module &M) override;
56 bool runOnFunction(Function &F) override;
57};
Philip Reamesf27f3732015-01-15 19:29:42 +000058
Philip Reamesb8714412015-01-15 19:39:17 +000059/// GCMachineCodeAnalysis - This is a target-independent pass over the machine
60/// function representation to identify safe points for the garbage collector
61/// in the machine code. It inserts labels at safe points and populates a
62/// GCMetadata record for each function.
63class GCMachineCodeAnalysis : public MachineFunctionPass {
64 const TargetMachine *TM;
65 GCFunctionInfo *FI;
66 MachineModuleInfo *MMI;
67 const TargetInstrInfo *TII;
Philip Reamesf27f3732015-01-15 19:29:42 +000068
Philip Reamesb8714412015-01-15 19:39:17 +000069 void FindSafePoints(MachineFunction &MF);
70 void VisitCallPoint(MachineBasicBlock::iterator MI);
71 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
72 DebugLoc DL) const;
Philip Reamesf27f3732015-01-15 19:29:42 +000073
Philip Reamesb8714412015-01-15 19:39:17 +000074 void FindStackOffsets(MachineFunction &MF);
Philip Reamesf27f3732015-01-15 19:29:42 +000075
Philip Reamesb8714412015-01-15 19:39:17 +000076public:
77 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000078
Philip Reamesb8714412015-01-15 19:39:17 +000079 GCMachineCodeAnalysis();
80 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000081
Philip Reamesb8714412015-01-15 19:39:17 +000082 bool runOnMachineFunction(MachineFunction &MF) override;
83};
Philip Reamesf27f3732015-01-15 19:29:42 +000084}
85
86// -----------------------------------------------------------------------------
87
Philip Reamesb8714412015-01-15 19:39:17 +000088INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
89 false)
Philip Reamesf27f3732015-01-15 19:29:42 +000090INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
91INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
92
Philip Reamesb8714412015-01-15 19:39:17 +000093FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
Philip Reamesf27f3732015-01-15 19:29:42 +000094
95char LowerIntrinsics::ID = 0;
96
Philip Reamesb8714412015-01-15 19:39:17 +000097LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
98 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
99}
Philip Reamesf27f3732015-01-15 19:29:42 +0000100
101const char *LowerIntrinsics::getPassName() const {
102 return "Lower Garbage Collection Instructions";
103}
104
105void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
106 FunctionPass::getAnalysisUsage(AU);
107 AU.addRequired<GCModuleInfo>();
108 AU.addPreserved<DominatorTreeWrapperPass>();
109}
110
111/// doInitialization - If this module uses the GC intrinsics, find them now.
112bool LowerIntrinsics::doInitialization(Module &M) {
113 // FIXME: This is rather antisocial in the context of a JIT since it performs
114 // work against the entire module. But this cannot be done at
115 // runFunction time (initializeCustomLowering likely needs to change
116 // the module).
117 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
118 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
119 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
120 if (!I->isDeclaration() && I->hasGC())
121 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
122
123 bool MadeChange = false;
124 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
125 if (NeedsCustomLoweringPass(**I))
126 if ((*I)->initializeCustomLowering(M))
127 MadeChange = true;
128
129 return MadeChange;
130}
131
132bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
Philip Reamesb8714412015-01-15 19:39:17 +0000133 unsigned Count) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000134 // Scroll past alloca instructions.
135 BasicBlock::iterator IP = F.getEntryBlock().begin();
Philip Reamesb8714412015-01-15 19:39:17 +0000136 while (isa<AllocaInst>(IP))
137 ++IP;
Philip Reamesf27f3732015-01-15 19:29:42 +0000138
139 // Search for initializers in the initial BB.
Philip Reamesb8714412015-01-15 19:39:17 +0000140 SmallPtrSet<AllocaInst *, 16> InitedRoots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000141 for (; !CouldBecomeSafePoint(IP); ++IP)
142 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
143 if (AllocaInst *AI =
Philip Reamesb8714412015-01-15 19:39:17 +0000144 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Philip Reamesf27f3732015-01-15 19:29:42 +0000145 InitedRoots.insert(AI);
146
147 // Add root initializers.
148 bool MadeChange = false;
149
150 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
151 if (!InitedRoots.count(*I)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000152 StoreInst *SI = new StoreInst(
153 ConstantPointerNull::get(cast<PointerType>(
154 cast<PointerType>((*I)->getType())->getElementType())),
155 *I);
Philip Reamesf27f3732015-01-15 19:29:42 +0000156 SI->insertAfter(*I);
157 MadeChange = true;
158 }
159
160 return MadeChange;
161}
162
163bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
164 // Default lowering is necessary only if read or write barriers have a default
165 // action. The default for roots is no action.
Philip Reamesb8714412015-01-15 19:39:17 +0000166 return !C.customWriteBarrier() || !C.customReadBarrier() ||
167 C.initializeRoots();
Philip Reamesf27f3732015-01-15 19:29:42 +0000168}
169
170bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
171 // Custom lowering is only necessary if enabled for some action.
Philip Reamesb8714412015-01-15 19:39:17 +0000172 return C.customWriteBarrier() || C.customReadBarrier() || C.customRoots();
Philip Reamesf27f3732015-01-15 19:29:42 +0000173}
174
175/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
176/// instruction could introduce a safe point.
177bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
178 // The natural definition of instructions which could introduce safe points
179 // are:
180 //
181 // - call, invoke (AfterCall, BeforeCall)
182 // - phis (Loops)
183 // - invoke, ret, unwind (Exit)
184 //
185 // However, instructions as seemingly inoccuous as arithmetic can become
186 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
187 // it is necessary to take a conservative approach.
188
Philip Reamesb8714412015-01-15 19:39:17 +0000189 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
190 isa<LoadInst>(I))
Philip Reamesf27f3732015-01-15 19:29:42 +0000191 return false;
192
193 // llvm.gcroot is safe because it doesn't do anything at runtime.
194 if (CallInst *CI = dyn_cast<CallInst>(I))
195 if (Function *F = CI->getCalledFunction())
196 if (unsigned IID = F->getIntrinsicID())
197 if (IID == Intrinsic::gcroot)
198 return false;
199
200 return true;
201}
202
203/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
204/// Leave gcroot intrinsics; the code generator needs to see those.
205bool LowerIntrinsics::runOnFunction(Function &F) {
206 // Quick exit for functions that do not use GC.
207 if (!F.hasGC())
208 return false;
209
210 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
211 GCStrategy &S = FI.getStrategy();
212
213 bool MadeChange = false;
214
215 if (NeedsDefaultLoweringPass(S))
216 MadeChange |= PerformDefaultLowering(F, S);
217
218 bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
219 if (UseCustomLoweringPass)
220 MadeChange |= S.performCustomLowering(F);
221
222 // Custom lowering may modify the CFG, so dominators must be recomputed.
223 if (UseCustomLoweringPass) {
224 if (DominatorTreeWrapperPass *DTWP =
225 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
226 DTWP->getDomTree().recalculate(F);
227 }
228
229 return MadeChange;
230}
231
232bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
233 bool LowerWr = !S.customWriteBarrier();
234 bool LowerRd = !S.customReadBarrier();
235 bool InitRoots = S.initializeRoots();
236
Philip Reamesb8714412015-01-15 19:39:17 +0000237 SmallVector<AllocaInst *, 32> Roots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000238
239 bool MadeChange = false;
240 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
241 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
242 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
243 Function *F = CI->getCalledFunction();
244 switch (F->getIntrinsicID()) {
245 case Intrinsic::gcwrite:
246 if (LowerWr) {
247 // Replace a write barrier with a simple store.
Philip Reamesb8714412015-01-15 19:39:17 +0000248 Value *St =
249 new StoreInst(CI->getArgOperand(0), CI->getArgOperand(2), CI);
Philip Reamesf27f3732015-01-15 19:29:42 +0000250 CI->replaceAllUsesWith(St);
251 CI->eraseFromParent();
252 }
253 break;
254 case Intrinsic::gcread:
255 if (LowerRd) {
256 // Replace a read barrier with a simple load.
257 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
258 Ld->takeName(CI);
259 CI->replaceAllUsesWith(Ld);
260 CI->eraseFromParent();
261 }
262 break;
263 case Intrinsic::gcroot:
264 if (InitRoots) {
265 // Initialize the GC root, but do not delete the intrinsic. The
266 // backend needs the intrinsic to flag the stack slot.
Philip Reamesb8714412015-01-15 19:39:17 +0000267 Roots.push_back(
268 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
Philip Reamesf27f3732015-01-15 19:29:42 +0000269 }
270 break;
271 default:
272 continue;
273 }
274
275 MadeChange = true;
276 }
277 }
278 }
279
280 if (Roots.size())
281 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
282
283 return MadeChange;
284}
285
286// -----------------------------------------------------------------------------
287
288char GCMachineCodeAnalysis::ID = 0;
289char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
290
291INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
292 "Analyze Machine Code For Garbage Collection", false, false)
293
Philip Reamesb8714412015-01-15 19:39:17 +0000294GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
Philip Reamesf27f3732015-01-15 19:29:42 +0000295
296void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
297 MachineFunctionPass::getAnalysisUsage(AU);
298 AU.setPreservesAll();
299 AU.addRequired<MachineModuleInfo>();
300 AU.addRequired<GCModuleInfo>();
301}
302
303MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
304 MachineBasicBlock::iterator MI,
305 DebugLoc DL) const {
306 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
307 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
308 return Label;
309}
310
311void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
312 // Find the return address (next instruction), too, so as to bracket the call
313 // instruction.
314 MachineBasicBlock::iterator RAI = CI;
315 ++RAI;
316
317 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000318 MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000319 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
320 }
321
322 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000323 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000324 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
325 }
326}
327
328void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
Philip Reamesb8714412015-01-15 19:39:17 +0000329 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
330 ++BBI)
331 for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
332 MI != ME; ++MI)
Philip Reamesf27f3732015-01-15 19:29:42 +0000333 if (MI->isCall())
334 VisitCallPoint(MI);
335}
336
337void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
338 const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
339 assert(TFI && "TargetRegisterInfo not available!");
340
341 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
342 RI != FI->roots_end();) {
343 // If the root references a dead object, no need to keep it.
344 if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
345 RI = FI->removeStackRoot(RI);
346 } else {
347 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
348 ++RI;
349 }
350 }
351}
352
353bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
354 // Quick exit for functions that do not use GC.
355 if (!MF.getFunction()->hasGC())
356 return false;
357
358 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
359 if (!FI->getStrategy().needsSafePoints())
360 return false;
361
362 TM = &MF.getTarget();
363 MMI = &getAnalysis<MachineModuleInfo>();
364 TII = TM->getSubtargetImpl()->getInstrInfo();
365
366 // Find the size of the stack frame.
367 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
368
369 // Find all safe points.
370 if (FI->getStrategy().customSafePoints()) {
371 FI->getStrategy().findCustomSafePoints(*FI, MF);
372 } else {
373 FindSafePoints(MF);
374 }
375
376 // Find the stack offsets for all roots.
377 FindStackOffsets(MF);
378
379 return false;
380}