1 //===-- GCStrategy.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 // MachineCodeAnalysis identifies the GC safe points in the machine code. Roots
14 // are identified in SelectionDAGISel.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/CodeGen/GCStrategy.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Module.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/Target/TargetFrameLowering.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
39 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
40 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
41 /// directed by the GCStrategy. It also performs automatic root initialization
42 /// and custom intrinsic lowering.
43 class LowerIntrinsics : public FunctionPass {
44 static bool NeedsDefaultLoweringPass(const GCStrategy &C);
45 static bool NeedsCustomLoweringPass(const GCStrategy &C);
46 static bool CouldBecomeSafePoint(Instruction *I);
47 bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
48 static bool InsertRootInitializers(Function &F,
49 AllocaInst **Roots, unsigned Count);
55 const char *getPassName() const;
56 void getAnalysisUsage(AnalysisUsage &AU) const;
58 bool doInitialization(Module &M);
59 bool runOnFunction(Function &F);
63 /// MachineCodeAnalysis - This is a target-independent pass over the machine
64 /// function representation to identify safe points for the garbage collector
65 /// in the machine code. It inserts labels at safe points and populates a
66 /// GCMetadata record for each function.
67 class MachineCodeAnalysis : public MachineFunctionPass {
68 const TargetMachine *TM;
70 MachineModuleInfo *MMI;
71 const TargetInstrInfo *TII;
73 void FindSafePoints(MachineFunction &MF);
74 void VisitCallPoint(MachineBasicBlock::iterator MI);
75 MCSymbol *InsertLabel(MachineBasicBlock &MBB,
76 MachineBasicBlock::iterator MI,
79 void FindStackOffsets(MachineFunction &MF);
84 MachineCodeAnalysis();
85 const char *getPassName() const;
86 void getAnalysisUsage(AnalysisUsage &AU) const;
88 bool runOnMachineFunction(MachineFunction &MF);
93 // -----------------------------------------------------------------------------
95 GCStrategy::GCStrategy() :
97 CustomReadBarriers(false),
98 CustomWriteBarriers(false),
100 CustomSafePoints(false),
105 GCStrategy::~GCStrategy() {
106 for (iterator I = begin(), E = end(); I != E; ++I)
112 bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
114 bool GCStrategy::performCustomLowering(Function &F) {
115 dbgs() << "gc " << getName() << " must override performCustomLowering.\n";
121 bool GCStrategy::findCustomSafePoints(GCFunctionInfo& FI, MachineFunction &F) {
122 dbgs() << "gc " << getName() << " must override findCustomSafePoints.\n";
128 GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
129 GCFunctionInfo *FI = new GCFunctionInfo(F, *this);
130 Functions.push_back(FI);
134 // -----------------------------------------------------------------------------
136 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering",
138 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
139 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
141 FunctionPass *llvm::createGCLoweringPass() {
142 return new LowerIntrinsics();
145 char LowerIntrinsics::ID = 0;
147 LowerIntrinsics::LowerIntrinsics()
149 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
152 const char *LowerIntrinsics::getPassName() const {
153 return "Lower Garbage Collection Instructions";
156 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
157 FunctionPass::getAnalysisUsage(AU);
158 AU.addRequired<GCModuleInfo>();
159 AU.addPreserved<DominatorTree>();
162 /// doInitialization - If this module uses the GC intrinsics, find them now.
163 bool LowerIntrinsics::doInitialization(Module &M) {
164 // FIXME: This is rather antisocial in the context of a JIT since it performs
165 // work against the entire module. But this cannot be done at
166 // runFunction time (initializeCustomLowering likely needs to change
168 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
169 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
170 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
171 if (!I->isDeclaration() && I->hasGC())
172 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
174 bool MadeChange = false;
175 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
176 if (NeedsCustomLoweringPass(**I))
177 if ((*I)->initializeCustomLowering(M))
183 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
185 // Scroll past alloca instructions.
186 BasicBlock::iterator IP = F.getEntryBlock().begin();
187 while (isa<AllocaInst>(IP)) ++IP;
189 // Search for initializers in the initial BB.
190 SmallPtrSet<AllocaInst*,16> InitedRoots;
191 for (; !CouldBecomeSafePoint(IP); ++IP)
192 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
194 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
195 InitedRoots.insert(AI);
197 // Add root initializers.
198 bool MadeChange = false;
200 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
201 if (!InitedRoots.count(*I)) {
202 StoreInst* SI = new StoreInst(ConstantPointerNull::get(cast<PointerType>(
203 cast<PointerType>((*I)->getType())->getElementType())),
212 bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
213 // Default lowering is necessary only if read or write barriers have a default
214 // action. The default for roots is no action.
215 return !C.customWriteBarrier()
216 || !C.customReadBarrier()
217 || C.initializeRoots();
220 bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
221 // Custom lowering is only necessary if enabled for some action.
222 return C.customWriteBarrier()
223 || C.customReadBarrier()
227 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
228 /// instruction could introduce a safe point.
229 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
230 // The natural definition of instructions which could introduce safe points
233 // - call, invoke (AfterCall, BeforeCall)
235 // - invoke, ret, unwind (Exit)
237 // However, instructions as seemingly inoccuous as arithmetic can become
238 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
239 // it is necessary to take a conservative approach.
241 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
242 isa<StoreInst>(I) || isa<LoadInst>(I))
245 // llvm.gcroot is safe because it doesn't do anything at runtime.
246 if (CallInst *CI = dyn_cast<CallInst>(I))
247 if (Function *F = CI->getCalledFunction())
248 if (unsigned IID = F->getIntrinsicID())
249 if (IID == Intrinsic::gcroot)
255 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
256 /// Leave gcroot intrinsics; the code generator needs to see those.
257 bool LowerIntrinsics::runOnFunction(Function &F) {
258 // Quick exit for functions that do not use GC.
262 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
263 GCStrategy &S = FI.getStrategy();
265 bool MadeChange = false;
267 if (NeedsDefaultLoweringPass(S))
268 MadeChange |= PerformDefaultLowering(F, S);
270 bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
271 if (UseCustomLoweringPass)
272 MadeChange |= S.performCustomLowering(F);
274 // Custom lowering may modify the CFG, so dominators must be recomputed.
275 if (UseCustomLoweringPass) {
276 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
277 DT->DT->recalculate(F);
283 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
284 bool LowerWr = !S.customWriteBarrier();
285 bool LowerRd = !S.customReadBarrier();
286 bool InitRoots = S.initializeRoots();
288 SmallVector<AllocaInst*, 32> Roots;
290 bool MadeChange = false;
291 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
292 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
293 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
294 Function *F = CI->getCalledFunction();
295 switch (F->getIntrinsicID()) {
296 case Intrinsic::gcwrite:
298 // Replace a write barrier with a simple store.
299 Value *St = new StoreInst(CI->getArgOperand(0),
300 CI->getArgOperand(2), CI);
301 CI->replaceAllUsesWith(St);
302 CI->eraseFromParent();
305 case Intrinsic::gcread:
307 // Replace a read barrier with a simple load.
308 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
310 CI->replaceAllUsesWith(Ld);
311 CI->eraseFromParent();
314 case Intrinsic::gcroot:
316 // Initialize the GC root, but do not delete the intrinsic. The
317 // backend needs the intrinsic to flag the stack slot.
318 Roots.push_back(cast<AllocaInst>(
319 CI->getArgOperand(0)->stripPointerCasts()));
332 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
337 // -----------------------------------------------------------------------------
339 FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
340 return new MachineCodeAnalysis();
343 char MachineCodeAnalysis::ID = 0;
345 MachineCodeAnalysis::MachineCodeAnalysis()
346 : MachineFunctionPass(ID) {}
348 const char *MachineCodeAnalysis::getPassName() const {
349 return "Analyze Machine Code For Garbage Collection";
352 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
353 MachineFunctionPass::getAnalysisUsage(AU);
354 AU.setPreservesAll();
355 AU.addRequired<MachineModuleInfo>();
356 AU.addRequired<GCModuleInfo>();
359 MCSymbol *MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
360 MachineBasicBlock::iterator MI,
362 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
363 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
367 void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
368 // Find the return address (next instruction), too, so as to bracket the call
370 MachineBasicBlock::iterator RAI = CI;
373 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
374 MCSymbol* Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
375 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
378 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
379 MCSymbol* Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
380 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
384 void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
385 for (MachineFunction::iterator BBI = MF.begin(),
386 BBE = MF.end(); BBI != BBE; ++BBI)
387 for (MachineBasicBlock::iterator MI = BBI->begin(),
388 ME = BBI->end(); MI != ME; ++MI)
393 void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
394 const TargetFrameLowering *TFI = TM->getFrameLowering();
395 assert(TFI && "TargetRegisterInfo not available!");
397 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
398 RE = FI->roots_end(); RI != RE; ++RI)
399 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
402 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
403 // Quick exit for functions that do not use GC.
404 if (!MF.getFunction()->hasGC())
407 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
408 if (!FI->getStrategy().needsSafePoints())
411 TM = &MF.getTarget();
412 MMI = &getAnalysis<MachineModuleInfo>();
413 TII = TM->getInstrInfo();
415 // Find the size of the stack frame.
416 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
418 // Find all safe points.
419 if (FI->getStrategy().customSafePoints()) {
420 FI->getStrategy().findCustomSafePoints(*FI, MF);
425 // Find the stack offsets for all roots.
426 FindStackOffsets(MF);