Don't instantiate GC metadata for declarations.
[oota-llvm.git] / lib / CodeGen / GCStrategy.cpp
1 //===-- Collector.cpp - Garbage collection infrastructure -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/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"
27
28 using namespace llvm;
29
30 namespace {
31   
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);
43     
44   public:
45     static char ID;
46     
47     LowerIntrinsics();
48     const char *getPassName() const;
49     void getAnalysisUsage(AnalysisUsage &AU) const;
50     
51     bool doInitialization(Module &M);
52     bool runOnFunction(Function &F);
53   };
54   
55   
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;
66     
67     void FindSafePoints(MachineFunction &MF);
68     void VisitCallPoint(MachineBasicBlock::iterator MI);
69     unsigned InsertLabel(MachineBasicBlock &MBB, 
70                          MachineBasicBlock::iterator MI) const;
71     
72     void FindStackOffsets(MachineFunction &MF);
73     
74   public:
75     static char ID;
76     
77     MachineCodeAnalysis();
78     const char *getPassName() const;
79     void getAnalysisUsage(AnalysisUsage &AU) const;
80     
81     bool runOnMachineFunction(MachineFunction &MF);
82   };
83   
84 }
85
86 // -----------------------------------------------------------------------------
87
88 Collector::Collector() :
89   NeededSafePoints(0),
90   CustomReadBarriers(false),
91   CustomWriteBarriers(false),
92   CustomRoots(false),
93   InitRoots(true),
94   UsesMetadata(false)
95 {}
96
97 Collector::~Collector() {
98   for (iterator I = begin(), E = end(); I != E; ++I)
99     delete *I;
100   
101   Functions.clear();
102 }
103  
104 bool Collector::initializeCustomLowering(Module &M) { return false; }
105  
106 bool Collector::performCustomLowering(Function &F) {
107   cerr << "gc " << getName() << " must override performCustomLowering.\n";
108   abort();
109   return 0;
110 }
111     
112 CollectorMetadata *Collector::insertFunctionMetadata(const Function &F) {
113   CollectorMetadata *CM = new CollectorMetadata(F, *this);
114   Functions.push_back(CM);
115   return CM;
116
117
118 // -----------------------------------------------------------------------------
119
120 FunctionPass *llvm::createGCLoweringPass() {
121   return new LowerIntrinsics();
122 }
123  
124 char LowerIntrinsics::ID = 0;
125
126 LowerIntrinsics::LowerIntrinsics()
127   : FunctionPass((intptr_t)&ID) {}
128
129 const char *LowerIntrinsics::getPassName() const {
130   return "Lower Garbage Collection Instructions";
131 }
132     
133 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
134   FunctionPass::getAnalysisUsage(AU);
135   AU.addRequired<CollectorModuleMetadata>();
136 }
137
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
143   //        the module).
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.
149   
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))
155         MadeChange = true;
156   
157   return MadeChange;
158 }
159
160 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots, 
161                                                           unsigned Count) {
162   // Scroll past alloca instructions.
163   BasicBlock::iterator IP = F.getEntryBlock().begin();
164   while (isa<AllocaInst>(IP)) ++IP;
165   
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))
170       if (AllocaInst *AI =
171           dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
172         InitedRoots.insert(AI);
173   
174   // Add root initializers.
175   bool MadeChange = false;
176   
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())),
181                     *I, IP);
182       MadeChange = true;
183     }
184   
185   return MadeChange;
186 }
187
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();
194 }
195
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()
200       || C.customRoots();
201 }
202
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
207   // are:
208   // 
209   //   - call, invoke (AfterCall, BeforeCall)
210   //   - phis (Loops)
211   //   - invoke, ret, unwind (Exit)
212   // 
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.
216   
217   if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
218       isa<StoreInst>(I) || isa<LoadInst>(I))
219     return false;
220   
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)
226           return false;
227   
228   return true;
229 }
230
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;
236   
237   CollectorMetadata &MD = getAnalysis<CollectorModuleMetadata>().get(F);
238   Collector &Coll = MD.getCollector();
239   
240   bool MadeChange = false;
241   
242   if (NeedsDefaultLoweringPass(Coll))
243     MadeChange |= PerformDefaultLowering(F, Coll);
244   
245   if (NeedsCustomLoweringPass(Coll))
246     MadeChange |= Coll.performCustomLowering(F);
247   
248   return MadeChange;
249 }
250
251 bool LowerIntrinsics::PerformDefaultLowering(Function &F, Collector &Coll) {
252   bool LowerWr = !Coll.customWriteBarrier();
253   bool LowerRd = !Coll.customReadBarrier();
254   bool InitRoots = Coll.initializeRoots();
255   
256   SmallVector<AllocaInst*,32> Roots;
257   
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:
265           if (LowerWr) {
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();
270           }
271           break;
272         case Intrinsic::gcread:
273           if (LowerRd) {
274             // Replace a read barrier with a simple load.
275             Value *Ld = new LoadInst(CI->getOperand(2), "", CI);
276             Ld->takeName(CI);
277             CI->replaceAllUsesWith(Ld);
278             CI->eraseFromParent();
279           }
280           break;
281         case Intrinsic::gcroot:
282           if (InitRoots) {
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()));
287           }
288           break;
289         default:
290           continue;
291         }
292         
293         MadeChange = true;
294       }
295     }
296   }
297   
298   if (Roots.size())
299     MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
300   
301   return MadeChange;
302 }
303
304 // -----------------------------------------------------------------------------
305
306 FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
307   return new MachineCodeAnalysis();
308 }
309
310 char MachineCodeAnalysis::ID = 0;
311
312 MachineCodeAnalysis::MachineCodeAnalysis()
313   : MachineFunctionPass(intptr_t(&ID)) {}
314
315 const char *MachineCodeAnalysis::getPassName() const {
316   return "Analyze Machine Code For Garbage Collection";
317 }
318
319 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
320   MachineFunctionPass::getAnalysisUsage(AU);
321   AU.setPreservesAll();
322   AU.addRequired<MachineModuleInfo>();
323   AU.addRequired<CollectorModuleMetadata>();
324 }
325
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);
330   return Label;
331 }
332
333 void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
334   // Find the return address (next instruction), too, so as to bracket the call
335   // instruction.
336   MachineBasicBlock::iterator RAI = CI; 
337   ++RAI;                                
338   
339   if (MD->getCollector().needsSafePoint(GC::PreCall))
340     MD->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
341   
342   if (MD->getCollector().needsSafePoint(GC::PostCall))
343     MD->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
344 }
345
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())
352         VisitCallPoint(MI);
353 }
354
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();
359   
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;
364 }
365
366 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
367   // Quick exit for functions that do not use GC.
368   if (!MF.getFunction()->hasCollector()) return false;
369   
370   MD = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
371   if (!MD->getCollector().needsSafePoints())
372     return false;
373   
374   TM = &MF.getTarget();
375   MMI = &getAnalysis<MachineModuleInfo>();
376   TII = TM->getInstrInfo();
377   MFI = MF.getFrameInfo();
378   
379   // Find the size of the stack frame.
380   MD->setFrameSize(MFI->getStackSize());
381   
382   // Find all safe points.
383   FindSafePoints(MF);
384   
385   // Find the stack offsets for all roots.
386   FindStackOffsets(MF);
387   
388   return false;
389 }