1 //===-- Collector.cpp - Garbage collection infrastructure -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements target- and collector-independent garbage collection
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/GCStrategy.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/Target/TargetFrameInfo.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/Compiler.h"
32 /// 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.
36 class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
37 static bool NeedsDefaultLoweringPass(const Collector &C);
38 static bool NeedsCustomLoweringPass(const Collector &C);
39 static bool CouldBecomeSafePoint(Instruction *I);
40 bool PerformDefaultLowering(Function &F, Collector &Coll);
41 static bool InsertRootInitializers(Function &F,
42 AllocaInst **Roots, unsigned Count);
48 const char *getPassName() const;
49 void getAnalysisUsage(AnalysisUsage &AU) const;
51 bool doInitialization(Module &M);
52 bool runOnFunction(Function &F);
56 /// 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.
60 class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
61 const TargetMachine *TM;
62 CollectorMetadata *MD;
63 MachineModuleInfo *MMI;
64 const TargetInstrInfo *TII;
65 MachineFrameInfo *MFI;
67 void FindSafePoints(MachineFunction &MF);
68 void VisitCallPoint(MachineBasicBlock::iterator MI);
69 unsigned InsertLabel(MachineBasicBlock &MBB,
70 MachineBasicBlock::iterator MI) const;
72 void FindStackOffsets(MachineFunction &MF);
77 MachineCodeAnalysis();
78 const char *getPassName() const;
79 void getAnalysisUsage(AnalysisUsage &AU) const;
81 bool runOnMachineFunction(MachineFunction &MF);
86 // -----------------------------------------------------------------------------
88 Collector::Collector() :
90 CustomReadBarriers(false),
91 CustomWriteBarriers(false),
97 Collector::~Collector() {
98 for (iterator I = begin(), E = end(); I != E; ++I)
104 bool Collector::initializeCustomLowering(Module &M) { return false; }
106 bool Collector::performCustomLowering(Function &F) {
107 cerr << "gc " << getName() << " must override performCustomLowering.\n";
112 CollectorMetadata *Collector::insertFunctionMetadata(const Function &F) {
113 CollectorMetadata *CM = new CollectorMetadata(F, *this);
114 Functions.push_back(CM);
118 // -----------------------------------------------------------------------------
120 FunctionPass *llvm::createGCLoweringPass() {
121 return new LowerIntrinsics();
124 char LowerIntrinsics::ID = 0;
126 LowerIntrinsics::LowerIntrinsics()
127 : FunctionPass((intptr_t)&ID) {}
129 const char *LowerIntrinsics::getPassName() const {
130 return "Lower Garbage Collection Instructions";
133 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
134 FunctionPass::getAnalysisUsage(AU);
135 AU.addRequired<CollectorModuleMetadata>();
138 /// doInitialization - If this module uses the GC intrinsics, find them now.
139 bool LowerIntrinsics::doInitialization(Module &M) {
140 // 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
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->isDeclaration() && I->hasCollector())
148 CMM->get(*I); // Instantiate the Collector.
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))
160 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
162 // Scroll past alloca instructions.
163 BasicBlock::iterator IP = F.getEntryBlock().begin();
164 while (isa<AllocaInst>(IP)) ++IP;
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))
171 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
172 InitedRoots.insert(AI);
174 // Add root initializers.
175 bool MadeChange = false;
177 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
178 if (!InitedRoots.count(*I)) {
179 new StoreInst(ConstantPointerNull::get(cast<PointerType>(
180 cast<PointerType>((*I)->getType())->getElementType())),
188 bool 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();
196 bool LowerIntrinsics::NeedsCustomLoweringPass(const Collector &C) {
197 // Custom lowering is only necessary if enabled for some action.
198 return C.customWriteBarrier()
199 || C.customReadBarrier()
203 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
204 /// instruction could introduce a safe point.
205 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
206 // The natural definition of instructions which could introduce safe points
209 // - call, invoke (AfterCall, BeforeCall)
211 // - invoke, ret, unwind (Exit)
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.
217 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
218 isa<StoreInst>(I) || isa<LoadInst>(I))
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)
231 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
232 /// Leave gcroot intrinsics; the code generator needs to see those.
233 bool LowerIntrinsics::runOnFunction(Function &F) {
234 // Quick exit for functions that do not use GC.
235 if (!F.hasCollector()) return false;
237 CollectorMetadata &MD = getAnalysis<CollectorModuleMetadata>().get(F);
238 Collector &Coll = MD.getCollector();
240 bool MadeChange = false;
242 if (NeedsDefaultLoweringPass(Coll))
243 MadeChange |= PerformDefaultLowering(F, Coll);
245 if (NeedsCustomLoweringPass(Coll))
246 MadeChange |= Coll.performCustomLowering(F);
251 bool LowerIntrinsics::PerformDefaultLowering(Function &F, Collector &Coll) {
252 bool LowerWr = !Coll.customWriteBarrier();
253 bool LowerRd = !Coll.customReadBarrier();
254 bool InitRoots = Coll.initializeRoots();
256 SmallVector<AllocaInst*,32> Roots;
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;) {
261 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
262 Function *F = CI->getCalledFunction();
263 switch (F->getIntrinsicID()) {
264 case Intrinsic::gcwrite:
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();
272 case Intrinsic::gcread:
274 // Replace a read barrier with a simple load.
275 Value *Ld = new LoadInst(CI->getOperand(2), "", CI);
277 CI->replaceAllUsesWith(Ld);
278 CI->eraseFromParent();
281 case Intrinsic::gcroot:
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>(
286 CI->getOperand(1)->stripPointerCasts()));
299 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
304 // -----------------------------------------------------------------------------
306 FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
307 return new MachineCodeAnalysis();
310 char MachineCodeAnalysis::ID = 0;
312 MachineCodeAnalysis::MachineCodeAnalysis()
313 : MachineFunctionPass(intptr_t(&ID)) {}
315 const char *MachineCodeAnalysis::getPassName() const {
316 return "Analyze Machine Code For Garbage Collection";
319 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
320 MachineFunctionPass::getAnalysisUsage(AU);
321 AU.setPreservesAll();
322 AU.addRequired<MachineModuleInfo>();
323 AU.addRequired<CollectorModuleMetadata>();
326 unsigned MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
327 MachineBasicBlock::iterator MI) const {
328 unsigned Label = MMI->NextLabelID();
329 BuildMI(MBB, MI, TII->get(TargetInstrInfo::GC_LABEL)).addImm(Label);
333 void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
334 // Find the return address (next instruction), too, so as to bracket the call
336 MachineBasicBlock::iterator RAI = CI;
339 if (MD->getCollector().needsSafePoint(GC::PreCall))
340 MD->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
342 if (MD->getCollector().needsSafePoint(GC::PostCall))
343 MD->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
346 void 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)
351 if (MI->getDesc().isCall())
355 void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
356 uint64_t StackSize = MFI->getStackSize();
357 uint64_t OffsetAdjustment = MFI->getOffsetAdjustment();
358 uint64_t OffsetOfLocalArea = TM->getFrameInfo()->getOffsetOfLocalArea();
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;
366 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
367 // Quick exit for functions that do not use GC.
368 if (!MF.getFunction()->hasCollector()) return false;
370 MD = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
371 if (!MD->getCollector().needsSafePoints())
374 TM = &MF.getTarget();
375 MMI = &getAnalysis<MachineModuleInfo>();
376 TII = TM->getInstrInfo();
377 MFI = MF.getFrameInfo();
379 // Find the size of the stack frame.
380 MD->setFrameSize(MFI->getStackSize());
382 // Find all safe points.
385 // Find the stack offsets for all roots.
386 FindStackOffsets(MF);