blob: 9907a3022534bd25edd2524822dfdc1d4fa41ff1 [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 {
Philip Reamesb8714412015-01-15 19:39:17 +000041 bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
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();
47 const char *getPassName() const override;
48 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 {
59 const TargetMachine *TM;
60 GCFunctionInfo *FI;
61 MachineModuleInfo *MMI;
62 const TargetInstrInfo *TII;
Philip Reamesf27f3732015-01-15 19:29:42 +000063
Philip Reamesb8714412015-01-15 19:39:17 +000064 void FindSafePoints(MachineFunction &MF);
65 void VisitCallPoint(MachineBasicBlock::iterator MI);
66 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
67 DebugLoc DL) const;
Philip Reamesf27f3732015-01-15 19:29:42 +000068
Philip Reamesb8714412015-01-15 19:39:17 +000069 void FindStackOffsets(MachineFunction &MF);
Philip Reamesf27f3732015-01-15 19:29:42 +000070
Philip Reamesb8714412015-01-15 19:39:17 +000071public:
72 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000073
Philip Reamesb8714412015-01-15 19:39:17 +000074 GCMachineCodeAnalysis();
75 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000076
Philip Reamesb8714412015-01-15 19:39:17 +000077 bool runOnMachineFunction(MachineFunction &MF) override;
78};
Philip Reamesf27f3732015-01-15 19:29:42 +000079}
80
81// -----------------------------------------------------------------------------
82
Philip Reamesb8714412015-01-15 19:39:17 +000083INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
84 false)
Philip Reamesf27f3732015-01-15 19:29:42 +000085INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
86INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
87
Philip Reamesb8714412015-01-15 19:39:17 +000088FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
Philip Reamesf27f3732015-01-15 19:29:42 +000089
90char LowerIntrinsics::ID = 0;
91
Philip Reamesb8714412015-01-15 19:39:17 +000092LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
93 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
94}
Philip Reamesf27f3732015-01-15 19:29:42 +000095
96const char *LowerIntrinsics::getPassName() const {
97 return "Lower Garbage Collection Instructions";
98}
99
100void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
101 FunctionPass::getAnalysisUsage(AU);
102 AU.addRequired<GCModuleInfo>();
103 AU.addPreserved<DominatorTreeWrapperPass>();
104}
105
Philip Reames66c9fb02015-01-15 19:49:25 +0000106static bool NeedsDefaultLoweringPass(const GCStrategy &C) {
107 // Default lowering is necessary only if read or write barriers have a default
108 // action. The default for roots is no action.
109 return !C.customWriteBarrier() || !C.customReadBarrier() ||
110 C.initializeRoots();
111}
112
113static bool NeedsCustomLoweringPass(const GCStrategy &C) {
114 // Custom lowering is only necessary if enabled for some action.
115 return C.customWriteBarrier() || C.customReadBarrier() || C.customRoots();
116}
117
118
119
Philip Reamesf27f3732015-01-15 19:29:42 +0000120/// doInitialization - If this module uses the GC intrinsics, find them now.
121bool LowerIntrinsics::doInitialization(Module &M) {
122 // FIXME: This is rather antisocial in the context of a JIT since it performs
123 // work against the entire module. But this cannot be done at
124 // runFunction time (initializeCustomLowering likely needs to change
125 // the module).
126 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
127 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
128 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
129 if (!I->isDeclaration() && I->hasGC())
130 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
131
132 bool MadeChange = false;
133 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
134 if (NeedsCustomLoweringPass(**I))
135 if ((*I)->initializeCustomLowering(M))
136 MadeChange = true;
137
138 return MadeChange;
139}
140
Philip Reames66c9fb02015-01-15 19:49:25 +0000141
142/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
143/// instruction could introduce a safe point.
144static bool CouldBecomeSafePoint(Instruction *I) {
145 // The natural definition of instructions which could introduce safe points
146 // are:
147 //
148 // - call, invoke (AfterCall, BeforeCall)
149 // - phis (Loops)
150 // - invoke, ret, unwind (Exit)
151 //
152 // However, instructions as seemingly inoccuous as arithmetic can become
153 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
154 // it is necessary to take a conservative approach.
155
156 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
157 isa<LoadInst>(I))
158 return false;
159
160 // llvm.gcroot is safe because it doesn't do anything at runtime.
161 if (CallInst *CI = dyn_cast<CallInst>(I))
162 if (Function *F = CI->getCalledFunction())
163 if (unsigned IID = F->getIntrinsicID())
164 if (IID == Intrinsic::gcroot)
165 return false;
166
167 return true;
168}
169
170static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
171 unsigned Count) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000172 // Scroll past alloca instructions.
173 BasicBlock::iterator IP = F.getEntryBlock().begin();
Philip Reamesb8714412015-01-15 19:39:17 +0000174 while (isa<AllocaInst>(IP))
175 ++IP;
Philip Reamesf27f3732015-01-15 19:29:42 +0000176
177 // Search for initializers in the initial BB.
Philip Reamesb8714412015-01-15 19:39:17 +0000178 SmallPtrSet<AllocaInst *, 16> InitedRoots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000179 for (; !CouldBecomeSafePoint(IP); ++IP)
180 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
181 if (AllocaInst *AI =
Philip Reamesb8714412015-01-15 19:39:17 +0000182 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Philip Reamesf27f3732015-01-15 19:29:42 +0000183 InitedRoots.insert(AI);
184
185 // Add root initializers.
186 bool MadeChange = false;
187
188 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
189 if (!InitedRoots.count(*I)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000190 StoreInst *SI = new StoreInst(
191 ConstantPointerNull::get(cast<PointerType>(
192 cast<PointerType>((*I)->getType())->getElementType())),
193 *I);
Philip Reamesf27f3732015-01-15 19:29:42 +0000194 SI->insertAfter(*I);
195 MadeChange = true;
196 }
197
198 return MadeChange;
199}
200
Philip Reamesf27f3732015-01-15 19:29:42 +0000201
202/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
203/// Leave gcroot intrinsics; the code generator needs to see those.
204bool LowerIntrinsics::runOnFunction(Function &F) {
205 // Quick exit for functions that do not use GC.
206 if (!F.hasGC())
207 return false;
208
209 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
210 GCStrategy &S = FI.getStrategy();
211
212 bool MadeChange = false;
213
214 if (NeedsDefaultLoweringPass(S))
215 MadeChange |= PerformDefaultLowering(F, S);
216
217 bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
218 if (UseCustomLoweringPass)
219 MadeChange |= S.performCustomLowering(F);
220
221 // Custom lowering may modify the CFG, so dominators must be recomputed.
222 if (UseCustomLoweringPass) {
223 if (DominatorTreeWrapperPass *DTWP =
224 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
225 DTWP->getDomTree().recalculate(F);
226 }
227
228 return MadeChange;
229}
230
231bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
232 bool LowerWr = !S.customWriteBarrier();
233 bool LowerRd = !S.customReadBarrier();
234 bool InitRoots = S.initializeRoots();
235
Philip Reamesb8714412015-01-15 19:39:17 +0000236 SmallVector<AllocaInst *, 32> Roots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000237
238 bool MadeChange = false;
239 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
240 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
241 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
242 Function *F = CI->getCalledFunction();
243 switch (F->getIntrinsicID()) {
244 case Intrinsic::gcwrite:
245 if (LowerWr) {
246 // Replace a write barrier with a simple store.
Philip Reamesb8714412015-01-15 19:39:17 +0000247 Value *St =
248 new StoreInst(CI->getArgOperand(0), CI->getArgOperand(2), CI);
Philip Reamesf27f3732015-01-15 19:29:42 +0000249 CI->replaceAllUsesWith(St);
250 CI->eraseFromParent();
251 }
252 break;
253 case Intrinsic::gcread:
254 if (LowerRd) {
255 // Replace a read barrier with a simple load.
256 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
257 Ld->takeName(CI);
258 CI->replaceAllUsesWith(Ld);
259 CI->eraseFromParent();
260 }
261 break;
262 case Intrinsic::gcroot:
263 if (InitRoots) {
264 // Initialize the GC root, but do not delete the intrinsic. The
265 // backend needs the intrinsic to flag the stack slot.
Philip Reamesb8714412015-01-15 19:39:17 +0000266 Roots.push_back(
267 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
Philip Reamesf27f3732015-01-15 19:29:42 +0000268 }
269 break;
270 default:
271 continue;
272 }
273
274 MadeChange = true;
275 }
276 }
277 }
278
279 if (Roots.size())
280 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
281
282 return MadeChange;
283}
284
285// -----------------------------------------------------------------------------
286
287char GCMachineCodeAnalysis::ID = 0;
288char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
289
290INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
291 "Analyze Machine Code For Garbage Collection", false, false)
292
Philip Reamesb8714412015-01-15 19:39:17 +0000293GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
Philip Reamesf27f3732015-01-15 19:29:42 +0000294
295void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
296 MachineFunctionPass::getAnalysisUsage(AU);
297 AU.setPreservesAll();
298 AU.addRequired<MachineModuleInfo>();
299 AU.addRequired<GCModuleInfo>();
300}
301
302MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
303 MachineBasicBlock::iterator MI,
304 DebugLoc DL) const {
305 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
306 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
307 return Label;
308}
309
310void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
311 // Find the return address (next instruction), too, so as to bracket the call
312 // instruction.
313 MachineBasicBlock::iterator RAI = CI;
314 ++RAI;
315
316 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000317 MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000318 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
319 }
320
321 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000322 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000323 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
324 }
325}
326
327void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
Philip Reamesb8714412015-01-15 19:39:17 +0000328 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
329 ++BBI)
330 for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
331 MI != ME; ++MI)
Philip Reamesf27f3732015-01-15 19:29:42 +0000332 if (MI->isCall())
333 VisitCallPoint(MI);
334}
335
336void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
337 const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
338 assert(TFI && "TargetRegisterInfo not available!");
339
340 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
341 RI != FI->roots_end();) {
342 // If the root references a dead object, no need to keep it.
343 if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
344 RI = FI->removeStackRoot(RI);
345 } else {
346 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
347 ++RI;
348 }
349 }
350}
351
352bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
353 // Quick exit for functions that do not use GC.
354 if (!MF.getFunction()->hasGC())
355 return false;
356
357 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
358 if (!FI->getStrategy().needsSafePoints())
359 return false;
360
361 TM = &MF.getTarget();
362 MMI = &getAnalysis<MachineModuleInfo>();
363 TII = TM->getSubtargetImpl()->getInstrInfo();
364
365 // Find the size of the stack frame.
366 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
367
368 // Find all safe points.
369 if (FI->getStrategy().customSafePoints()) {
370 FI->getStrategy().findCustomSafePoints(*FI, MF);
371 } else {
372 FindSafePoints(MF);
373 }
374
375 // Find the stack offsets for all roots.
376 FindStackOffsets(MF);
377
378 return false;
379}