DW_AT_virtuality is also defined to be constant, not flag.
[oota-llvm.git] / lib / CodeGen / GCStrategy.cpp
1 //===-- GCStrategy.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 // MachineCodeAnalysis identifies the GC safe points in the machine code. Roots
14 // are identified in SelectionDAGISel.
15 //
16 //===----------------------------------------------------------------------===//
17
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"
34
35 using namespace llvm;
36
37 namespace {
38   
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);
50     
51   public:
52     static char ID;
53     
54     LowerIntrinsics();
55     const char *getPassName() const;
56     void getAnalysisUsage(AnalysisUsage &AU) const;
57     
58     bool doInitialization(Module &M);
59     bool runOnFunction(Function &F);
60   };
61   
62   
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;
69     GCFunctionInfo *FI;
70     MachineModuleInfo *MMI;
71     const TargetInstrInfo *TII;
72     
73     void FindSafePoints(MachineFunction &MF);
74     void VisitCallPoint(MachineBasicBlock::iterator MI);
75     MCSymbol *InsertLabel(MachineBasicBlock &MBB, 
76                           MachineBasicBlock::iterator MI,
77                           DebugLoc DL) const;
78     
79     void FindStackOffsets(MachineFunction &MF);
80     
81   public:
82     static char ID;
83     
84     MachineCodeAnalysis();
85     const char *getPassName() const;
86     void getAnalysisUsage(AnalysisUsage &AU) const;
87     
88     bool runOnMachineFunction(MachineFunction &MF);
89   };
90   
91 }
92
93 // -----------------------------------------------------------------------------
94
95 GCStrategy::GCStrategy() :
96   NeededSafePoints(0),
97   CustomReadBarriers(false),
98   CustomWriteBarriers(false),
99   CustomRoots(false),
100   CustomSafePoints(false),
101   InitRoots(true),
102   UsesMetadata(false)
103 {}
104
105 GCStrategy::~GCStrategy() {
106   for (iterator I = begin(), E = end(); I != E; ++I)
107     delete *I;
108   
109   Functions.clear();
110 }
111  
112 bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
113  
114 bool GCStrategy::performCustomLowering(Function &F) {
115   dbgs() << "gc " << getName() << " must override performCustomLowering.\n";
116   llvm_unreachable(0);
117   return 0;
118 }
119
120
121 bool GCStrategy::findCustomSafePoints(GCFunctionInfo& FI, MachineFunction &F) {
122   dbgs() << "gc " << getName() << " must override findCustomSafePoints.\n";
123   llvm_unreachable(0);
124   return 0;
125 }
126
127
128 GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
129   GCFunctionInfo *FI = new GCFunctionInfo(F, *this);
130   Functions.push_back(FI);
131   return FI;
132 }
133
134 // -----------------------------------------------------------------------------
135
136 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering",
137                       false, false)
138 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
139 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
140
141 FunctionPass *llvm::createGCLoweringPass() {
142   return new LowerIntrinsics();
143 }
144  
145 char LowerIntrinsics::ID = 0;
146
147 LowerIntrinsics::LowerIntrinsics()
148   : FunctionPass(ID) {
149     initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
150   }
151
152 const char *LowerIntrinsics::getPassName() const {
153   return "Lower Garbage Collection Instructions";
154 }
155     
156 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
157   FunctionPass::getAnalysisUsage(AU);
158   AU.addRequired<GCModuleInfo>();
159   AU.addPreserved<DominatorTree>();
160 }
161
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
167   //        the module).
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.
173   
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))
178         MadeChange = true;
179   
180   return MadeChange;
181 }
182
183 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots, 
184                                                           unsigned Count) {
185   // Scroll past alloca instructions.
186   BasicBlock::iterator IP = F.getEntryBlock().begin();
187   while (isa<AllocaInst>(IP)) ++IP;
188   
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))
193       if (AllocaInst *AI =
194           dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
195         InitedRoots.insert(AI);
196   
197   // Add root initializers.
198   bool MadeChange = false;
199   
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())),
204                         *I);
205       SI->insertAfter(*I);
206       MadeChange = true;
207     }
208   
209   return MadeChange;
210 }
211
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();
218 }
219
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()
224       || C.customRoots();
225 }
226
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
231   // are:
232   // 
233   //   - call, invoke (AfterCall, BeforeCall)
234   //   - phis (Loops)
235   //   - invoke, ret, unwind (Exit)
236   // 
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.
240   
241   if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
242       isa<StoreInst>(I) || isa<LoadInst>(I))
243     return false;
244   
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)
250           return false;
251   
252   return true;
253 }
254
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.
259   if (!F.hasGC())
260     return false;
261   
262   GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
263   GCStrategy &S = FI.getStrategy();
264   
265   bool MadeChange = false;
266   
267   if (NeedsDefaultLoweringPass(S))
268     MadeChange |= PerformDefaultLowering(F, S);
269   
270   bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
271   if (UseCustomLoweringPass)
272     MadeChange |= S.performCustomLowering(F);
273
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);
278   }
279
280   return MadeChange;
281 }
282
283 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
284   bool LowerWr = !S.customWriteBarrier();
285   bool LowerRd = !S.customReadBarrier();
286   bool InitRoots = S.initializeRoots();
287   
288   SmallVector<AllocaInst*, 32> Roots;
289   
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:
297           if (LowerWr) {
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();
303           }
304           break;
305         case Intrinsic::gcread:
306           if (LowerRd) {
307             // Replace a read barrier with a simple load.
308             Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
309             Ld->takeName(CI);
310             CI->replaceAllUsesWith(Ld);
311             CI->eraseFromParent();
312           }
313           break;
314         case Intrinsic::gcroot:
315           if (InitRoots) {
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()));
320           }
321           break;
322         default:
323           continue;
324         }
325         
326         MadeChange = true;
327       }
328     }
329   }
330   
331   if (Roots.size())
332     MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
333   
334   return MadeChange;
335 }
336
337 // -----------------------------------------------------------------------------
338
339 FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
340   return new MachineCodeAnalysis();
341 }
342
343 char MachineCodeAnalysis::ID = 0;
344
345 MachineCodeAnalysis::MachineCodeAnalysis()
346   : MachineFunctionPass(ID) {}
347
348 const char *MachineCodeAnalysis::getPassName() const {
349   return "Analyze Machine Code For Garbage Collection";
350 }
351
352 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
353   MachineFunctionPass::getAnalysisUsage(AU);
354   AU.setPreservesAll();
355   AU.addRequired<MachineModuleInfo>();
356   AU.addRequired<GCModuleInfo>();
357 }
358
359 MCSymbol *MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB, 
360                                            MachineBasicBlock::iterator MI,
361                                            DebugLoc DL) const {
362   MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
363   BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
364   return Label;
365 }
366
367 void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
368   // Find the return address (next instruction), too, so as to bracket the call
369   // instruction.
370   MachineBasicBlock::iterator RAI = CI; 
371   ++RAI;                                
372   
373   if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
374     MCSymbol* Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
375     FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
376   }
377   
378   if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
379     MCSymbol* Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
380     FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
381   }
382 }
383
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)
389       if (MI->isCall())
390         VisitCallPoint(MI);
391 }
392
393 void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
394   const TargetFrameLowering *TFI = TM->getFrameLowering();
395   assert(TFI && "TargetRegisterInfo not available!");
396   
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);
400 }
401
402 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
403   // Quick exit for functions that do not use GC.
404   if (!MF.getFunction()->hasGC())
405     return false;
406   
407   FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
408   if (!FI->getStrategy().needsSafePoints())
409     return false;
410   
411   TM = &MF.getTarget();
412   MMI = &getAnalysis<MachineModuleInfo>();
413   TII = TM->getInstrInfo();
414   
415   // Find the size of the stack frame.
416   FI->setFrameSize(MF.getFrameInfo()->getStackSize());
417
418   // Find all safe points.
419   if (FI->getStrategy().customSafePoints()) {
420     FI->getStrategy().findCustomSafePoints(*FI, MF);
421   } else {
422     FindSafePoints(MF);
423   }
424   
425   // Find the stack offsets for all roots.
426   FindStackOffsets(MF);
427   
428   return false;
429 }