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 bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
106 bool GCStrategy::performCustomLowering(Function &F) {
107 dbgs() << "gc " << getName() << " must override performCustomLowering.\n";
108 llvm_unreachable("must override performCustomLowering");
112 bool GCStrategy::findCustomSafePoints(GCFunctionInfo& FI, MachineFunction &F) {
113 dbgs() << "gc " << getName() << " must override findCustomSafePoints.\n";
114 llvm_unreachable(nullptr);
118 GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
119 Functions.push_back(make_unique<GCFunctionInfo>(F, *this));
120 return Functions.back().get();
123 // -----------------------------------------------------------------------------
125 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering",
127 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
128 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
130 FunctionPass *llvm::createGCLoweringPass() {
131 return new LowerIntrinsics();
134 char LowerIntrinsics::ID = 0;
136 LowerIntrinsics::LowerIntrinsics()
138 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
141 const char *LowerIntrinsics::getPassName() const {
142 return "Lower Garbage Collection Instructions";
145 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
146 FunctionPass::getAnalysisUsage(AU);
147 AU.addRequired<GCModuleInfo>();
148 AU.addPreserved<DominatorTreeWrapperPass>();
151 /// doInitialization - If this module uses the GC intrinsics, find them now.
152 bool LowerIntrinsics::doInitialization(Module &M) {
153 // FIXME: This is rather antisocial in the context of a JIT since it performs
154 // work against the entire module. But this cannot be done at
155 // runFunction time (initializeCustomLowering likely needs to change
157 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
158 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
159 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
160 if (!I->isDeclaration() && I->hasGC())
161 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
163 bool MadeChange = false;
164 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
165 if (NeedsCustomLoweringPass(**I))
166 if ((*I)->initializeCustomLowering(M))
172 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
174 // Scroll past alloca instructions.
175 BasicBlock::iterator IP = F.getEntryBlock().begin();
176 while (isa<AllocaInst>(IP)) ++IP;
178 // Search for initializers in the initial BB.
179 SmallPtrSet<AllocaInst*,16> InitedRoots;
180 for (; !CouldBecomeSafePoint(IP); ++IP)
181 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
183 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
184 InitedRoots.insert(AI);
186 // Add root initializers.
187 bool MadeChange = false;
189 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
190 if (!InitedRoots.count(*I)) {
191 StoreInst* SI = new StoreInst(ConstantPointerNull::get(cast<PointerType>(
192 cast<PointerType>((*I)->getType())->getElementType())),
201 bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
202 // Default lowering is necessary only if read or write barriers have a default
203 // action. The default for roots is no action.
204 return !C.customWriteBarrier()
205 || !C.customReadBarrier()
206 || C.initializeRoots();
209 bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
210 // Custom lowering is only necessary if enabled for some action.
211 return C.customWriteBarrier()
212 || C.customReadBarrier()
216 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
217 /// instruction could introduce a safe point.
218 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
219 // The natural definition of instructions which could introduce safe points
222 // - call, invoke (AfterCall, BeforeCall)
224 // - invoke, ret, unwind (Exit)
226 // However, instructions as seemingly inoccuous as arithmetic can become
227 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
228 // it is necessary to take a conservative approach.
230 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
231 isa<StoreInst>(I) || isa<LoadInst>(I))
234 // llvm.gcroot is safe because it doesn't do anything at runtime.
235 if (CallInst *CI = dyn_cast<CallInst>(I))
236 if (Function *F = CI->getCalledFunction())
237 if (unsigned IID = F->getIntrinsicID())
238 if (IID == Intrinsic::gcroot)
244 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
245 /// Leave gcroot intrinsics; the code generator needs to see those.
246 bool LowerIntrinsics::runOnFunction(Function &F) {
247 // Quick exit for functions that do not use GC.
251 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
252 GCStrategy &S = FI.getStrategy();
254 bool MadeChange = false;
256 if (NeedsDefaultLoweringPass(S))
257 MadeChange |= PerformDefaultLowering(F, S);
259 bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
260 if (UseCustomLoweringPass)
261 MadeChange |= S.performCustomLowering(F);
263 // Custom lowering may modify the CFG, so dominators must be recomputed.
264 if (UseCustomLoweringPass) {
265 if (DominatorTreeWrapperPass *DTWP =
266 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
267 DTWP->getDomTree().recalculate(F);
273 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
274 bool LowerWr = !S.customWriteBarrier();
275 bool LowerRd = !S.customReadBarrier();
276 bool InitRoots = S.initializeRoots();
278 SmallVector<AllocaInst*, 32> Roots;
280 bool MadeChange = false;
281 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
282 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
283 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
284 Function *F = CI->getCalledFunction();
285 switch (F->getIntrinsicID()) {
286 case Intrinsic::gcwrite:
288 // Replace a write barrier with a simple store.
289 Value *St = new StoreInst(CI->getArgOperand(0),
290 CI->getArgOperand(2), CI);
291 CI->replaceAllUsesWith(St);
292 CI->eraseFromParent();
295 case Intrinsic::gcread:
297 // Replace a read barrier with a simple load.
298 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
300 CI->replaceAllUsesWith(Ld);
301 CI->eraseFromParent();
304 case Intrinsic::gcroot:
306 // Initialize the GC root, but do not delete the intrinsic. The
307 // backend needs the intrinsic to flag the stack slot.
308 Roots.push_back(cast<AllocaInst>(
309 CI->getArgOperand(0)->stripPointerCasts()));
322 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
327 // -----------------------------------------------------------------------------
329 char GCMachineCodeAnalysis::ID = 0;
330 char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
332 INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
333 "Analyze Machine Code For Garbage Collection", false, false)
335 GCMachineCodeAnalysis::GCMachineCodeAnalysis()
336 : MachineFunctionPass(ID) {}
338 void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
339 MachineFunctionPass::getAnalysisUsage(AU);
340 AU.setPreservesAll();
341 AU.addRequired<MachineModuleInfo>();
342 AU.addRequired<GCModuleInfo>();
345 MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
346 MachineBasicBlock::iterator MI,
348 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
349 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
353 void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
354 // Find the return address (next instruction), too, so as to bracket the call
356 MachineBasicBlock::iterator RAI = CI;
359 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
360 MCSymbol* Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
361 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
364 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
365 MCSymbol* Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
366 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
370 void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
371 for (MachineFunction::iterator BBI = MF.begin(),
372 BBE = MF.end(); BBI != BBE; ++BBI)
373 for (MachineBasicBlock::iterator MI = BBI->begin(),
374 ME = BBI->end(); MI != ME; ++MI)
379 void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
380 const TargetFrameLowering *TFI = TM->getFrameLowering();
381 assert(TFI && "TargetRegisterInfo not available!");
383 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
384 RI != FI->roots_end();) {
385 // If the root references a dead object, no need to keep it.
386 if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
387 RI = FI->removeStackRoot(RI);
389 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
395 bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
396 // Quick exit for functions that do not use GC.
397 if (!MF.getFunction()->hasGC())
400 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
401 if (!FI->getStrategy().needsSafePoints())
404 TM = &MF.getTarget();
405 MMI = &getAnalysis<MachineModuleInfo>();
406 TII = TM->getInstrInfo();
408 // Find the size of the stack frame.
409 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
411 // Find all safe points.
412 if (FI->getStrategy().customSafePoints()) {
413 FI->getStrategy().findCustomSafePoints(*FI, MF);
418 // Find the stack offsets for all roots.
419 FindStackOffsets(MF);