blob: 629a2e13dee4c73a59fdc7d5c2231d93cfbcfb0c [file] [log] [blame]
Gordon Henriksen364caf02007-09-29 02:13:43 +00001//===-- Collector.cpp - Garbage collection infrastructure -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Gordon Henriksen364caf02007-09-29 02:13:43 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements target- and collector-independent garbage collection
11// infrastructure.
12//
13//===----------------------------------------------------------------------===//
14
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000015#include "llvm/CodeGen/GCStrategy.h"
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000016#include "llvm/CodeGen/Passes.h"
Gordon Henriksen364caf02007-09-29 02:13:43 +000017#include "llvm/IntrinsicInst.h"
18#include "llvm/Module.h"
Gordon Henriksen364caf02007-09-29 02:13:43 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000022#include "llvm/CodeGen/MachineModuleInfo.h"
Gordon Henriksen364caf02007-09-29 02:13:43 +000023#include "llvm/Target/TargetFrameInfo.h"
24#include "llvm/Target/TargetInstrInfo.h"
25#include "llvm/Target/TargetMachine.h"
26#include "llvm/Support/Compiler.h"
27
28using namespace llvm;
29
30namespace {
31
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000032 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
33 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
34 /// directed by the Collector. It also performs automatic root initialization
35 /// and custom intrinsic lowering.
Gordon Henriksen364caf02007-09-29 02:13:43 +000036 class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000037 static bool NeedsDefaultLoweringPass(const Collector &C);
38 static bool NeedsCustomLoweringPass(const Collector &C);
Gordon Henriksen364caf02007-09-29 02:13:43 +000039 static bool CouldBecomeSafePoint(Instruction *I);
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000040 bool PerformDefaultLowering(Function &F, Collector &Coll);
41 static bool InsertRootInitializers(Function &F,
Gordon Henriksen364caf02007-09-29 02:13:43 +000042 AllocaInst **Roots, unsigned Count);
43
44 public:
45 static char ID;
46
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000047 LowerIntrinsics();
Gordon Henriksen364caf02007-09-29 02:13:43 +000048 const char *getPassName() const;
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000049 void getAnalysisUsage(AnalysisUsage &AU) const;
Gordon Henriksen364caf02007-09-29 02:13:43 +000050
51 bool doInitialization(Module &M);
52 bool runOnFunction(Function &F);
53 };
54
55
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000056 /// MachineCodeAnalysis - This is a target-independent pass over the machine
57 /// function representation to identify safe points for the garbage collector
58 /// in the machine code. It inserts labels at safe points and populates a
59 /// CollectorMetadata record for each function.
Gordon Henriksen364caf02007-09-29 02:13:43 +000060 class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000061 const TargetMachine *TM;
Gordon Henriksen364caf02007-09-29 02:13:43 +000062 CollectorMetadata *MD;
63 MachineModuleInfo *MMI;
64 const TargetInstrInfo *TII;
65 MachineFrameInfo *MFI;
66
67 void FindSafePoints(MachineFunction &MF);
68 void VisitCallPoint(MachineBasicBlock::iterator MI);
69 unsigned InsertLabel(MachineBasicBlock &MBB,
70 MachineBasicBlock::iterator MI) const;
71
72 void FindStackOffsets(MachineFunction &MF);
73
74 public:
75 static char ID;
76
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000077 MachineCodeAnalysis();
Gordon Henriksen364caf02007-09-29 02:13:43 +000078 const char *getPassName() const;
79 void getAnalysisUsage(AnalysisUsage &AU) const;
80
81 bool runOnMachineFunction(MachineFunction &MF);
82 };
83
84}
85
86// -----------------------------------------------------------------------------
87
Gordon Henriksen364caf02007-09-29 02:13:43 +000088Collector::Collector() :
89 NeededSafePoints(0),
90 CustomReadBarriers(false),
91 CustomWriteBarriers(false),
92 CustomRoots(false),
Gordon Henriksenc317a602008-08-17 12:08:44 +000093 InitRoots(true),
94 UsesMetadata(false)
Gordon Henriksen364caf02007-09-29 02:13:43 +000095{}
96
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000097Collector::~Collector() {
98 for (iterator I = begin(), E = end(); I != E; ++I)
99 delete *I;
100
101 Functions.clear();
Gordon Henriksen364caf02007-09-29 02:13:43 +0000102}
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000103
104bool Collector::initializeCustomLowering(Module &M) { return false; }
105
106bool Collector::performCustomLowering(Function &F) {
107 cerr << "gc " << getName() << " must override performCustomLowering.\n";
Gordon Henriksen364caf02007-09-29 02:13:43 +0000108 abort();
109 return 0;
110}
111
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000112CollectorMetadata *Collector::insertFunctionMetadata(const Function &F) {
113 CollectorMetadata *CM = new CollectorMetadata(F, *this);
114 Functions.push_back(CM);
115 return CM;
116}
Gordon Henriksen364caf02007-09-29 02:13:43 +0000117
118// -----------------------------------------------------------------------------
119
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000120FunctionPass *llvm::createGCLoweringPass() {
121 return new LowerIntrinsics();
122}
123
Gordon Henriksen364caf02007-09-29 02:13:43 +0000124char LowerIntrinsics::ID = 0;
125
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000126LowerIntrinsics::LowerIntrinsics()
Gordon Henriksena6c99252007-12-22 17:27:01 +0000127 : FunctionPass((intptr_t)&ID) {}
Gordon Henriksen364caf02007-09-29 02:13:43 +0000128
129const char *LowerIntrinsics::getPassName() const {
130 return "Lower Garbage Collection Instructions";
131}
132
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000133void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
134 FunctionPass::getAnalysisUsage(AU);
135 AU.addRequired<CollectorModuleMetadata>();
136}
137
138/// doInitialization - If this module uses the GC intrinsics, find them now.
Gordon Henriksen364caf02007-09-29 02:13:43 +0000139bool LowerIntrinsics::doInitialization(Module &M) {
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000140 // FIXME: This is rather antisocial in the context of a JIT since it performs
141 // work against the entire module. But this cannot be done at
142 // runFunction time (initializeCustomLowering likely needs to change
143 // the module).
144 CollectorModuleMetadata *CMM = getAnalysisToUpdate<CollectorModuleMetadata>();
145 assert(CMM && "LowerIntrinsics didn't require CollectorModuleMetadata!?");
146 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
147 if (I->hasCollector())
148 CMM->get(*I); // Instantiate the Collector.
149
150 bool MadeChange = false;
151 for (CollectorModuleMetadata::iterator I = CMM->begin(),
152 E = CMM->end(); I != E; ++I)
153 if (NeedsCustomLoweringPass(**I))
154 if ((*I)->initializeCustomLowering(M))
155 MadeChange = true;
156
157 return MadeChange;
Gordon Henriksen364caf02007-09-29 02:13:43 +0000158}
159
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000160bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
Gordon Henriksen364caf02007-09-29 02:13:43 +0000161 unsigned Count) {
162 // Scroll past alloca instructions.
163 BasicBlock::iterator IP = F.getEntryBlock().begin();
164 while (isa<AllocaInst>(IP)) ++IP;
165
166 // Search for initializers in the initial BB.
167 SmallPtrSet<AllocaInst*,16> InitedRoots;
168 for (; !CouldBecomeSafePoint(IP); ++IP)
169 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
Anton Korobeynikovb04addd2008-05-06 22:52:30 +0000170 if (AllocaInst *AI =
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000171 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Gordon Henriksen364caf02007-09-29 02:13:43 +0000172 InitedRoots.insert(AI);
173
174 // Add root initializers.
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000175 bool MadeChange = false;
176
Gordon Henriksen364caf02007-09-29 02:13:43 +0000177 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000178 if (!InitedRoots.count(*I)) {
Gordon Henriksen364caf02007-09-29 02:13:43 +0000179 new StoreInst(ConstantPointerNull::get(cast<PointerType>(
180 cast<PointerType>((*I)->getType())->getElementType())),
181 *I, IP);
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000182 MadeChange = true;
183 }
184
185 return MadeChange;
186}
187
188bool LowerIntrinsics::NeedsDefaultLoweringPass(const Collector &C) {
189 // Default lowering is necessary only if read or write barriers have a default
190 // action. The default for roots is no action.
191 return !C.customWriteBarrier()
192 || !C.customReadBarrier()
193 || C.initializeRoots();
194}
195
196bool LowerIntrinsics::NeedsCustomLoweringPass(const Collector &C) {
197 // Custom lowering is only necessary if enabled for some action.
198 return C.customWriteBarrier()
199 || C.customReadBarrier()
200 || C.customRoots();
Gordon Henriksen364caf02007-09-29 02:13:43 +0000201}
202
203/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
204/// instruction could introduce a safe point.
205bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
206 // The natural definition of instructions which could introduce safe points
207 // are:
208 //
209 // - call, invoke (AfterCall, BeforeCall)
210 // - phis (Loops)
211 // - invoke, ret, unwind (Exit)
212 //
213 // However, instructions as seemingly inoccuous as arithmetic can become
214 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
215 // it is necessary to take a conservative approach.
216
217 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
218 isa<StoreInst>(I) || isa<LoadInst>(I))
219 return false;
220
221 // llvm.gcroot is safe because it doesn't do anything at runtime.
222 if (CallInst *CI = dyn_cast<CallInst>(I))
223 if (Function *F = CI->getCalledFunction())
224 if (unsigned IID = F->getIntrinsicID())
225 if (IID == Intrinsic::gcroot)
226 return false;
227
228 return true;
229}
230
231/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
232/// Leave gcroot intrinsics; the code generator needs to see those.
233bool LowerIntrinsics::runOnFunction(Function &F) {
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000234 // Quick exit for functions that do not use GC.
235 if (!F.hasCollector()) return false;
Gordon Henriksen364caf02007-09-29 02:13:43 +0000236
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000237 CollectorMetadata &MD = getAnalysis<CollectorModuleMetadata>().get(F);
238 Collector &Coll = MD.getCollector();
239
240 bool MadeChange = false;
241
242 if (NeedsDefaultLoweringPass(Coll))
243 MadeChange |= PerformDefaultLowering(F, Coll);
244
245 if (NeedsCustomLoweringPass(Coll))
246 MadeChange |= Coll.performCustomLowering(F);
247
248 return MadeChange;
249}
250
251bool LowerIntrinsics::PerformDefaultLowering(Function &F, Collector &Coll) {
Gordon Henriksen364caf02007-09-29 02:13:43 +0000252 bool LowerWr = !Coll.customWriteBarrier();
253 bool LowerRd = !Coll.customReadBarrier();
254 bool InitRoots = Coll.initializeRoots();
255
256 SmallVector<AllocaInst*,32> Roots;
257
258 bool MadeChange = false;
259 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
260 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
Gordon Henriksena6c99252007-12-22 17:27:01 +0000261 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
Gordon Henriksen364caf02007-09-29 02:13:43 +0000262 Function *F = CI->getCalledFunction();
Gordon Henriksena6c99252007-12-22 17:27:01 +0000263 switch (F->getIntrinsicID()) {
264 case Intrinsic::gcwrite:
265 if (LowerWr) {
266 // Replace a write barrier with a simple store.
267 Value *St = new StoreInst(CI->getOperand(1), CI->getOperand(3), CI);
268 CI->replaceAllUsesWith(St);
269 CI->eraseFromParent();
270 }
271 break;
272 case Intrinsic::gcread:
273 if (LowerRd) {
274 // Replace a read barrier with a simple load.
275 Value *Ld = new LoadInst(CI->getOperand(2), "", CI);
276 Ld->takeName(CI);
277 CI->replaceAllUsesWith(Ld);
278 CI->eraseFromParent();
279 }
280 break;
281 case Intrinsic::gcroot:
282 if (InitRoots) {
283 // Initialize the GC root, but do not delete the intrinsic. The
284 // backend needs the intrinsic to flag the stack slot.
285 Roots.push_back(cast<AllocaInst>(
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000286 CI->getOperand(1)->stripPointerCasts()));
Gordon Henriksena6c99252007-12-22 17:27:01 +0000287 }
288 break;
289 default:
Gordon Henriksen364caf02007-09-29 02:13:43 +0000290 continue;
291 }
292
293 MadeChange = true;
294 }
295 }
296 }
297
298 if (Roots.size())
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000299 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
Gordon Henriksen364caf02007-09-29 02:13:43 +0000300
301 return MadeChange;
302}
303
304// -----------------------------------------------------------------------------
305
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000306FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
307 return new MachineCodeAnalysis();
308}
309
Gordon Henriksen364caf02007-09-29 02:13:43 +0000310char MachineCodeAnalysis::ID = 0;
311
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000312MachineCodeAnalysis::MachineCodeAnalysis()
313 : MachineFunctionPass(intptr_t(&ID)) {}
Gordon Henriksen364caf02007-09-29 02:13:43 +0000314
315const char *MachineCodeAnalysis::getPassName() const {
316 return "Analyze Machine Code For Garbage Collection";
317}
318
319void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
320 MachineFunctionPass::getAnalysisUsage(AU);
321 AU.setPreservesAll();
322 AU.addRequired<MachineModuleInfo>();
323 AU.addRequired<CollectorModuleMetadata>();
324}
325
326unsigned MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
327 MachineBasicBlock::iterator MI) const {
328 unsigned Label = MMI->NextLabelID();
Dan Gohman44066042008-07-01 00:05:16 +0000329 BuildMI(MBB, MI, TII->get(TargetInstrInfo::GC_LABEL)).addImm(Label);
Gordon Henriksen364caf02007-09-29 02:13:43 +0000330 return Label;
331}
332
333void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
334 // Find the return address (next instruction), too, so as to bracket the call
335 // instruction.
336 MachineBasicBlock::iterator RAI = CI;
337 ++RAI;
338
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000339 if (MD->getCollector().needsSafePoint(GC::PreCall))
Gordon Henriksen364caf02007-09-29 02:13:43 +0000340 MD->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
341
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000342 if (MD->getCollector().needsSafePoint(GC::PostCall))
Gordon Henriksen364caf02007-09-29 02:13:43 +0000343 MD->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
344}
345
346void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
347 for (MachineFunction::iterator BBI = MF.begin(),
348 BBE = MF.end(); BBI != BBE; ++BBI)
349 for (MachineBasicBlock::iterator MI = BBI->begin(),
350 ME = BBI->end(); MI != ME; ++MI)
Chris Lattner749c6f62008-01-07 07:27:27 +0000351 if (MI->getDesc().isCall())
Dan Gohmanfd3ff032008-07-07 20:08:05 +0000352 VisitCallPoint(MI);
Gordon Henriksen364caf02007-09-29 02:13:43 +0000353}
354
355void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
356 uint64_t StackSize = MFI->getStackSize();
357 uint64_t OffsetAdjustment = MFI->getOffsetAdjustment();
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000358 uint64_t OffsetOfLocalArea = TM->getFrameInfo()->getOffsetOfLocalArea();
Gordon Henriksen364caf02007-09-29 02:13:43 +0000359
360 for (CollectorMetadata::roots_iterator RI = MD->roots_begin(),
361 RE = MD->roots_end(); RI != RE; ++RI)
362 RI->StackOffset = MFI->getObjectOffset(RI->Num) + StackSize
363 - OffsetOfLocalArea + OffsetAdjustment;
364}
365
366bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000367 // Quick exit for functions that do not use GC.
368 if (!MF.getFunction()->hasCollector()) return false;
369
370 MD = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
371 if (!MD->getCollector().needsSafePoints())
Gordon Henriksen364caf02007-09-29 02:13:43 +0000372 return false;
373
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000374 TM = &MF.getTarget();
Gordon Henriksen364caf02007-09-29 02:13:43 +0000375 MMI = &getAnalysis<MachineModuleInfo>();
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000376 TII = TM->getInstrInfo();
Gordon Henriksen364caf02007-09-29 02:13:43 +0000377 MFI = MF.getFrameInfo();
378
379 // Find the size of the stack frame.
380 MD->setFrameSize(MFI->getStackSize());
381
382 // Find all safe points.
383 FindSafePoints(MF);
384
385 // Find the stack offsets for all roots.
386 FindStackOffsets(MF);
387
388 return false;
389}