CollectorMetadata and Collector are rejiggered to get along with
[oota-llvm.git] / lib / CodeGen / Collector.cpp
1 //===-- 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"
16 #include "llvm/CodeGen/Passes.h"
17 #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
29 using namespace llvm;
30
31 namespace {
32   
33   /// 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.
37   class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
38     /// GCRootInt, GCReadInt, GCWriteInt - The function prototypes for the
39     /// llvm.gc* intrinsics.
40     Function *GCRootInt, *GCReadInt, *GCWriteInt;
41     
42     static bool NeedsDefaultLoweringPass(const Collector &C);
43     static bool NeedsCustomLoweringPass(const Collector &C);
44     static bool CouldBecomeSafePoint(Instruction *I);
45     bool PerformDefaultLowering(Function &F, Collector &Coll);
46     static bool InsertRootInitializers(Function &F,
47                                        AllocaInst **Roots, unsigned Count);
48     
49   public:
50     static char ID;
51     
52     LowerIntrinsics();
53     const char *getPassName() const;
54     void getAnalysisUsage(AnalysisUsage &AU) const;
55     
56     bool doInitialization(Module &M);
57     bool runOnFunction(Function &F);
58   };
59   
60   
61   /// 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.
65   class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
66     const TargetMachine *TM;
67     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     
82     MachineCodeAnalysis();
83     const char *getPassName() const;
84     void getAnalysisUsage(AnalysisUsage &AU) const;
85     
86     bool runOnMachineFunction(MachineFunction &MF);
87   };
88   
89 }
90
91 // -----------------------------------------------------------------------------
92
93 Collector::Collector() :
94   NeededSafePoints(0),
95   CustomReadBarriers(false),
96   CustomWriteBarriers(false),
97   CustomRoots(false),
98   InitRoots(true)
99 {}
100
101 Collector::~Collector() {
102   for (iterator I = begin(), E = end(); I != E; ++I)
103     delete *I;
104   
105   Functions.clear();
106 }
107  
108 bool Collector::initializeCustomLowering(Module &M) { return false; }
109  
110 bool Collector::performCustomLowering(Function &F) {
111   cerr << "gc " << getName() << " must override performCustomLowering.\n";
112   abort();
113   return 0;
114 }
115     
116 void Collector::beginAssembly(std::ostream &OS, AsmPrinter &AP,
117                               const TargetAsmInfo &TAI) {
118   // Default is no action.
119 }
120     
121 void Collector::finishAssembly(std::ostream &OS, AsmPrinter &AP,
122                                const TargetAsmInfo &TAI) {
123   // Default is no action.
124 }
125  
126 CollectorMetadata *Collector::insertFunctionMetadata(const Function &F) {
127   CollectorMetadata *CM = new CollectorMetadata(F, *this);
128   Functions.push_back(CM);
129   return CM;
130
131
132 // -----------------------------------------------------------------------------
133
134 FunctionPass *llvm::createGCLoweringPass() {
135   return new LowerIntrinsics();
136 }
137  
138 char LowerIntrinsics::ID = 0;
139
140 LowerIntrinsics::LowerIntrinsics()
141   : FunctionPass((intptr_t)&ID),
142     GCRootInt(0), GCReadInt(0), GCWriteInt(0) {}
143
144 const char *LowerIntrinsics::getPassName() const {
145   return "Lower Garbage Collection Instructions";
146 }
147     
148 void 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.
154 bool LowerIntrinsics::doInitialization(Module &M) {
155   GCReadInt  = M.getFunction("llvm.gcread");
156   GCWriteInt = M.getFunction("llvm.gcwrite");
157   GCRootInt  = M.getFunction("llvm.gcroot");
158   
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;
177 }
178
179 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots, 
180                                                           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.
194   bool MadeChange = false;
195   
196   for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
197     if (!InitedRoots.count(*I)) {
198       new StoreInst(ConstantPointerNull::get(cast<PointerType>(
199                       cast<PointerType>((*I)->getType())->getElementType())),
200                     *I, IP);
201       MadeChange = true;
202     }
203   
204   return MadeChange;
205 }
206
207 bool 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
215 bool 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();
220 }
221
222 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
223 /// instruction could introduce a safe point.
224 bool 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.
252 bool LowerIntrinsics::runOnFunction(Function &F) {
253   // Quick exit for functions that do not use GC.
254   if (!F.hasCollector()) return false;
255   
256   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
270 bool LowerIntrinsics::PerformDefaultLowering(Function &F, Collector &Coll) {
271   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())
308     MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
309   
310   return MadeChange;
311 }
312
313 // -----------------------------------------------------------------------------
314
315 FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
316   return new MachineCodeAnalysis();
317 }
318
319 char MachineCodeAnalysis::ID = 0;
320
321 MachineCodeAnalysis::MachineCodeAnalysis()
322   : MachineFunctionPass(intptr_t(&ID)) {}
323
324 const char *MachineCodeAnalysis::getPassName() const {
325   return "Analyze Machine Code For Garbage Collection";
326 }
327
328 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
329   MachineFunctionPass::getAnalysisUsage(AU);
330   AU.setPreservesAll();
331   AU.addRequired<MachineModuleInfo>();
332   AU.addRequired<CollectorModuleMetadata>();
333 }
334
335 unsigned 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
342 void 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   
348   if (MD->getCollector().needsSafePoint(GC::PreCall))
349     MD->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
350   
351   if (MD->getCollector().needsSafePoint(GC::PostCall))
352     MD->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
353 }
354
355 void 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
364 void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
365   uint64_t StackSize = MFI->getStackSize();
366   uint64_t OffsetAdjustment = MFI->getOffsetAdjustment();
367   uint64_t OffsetOfLocalArea = TM->getFrameInfo()->getOffsetOfLocalArea();
368   
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
375 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
376   // 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())
381     return false;
382   
383   TM = &MF.getTarget();
384   MMI = &getAnalysis<MachineModuleInfo>();
385   TII = TM->getInstrInfo();
386   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 }