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 // GCMachineCodeAnalysis identifies the GC safe points in the machine code.
14 // Roots are identified in SelectionDAGISel.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/CodeGen/GCStrategy.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/CodeGen/Passes.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetFrameLowering.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetRegisterInfo.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 override;
56 void getAnalysisUsage(AnalysisUsage &AU) const override;
58 bool doInitialization(Module &M) override;
59 bool runOnFunction(Function &F) override;
63 /// GCMachineCodeAnalysis - 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 GCMachineCodeAnalysis : 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 GCMachineCodeAnalysis();
85 void getAnalysisUsage(AnalysisUsage &AU) const override;
87 bool runOnMachineFunction(MachineFunction &MF) override;
92 // -----------------------------------------------------------------------------
94 GCStrategy::GCStrategy() :
96 CustomReadBarriers(false),
97 CustomWriteBarriers(false),
99 CustomSafePoints(false),
104 GCStrategy::~GCStrategy() {
105 for (iterator I = begin(), E = end(); I != E; ++I)
111 bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
113 bool GCStrategy::performCustomLowering(Function &F) {
114 dbgs() << "gc " << getName() << " must override performCustomLowering.\n";
115 llvm_unreachable("must override performCustomLowering");
119 bool GCStrategy::findCustomSafePoints(GCFunctionInfo& FI, MachineFunction &F) {
120 dbgs() << "gc " << getName() << " must override findCustomSafePoints.\n";
125 GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
126 GCFunctionInfo *FI = new GCFunctionInfo(F, *this);
127 Functions.push_back(FI);
131 // -----------------------------------------------------------------------------
133 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering",
135 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
136 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
138 FunctionPass *llvm::createGCLoweringPass() {
139 return new LowerIntrinsics();
142 char LowerIntrinsics::ID = 0;
144 LowerIntrinsics::LowerIntrinsics()
146 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
149 const char *LowerIntrinsics::getPassName() const {
150 return "Lower Garbage Collection Instructions";
153 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
154 FunctionPass::getAnalysisUsage(AU);
155 AU.addRequired<GCModuleInfo>();
156 AU.addPreserved<DominatorTreeWrapperPass>();
159 /// doInitialization - If this module uses the GC intrinsics, find them now.
160 bool LowerIntrinsics::doInitialization(Module &M) {
161 // FIXME: This is rather antisocial in the context of a JIT since it performs
162 // work against the entire module. But this cannot be done at
163 // runFunction time (initializeCustomLowering likely needs to change
165 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
166 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
167 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
168 if (!I->isDeclaration() && I->hasGC())
169 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
171 bool MadeChange = false;
172 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
173 if (NeedsCustomLoweringPass(**I))
174 if ((*I)->initializeCustomLowering(M))
180 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
182 // Scroll past alloca instructions.
183 BasicBlock::iterator IP = F.getEntryBlock().begin();
184 while (isa<AllocaInst>(IP)) ++IP;
186 // Search for initializers in the initial BB.
187 SmallPtrSet<AllocaInst*,16> InitedRoots;
188 for (; !CouldBecomeSafePoint(IP); ++IP)
189 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
191 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
192 InitedRoots.insert(AI);
194 // Add root initializers.
195 bool MadeChange = false;
197 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
198 if (!InitedRoots.count(*I)) {
199 StoreInst* SI = new StoreInst(ConstantPointerNull::get(cast<PointerType>(
200 cast<PointerType>((*I)->getType())->getElementType())),
209 bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
210 // Default lowering is necessary only if read or write barriers have a default
211 // action. The default for roots is no action.
212 return !C.customWriteBarrier()
213 || !C.customReadBarrier()
214 || C.initializeRoots();
217 bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
218 // Custom lowering is only necessary if enabled for some action.
219 return C.customWriteBarrier()
220 || C.customReadBarrier()
224 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
225 /// instruction could introduce a safe point.
226 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
227 // The natural definition of instructions which could introduce safe points
230 // - call, invoke (AfterCall, BeforeCall)
232 // - invoke, ret, unwind (Exit)
234 // However, instructions as seemingly inoccuous as arithmetic can become
235 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
236 // it is necessary to take a conservative approach.
238 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
239 isa<StoreInst>(I) || isa<LoadInst>(I))
242 // llvm.gcroot is safe because it doesn't do anything at runtime.
243 if (CallInst *CI = dyn_cast<CallInst>(I))
244 if (Function *F = CI->getCalledFunction())
245 if (unsigned IID = F->getIntrinsicID())
246 if (IID == Intrinsic::gcroot)
252 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
253 /// Leave gcroot intrinsics; the code generator needs to see those.
254 bool LowerIntrinsics::runOnFunction(Function &F) {
255 // Quick exit for functions that do not use GC.
259 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
260 GCStrategy &S = FI.getStrategy();
262 bool MadeChange = false;
264 if (NeedsDefaultLoweringPass(S))
265 MadeChange |= PerformDefaultLowering(F, S);
267 bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
268 if (UseCustomLoweringPass)
269 MadeChange |= S.performCustomLowering(F);
271 // Custom lowering may modify the CFG, so dominators must be recomputed.
272 if (UseCustomLoweringPass) {
273 if (DominatorTreeWrapperPass *DTWP =
274 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
275 DTWP->getDomTree().recalculate(F);
281 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
282 bool LowerWr = !S.customWriteBarrier();
283 bool LowerRd = !S.customReadBarrier();
284 bool InitRoots = S.initializeRoots();
286 SmallVector<AllocaInst*, 32> Roots;
288 bool MadeChange = false;
289 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
290 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
291 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
292 Function *F = CI->getCalledFunction();
293 switch (F->getIntrinsicID()) {
294 case Intrinsic::gcwrite:
296 // Replace a write barrier with a simple store.
297 Value *St = new StoreInst(CI->getArgOperand(0),
298 CI->getArgOperand(2), CI);
299 CI->replaceAllUsesWith(St);
300 CI->eraseFromParent();
303 case Intrinsic::gcread:
305 // Replace a read barrier with a simple load.
306 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
308 CI->replaceAllUsesWith(Ld);
309 CI->eraseFromParent();
312 case Intrinsic::gcroot:
314 // Initialize the GC root, but do not delete the intrinsic. The
315 // backend needs the intrinsic to flag the stack slot.
316 Roots.push_back(cast<AllocaInst>(
317 CI->getArgOperand(0)->stripPointerCasts()));
330 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
335 // -----------------------------------------------------------------------------
337 char GCMachineCodeAnalysis::ID = 0;
338 char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
340 INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
341 "Analyze Machine Code For Garbage Collection", false, false)
343 GCMachineCodeAnalysis::GCMachineCodeAnalysis()
344 : MachineFunctionPass(ID) {}
346 void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
347 MachineFunctionPass::getAnalysisUsage(AU);
348 AU.setPreservesAll();
349 AU.addRequired<MachineModuleInfo>();
350 AU.addRequired<GCModuleInfo>();
353 MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
354 MachineBasicBlock::iterator MI,
356 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
357 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
361 void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
362 // Find the return address (next instruction), too, so as to bracket the call
364 MachineBasicBlock::iterator RAI = CI;
367 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
368 MCSymbol* Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
369 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
372 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
373 MCSymbol* Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
374 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
378 void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
379 for (MachineFunction::iterator BBI = MF.begin(),
380 BBE = MF.end(); BBI != BBE; ++BBI)
381 for (MachineBasicBlock::iterator MI = BBI->begin(),
382 ME = BBI->end(); MI != ME; ++MI)
387 void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
388 const TargetFrameLowering *TFI = TM->getFrameLowering();
389 assert(TFI && "TargetRegisterInfo not available!");
391 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
392 RI != FI->roots_end();) {
393 // If the root references a dead object, no need to keep it.
394 if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
395 RI = FI->removeStackRoot(RI);
397 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
403 bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
404 // Quick exit for functions that do not use GC.
405 if (!MF.getFunction()->hasGC())
408 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
409 if (!FI->getStrategy().needsSafePoints())
412 TM = &MF.getTarget();
413 MMI = &getAnalysis<MachineModuleInfo>();
414 TII = TM->getInstrInfo();
416 // Find the size of the stack frame.
417 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
419 // Find all safe points.
420 if (FI->getStrategy().customSafePoints()) {
421 FI->getStrategy().findCustomSafePoints(*FI, MF);
426 // Find the stack offsets for all roots.
427 FindStackOffsets(MF);