blob: 67b392889e18681da5347fc79144949fab68a49c [file] [log] [blame]
Gordon Henriksenc5ff2262007-09-29 02:13:43 +00001//===-- Collector.cpp - Garbage collection infrastructure -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Gordon Henriksen and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements target- and collector-independent garbage collection
11// infrastructure.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CodeGen/Collector.h"
Gordon Henriksenc22962f2007-12-11 00:30:17 +000016#include "llvm/CodeGen/Passes.h"
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000017#include "llvm/IntrinsicInst.h"
18#include "llvm/Module.h"
19#include "llvm/PassManager.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/CodeGen/MachineFrameInfo.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/Target/TargetFrameInfo.h"
25#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Support/Compiler.h"
28
29using namespace llvm;
30
31namespace {
32
Gordon Henriksenc22962f2007-12-11 00:30:17 +000033 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
34 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
35 /// directed by the Collector. It also performs automatic root initialization
36 /// and custom intrinsic lowering.
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000037 class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000038 /// GCRootInt, GCReadInt, GCWriteInt - The function prototypes for the
39 /// llvm.gc* intrinsics.
40 Function *GCRootInt, *GCReadInt, *GCWriteInt;
41
Gordon Henriksenc22962f2007-12-11 00:30:17 +000042 static bool NeedsDefaultLoweringPass(const Collector &C);
43 static bool NeedsCustomLoweringPass(const Collector &C);
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000044 static bool CouldBecomeSafePoint(Instruction *I);
Gordon Henriksenc22962f2007-12-11 00:30:17 +000045 bool PerformDefaultLowering(Function &F, Collector &Coll);
46 static bool InsertRootInitializers(Function &F,
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000047 AllocaInst **Roots, unsigned Count);
48
49 public:
50 static char ID;
51
Gordon Henriksenc22962f2007-12-11 00:30:17 +000052 LowerIntrinsics();
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000053 const char *getPassName() const;
Gordon Henriksenc22962f2007-12-11 00:30:17 +000054 void getAnalysisUsage(AnalysisUsage &AU) const;
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000055
56 bool doInitialization(Module &M);
57 bool runOnFunction(Function &F);
58 };
59
60
Gordon Henriksenc22962f2007-12-11 00:30:17 +000061 /// MachineCodeAnalysis - This is a target-independent pass over the machine
62 /// function representation to identify safe points for the garbage collector
63 /// in the machine code. It inserts labels at safe points and populates a
64 /// CollectorMetadata record for each function.
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000065 class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
Gordon Henriksenc22962f2007-12-11 00:30:17 +000066 const TargetMachine *TM;
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000067 CollectorMetadata *MD;
68 MachineModuleInfo *MMI;
69 const TargetInstrInfo *TII;
70 MachineFrameInfo *MFI;
71
72 void FindSafePoints(MachineFunction &MF);
73 void VisitCallPoint(MachineBasicBlock::iterator MI);
74 unsigned InsertLabel(MachineBasicBlock &MBB,
75 MachineBasicBlock::iterator MI) const;
76
77 void FindStackOffsets(MachineFunction &MF);
78
79 public:
80 static char ID;
81
Gordon Henriksenc22962f2007-12-11 00:30:17 +000082 MachineCodeAnalysis();
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000083 const char *getPassName() const;
84 void getAnalysisUsage(AnalysisUsage &AU) const;
85
86 bool runOnMachineFunction(MachineFunction &MF);
87 };
88
89}
90
91// -----------------------------------------------------------------------------
92
Gordon Henriksenc5ff2262007-09-29 02:13:43 +000093Collector::Collector() :
94 NeededSafePoints(0),
95 CustomReadBarriers(false),
96 CustomWriteBarriers(false),
97 CustomRoots(false),
98 InitRoots(true)
99{}
100
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000101Collector::~Collector() {
102 for (iterator I = begin(), E = end(); I != E; ++I)
103 delete *I;
104
105 Functions.clear();
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000106}
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000107
108bool Collector::initializeCustomLowering(Module &M) { return false; }
109
110bool Collector::performCustomLowering(Function &F) {
111 cerr << "gc " << getName() << " must override performCustomLowering.\n";
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000112 abort();
113 return 0;
114}
115
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000116void Collector::beginAssembly(std::ostream &OS, AsmPrinter &AP,
117 const TargetAsmInfo &TAI) {
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000118 // Default is no action.
119}
120
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000121void Collector::finishAssembly(std::ostream &OS, AsmPrinter &AP,
122 const TargetAsmInfo &TAI) {
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000123 // Default is no action.
124}
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000125
126CollectorMetadata *Collector::insertFunctionMetadata(const Function &F) {
127 CollectorMetadata *CM = new CollectorMetadata(F, *this);
128 Functions.push_back(CM);
129 return CM;
130}
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000131
132// -----------------------------------------------------------------------------
133
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000134FunctionPass *llvm::createGCLoweringPass() {
135 return new LowerIntrinsics();
136}
137
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000138char LowerIntrinsics::ID = 0;
139
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000140LowerIntrinsics::LowerIntrinsics()
141 : FunctionPass((intptr_t)&ID),
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000142 GCRootInt(0), GCReadInt(0), GCWriteInt(0) {}
143
144const char *LowerIntrinsics::getPassName() const {
145 return "Lower Garbage Collection Instructions";
146}
147
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000148void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
149 FunctionPass::getAnalysisUsage(AU);
150 AU.addRequired<CollectorModuleMetadata>();
151}
152
153/// doInitialization - If this module uses the GC intrinsics, find them now.
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000154bool LowerIntrinsics::doInitialization(Module &M) {
155 GCReadInt = M.getFunction("llvm.gcread");
156 GCWriteInt = M.getFunction("llvm.gcwrite");
157 GCRootInt = M.getFunction("llvm.gcroot");
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000158
159 // FIXME: This is rather antisocial in the context of a JIT since it performs
160 // work against the entire module. But this cannot be done at
161 // runFunction time (initializeCustomLowering likely needs to change
162 // the module).
163 CollectorModuleMetadata *CMM = getAnalysisToUpdate<CollectorModuleMetadata>();
164 assert(CMM && "LowerIntrinsics didn't require CollectorModuleMetadata!?");
165 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
166 if (I->hasCollector())
167 CMM->get(*I); // Instantiate the Collector.
168
169 bool MadeChange = false;
170 for (CollectorModuleMetadata::iterator I = CMM->begin(),
171 E = CMM->end(); I != E; ++I)
172 if (NeedsCustomLoweringPass(**I))
173 if ((*I)->initializeCustomLowering(M))
174 MadeChange = true;
175
176 return MadeChange;
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000177}
178
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000179bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000180 unsigned Count) {
181 // Scroll past alloca instructions.
182 BasicBlock::iterator IP = F.getEntryBlock().begin();
183 while (isa<AllocaInst>(IP)) ++IP;
184
185 // Search for initializers in the initial BB.
186 SmallPtrSet<AllocaInst*,16> InitedRoots;
187 for (; !CouldBecomeSafePoint(IP); ++IP)
188 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
189 if (AllocaInst *AI = dyn_cast<AllocaInst>(
190 IntrinsicInst::StripPointerCasts(SI->getOperand(1))))
191 InitedRoots.insert(AI);
192
193 // Add root initializers.
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000194 bool MadeChange = false;
195
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000196 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000197 if (!InitedRoots.count(*I)) {
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000198 new StoreInst(ConstantPointerNull::get(cast<PointerType>(
199 cast<PointerType>((*I)->getType())->getElementType())),
200 *I, IP);
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000201 MadeChange = true;
202 }
203
204 return MadeChange;
205}
206
207bool LowerIntrinsics::NeedsDefaultLoweringPass(const Collector &C) {
208 // Default lowering is necessary only if read or write barriers have a default
209 // action. The default for roots is no action.
210 return !C.customWriteBarrier()
211 || !C.customReadBarrier()
212 || C.initializeRoots();
213}
214
215bool LowerIntrinsics::NeedsCustomLoweringPass(const Collector &C) {
216 // Custom lowering is only necessary if enabled for some action.
217 return C.customWriteBarrier()
218 || C.customReadBarrier()
219 || C.customRoots();
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000220}
221
222/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
223/// instruction could introduce a safe point.
224bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
225 // The natural definition of instructions which could introduce safe points
226 // are:
227 //
228 // - call, invoke (AfterCall, BeforeCall)
229 // - phis (Loops)
230 // - invoke, ret, unwind (Exit)
231 //
232 // However, instructions as seemingly inoccuous as arithmetic can become
233 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
234 // it is necessary to take a conservative approach.
235
236 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
237 isa<StoreInst>(I) || isa<LoadInst>(I))
238 return false;
239
240 // llvm.gcroot is safe because it doesn't do anything at runtime.
241 if (CallInst *CI = dyn_cast<CallInst>(I))
242 if (Function *F = CI->getCalledFunction())
243 if (unsigned IID = F->getIntrinsicID())
244 if (IID == Intrinsic::gcroot)
245 return false;
246
247 return true;
248}
249
250/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
251/// Leave gcroot intrinsics; the code generator needs to see those.
252bool LowerIntrinsics::runOnFunction(Function &F) {
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000253 // Quick exit for functions that do not use GC.
254 if (!F.hasCollector()) return false;
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000255
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000256 CollectorMetadata &MD = getAnalysis<CollectorModuleMetadata>().get(F);
257 Collector &Coll = MD.getCollector();
258
259 bool MadeChange = false;
260
261 if (NeedsDefaultLoweringPass(Coll))
262 MadeChange |= PerformDefaultLowering(F, Coll);
263
264 if (NeedsCustomLoweringPass(Coll))
265 MadeChange |= Coll.performCustomLowering(F);
266
267 return MadeChange;
268}
269
270bool LowerIntrinsics::PerformDefaultLowering(Function &F, Collector &Coll) {
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000271 bool LowerWr = !Coll.customWriteBarrier();
272 bool LowerRd = !Coll.customReadBarrier();
273 bool InitRoots = Coll.initializeRoots();
274
275 SmallVector<AllocaInst*,32> Roots;
276
277 bool MadeChange = false;
278 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
279 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
280 if (CallInst *CI = dyn_cast<CallInst>(II++)) {
281 Function *F = CI->getCalledFunction();
282 if (F == GCWriteInt && LowerWr) {
283 // Replace a write barrier with a simple store.
284 Value *St = new StoreInst(CI->getOperand(1), CI->getOperand(3), CI);
285 CI->replaceAllUsesWith(St);
286 CI->eraseFromParent();
287 } else if (F == GCReadInt && LowerRd) {
288 // Replace a read barrier with a simple load.
289 Value *Ld = new LoadInst(CI->getOperand(2), "", CI);
290 Ld->takeName(CI);
291 CI->replaceAllUsesWith(Ld);
292 CI->eraseFromParent();
293 } else if (F == GCRootInt && InitRoots) {
294 // Initialize the GC root, but do not delete the intrinsic. The
295 // backend needs the intrinsic to flag the stack slot.
296 Roots.push_back(cast<AllocaInst>(
297 IntrinsicInst::StripPointerCasts(CI->getOperand(1))));
298 } else {
299 continue;
300 }
301
302 MadeChange = true;
303 }
304 }
305 }
306
307 if (Roots.size())
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000308 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000309
310 return MadeChange;
311}
312
313// -----------------------------------------------------------------------------
314
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000315FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
316 return new MachineCodeAnalysis();
317}
318
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000319char MachineCodeAnalysis::ID = 0;
320
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000321MachineCodeAnalysis::MachineCodeAnalysis()
322 : MachineFunctionPass(intptr_t(&ID)) {}
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000323
324const char *MachineCodeAnalysis::getPassName() const {
325 return "Analyze Machine Code For Garbage Collection";
326}
327
328void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
329 MachineFunctionPass::getAnalysisUsage(AU);
330 AU.setPreservesAll();
331 AU.addRequired<MachineModuleInfo>();
332 AU.addRequired<CollectorModuleMetadata>();
333}
334
335unsigned MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
336 MachineBasicBlock::iterator MI) const {
337 unsigned Label = MMI->NextLabelID();
338 BuildMI(MBB, MI, TII->get(TargetInstrInfo::LABEL)).addImm(Label);
339 return Label;
340}
341
342void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
343 // Find the return address (next instruction), too, so as to bracket the call
344 // instruction.
345 MachineBasicBlock::iterator RAI = CI;
346 ++RAI;
347
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000348 if (MD->getCollector().needsSafePoint(GC::PreCall))
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000349 MD->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
350
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000351 if (MD->getCollector().needsSafePoint(GC::PostCall))
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000352 MD->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
353}
354
355void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
356 for (MachineFunction::iterator BBI = MF.begin(),
357 BBE = MF.end(); BBI != BBE; ++BBI)
358 for (MachineBasicBlock::iterator MI = BBI->begin(),
359 ME = BBI->end(); MI != ME; ++MI)
360 if (TII->isCall(MI->getOpcode()))
361 VisitCallPoint(*MI);
362}
363
364void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
365 uint64_t StackSize = MFI->getStackSize();
366 uint64_t OffsetAdjustment = MFI->getOffsetAdjustment();
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000367 uint64_t OffsetOfLocalArea = TM->getFrameInfo()->getOffsetOfLocalArea();
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000368
369 for (CollectorMetadata::roots_iterator RI = MD->roots_begin(),
370 RE = MD->roots_end(); RI != RE; ++RI)
371 RI->StackOffset = MFI->getObjectOffset(RI->Num) + StackSize
372 - OffsetOfLocalArea + OffsetAdjustment;
373}
374
375bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000376 // Quick exit for functions that do not use GC.
377 if (!MF.getFunction()->hasCollector()) return false;
378
379 MD = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
380 if (!MD->getCollector().needsSafePoints())
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000381 return false;
382
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000383 TM = &MF.getTarget();
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000384 MMI = &getAnalysis<MachineModuleInfo>();
Gordon Henriksenc22962f2007-12-11 00:30:17 +0000385 TII = TM->getInstrInfo();
Gordon Henriksenc5ff2262007-09-29 02:13:43 +0000386 MFI = MF.getFrameInfo();
387
388 // Find the size of the stack frame.
389 MD->setFrameSize(MFI->getStackSize());
390
391 // Find all safe points.
392 FindSafePoints(MF);
393
394 // Find the stack offsets for all roots.
395 FindStackOffsets(MF);
396
397 return false;
398}