Style cleanup of old gc.root lowering code
[oota-llvm.git] / lib / CodeGen / GCRootLowering.cpp
1 //===-- GCRootLowering.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 the lowering for the gc.root mechanism.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/GCStrategy.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineFunctionPass.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/IR/Dominators.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetFrameLowering.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Target/TargetSubtargetInfo.h"
31
32 using namespace llvm;
33
34 namespace {
35
36 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
37 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
38 /// directed by the GCStrategy. It also performs automatic root initialization
39 /// and custom intrinsic lowering.
40 class LowerIntrinsics : public FunctionPass {
41   bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
42
43 public:
44   static char ID;
45
46   LowerIntrinsics();
47   const char *getPassName() const override;
48   void getAnalysisUsage(AnalysisUsage &AU) const override;
49
50   bool doInitialization(Module &M) override;
51   bool runOnFunction(Function &F) override;
52 };
53
54 /// GCMachineCodeAnalysis - This is a target-independent pass over the machine
55 /// function representation to identify safe points for the garbage collector
56 /// in the machine code. It inserts labels at safe points and populates a
57 /// GCMetadata record for each function.
58 class GCMachineCodeAnalysis : public MachineFunctionPass {
59   const TargetMachine *TM;
60   GCFunctionInfo *FI;
61   MachineModuleInfo *MMI;
62   const TargetInstrInfo *TII;
63
64   void FindSafePoints(MachineFunction &MF);
65   void VisitCallPoint(MachineBasicBlock::iterator MI);
66   MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
67                         DebugLoc DL) const;
68
69   void FindStackOffsets(MachineFunction &MF);
70
71 public:
72   static char ID;
73
74   GCMachineCodeAnalysis();
75   void getAnalysisUsage(AnalysisUsage &AU) const override;
76
77   bool runOnMachineFunction(MachineFunction &MF) override;
78 };
79 }
80
81 // -----------------------------------------------------------------------------
82
83 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
84                       false)
85 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
86 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
87
88 FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
89
90 char LowerIntrinsics::ID = 0;
91
92 LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
93   initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
94 }
95
96 const char *LowerIntrinsics::getPassName() const {
97   return "Lower Garbage Collection Instructions";
98 }
99
100 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
101   FunctionPass::getAnalysisUsage(AU);
102   AU.addRequired<GCModuleInfo>();
103   AU.addPreserved<DominatorTreeWrapperPass>();
104 }
105
106 static bool NeedsDefaultLoweringPass(const GCStrategy &C) {
107   // Default lowering is necessary only if read or write barriers have a default
108   // action. The default for roots is no action.
109   return !C.customWriteBarrier() || !C.customReadBarrier() ||
110          C.initializeRoots();
111 }
112
113 static bool NeedsCustomLoweringPass(const GCStrategy &C) {
114   // Custom lowering is only necessary if enabled for some action.
115   return C.customWriteBarrier() || C.customReadBarrier() || C.customRoots();
116 }
117
118
119
120 /// doInitialization - If this module uses the GC intrinsics, find them now.
121 bool LowerIntrinsics::doInitialization(Module &M) {
122   // FIXME: This is rather antisocial in the context of a JIT since it performs
123   //        work against the entire module. But this cannot be done at
124   //        runFunction time (initializeCustomLowering likely needs to change
125   //        the module).
126   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
127   assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
128   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
129     if (!I->isDeclaration() && I->hasGC())
130       MI->getFunctionInfo(*I); // Instantiate the GC strategy.
131
132   bool MadeChange = false;
133   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
134     if (NeedsCustomLoweringPass(**I))
135       if ((*I)->initializeCustomLowering(M))
136         MadeChange = true;
137
138   return MadeChange;
139 }
140
141
142 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
143 /// instruction could introduce a safe point.
144 static bool CouldBecomeSafePoint(Instruction *I) {
145   // The natural definition of instructions which could introduce safe points
146   // are:
147   //
148   //   - call, invoke (AfterCall, BeforeCall)
149   //   - phis (Loops)
150   //   - invoke, ret, unwind (Exit)
151   //
152   // However, instructions as seemingly inoccuous as arithmetic can become
153   // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
154   // it is necessary to take a conservative approach.
155
156   if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
157       isa<LoadInst>(I))
158     return false;
159
160   // llvm.gcroot is safe because it doesn't do anything at runtime.
161   if (CallInst *CI = dyn_cast<CallInst>(I))
162     if (Function *F = CI->getCalledFunction())
163       if (unsigned IID = F->getIntrinsicID())
164         if (IID == Intrinsic::gcroot)
165           return false;
166
167   return true;
168 }
169
170 static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
171                                    unsigned Count) {
172   // Scroll past alloca instructions.
173   BasicBlock::iterator IP = F.getEntryBlock().begin();
174   while (isa<AllocaInst>(IP))
175     ++IP;
176
177   // Search for initializers in the initial BB.
178   SmallPtrSet<AllocaInst *, 16> InitedRoots;
179   for (; !CouldBecomeSafePoint(IP); ++IP)
180     if (StoreInst *SI = dyn_cast<StoreInst>(IP))
181       if (AllocaInst *AI =
182               dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
183         InitedRoots.insert(AI);
184
185   // Add root initializers.
186   bool MadeChange = false;
187
188   for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
189     if (!InitedRoots.count(*I)) {
190       StoreInst *SI = new StoreInst(
191           ConstantPointerNull::get(cast<PointerType>(
192               cast<PointerType>((*I)->getType())->getElementType())),
193           *I);
194       SI->insertAfter(*I);
195       MadeChange = true;
196     }
197
198   return MadeChange;
199 }
200
201
202 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
203 /// Leave gcroot intrinsics; the code generator needs to see those.
204 bool LowerIntrinsics::runOnFunction(Function &F) {
205   // Quick exit for functions that do not use GC.
206   if (!F.hasGC())
207     return false;
208
209   GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
210   GCStrategy &S = FI.getStrategy();
211
212   bool MadeChange = false;
213
214   if (NeedsDefaultLoweringPass(S))
215     MadeChange |= PerformDefaultLowering(F, S);
216
217   bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
218   if (UseCustomLoweringPass)
219     MadeChange |= S.performCustomLowering(F);
220
221   // Custom lowering may modify the CFG, so dominators must be recomputed.
222   if (UseCustomLoweringPass) {
223     if (DominatorTreeWrapperPass *DTWP =
224             getAnalysisIfAvailable<DominatorTreeWrapperPass>())
225       DTWP->getDomTree().recalculate(F);
226   }
227
228   return MadeChange;
229 }
230
231 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
232   bool LowerWr = !S.customWriteBarrier();
233   bool LowerRd = !S.customReadBarrier();
234   bool InitRoots = S.initializeRoots();
235
236   SmallVector<AllocaInst *, 32> Roots;
237
238   bool MadeChange = false;
239   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
240     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
241       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
242         Function *F = CI->getCalledFunction();
243         switch (F->getIntrinsicID()) {
244         case Intrinsic::gcwrite:
245           if (LowerWr) {
246             // Replace a write barrier with a simple store.
247             Value *St =
248                 new StoreInst(CI->getArgOperand(0), CI->getArgOperand(2), CI);
249             CI->replaceAllUsesWith(St);
250             CI->eraseFromParent();
251           }
252           break;
253         case Intrinsic::gcread:
254           if (LowerRd) {
255             // Replace a read barrier with a simple load.
256             Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
257             Ld->takeName(CI);
258             CI->replaceAllUsesWith(Ld);
259             CI->eraseFromParent();
260           }
261           break;
262         case Intrinsic::gcroot:
263           if (InitRoots) {
264             // Initialize the GC root, but do not delete the intrinsic. The
265             // backend needs the intrinsic to flag the stack slot.
266             Roots.push_back(
267                 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
268           }
269           break;
270         default:
271           continue;
272         }
273
274         MadeChange = true;
275       }
276     }
277   }
278
279   if (Roots.size())
280     MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
281
282   return MadeChange;
283 }
284
285 // -----------------------------------------------------------------------------
286
287 char GCMachineCodeAnalysis::ID = 0;
288 char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
289
290 INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
291                 "Analyze Machine Code For Garbage Collection", false, false)
292
293 GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
294
295 void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
296   MachineFunctionPass::getAnalysisUsage(AU);
297   AU.setPreservesAll();
298   AU.addRequired<MachineModuleInfo>();
299   AU.addRequired<GCModuleInfo>();
300 }
301
302 MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
303                                              MachineBasicBlock::iterator MI,
304                                              DebugLoc DL) const {
305   MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
306   BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
307   return Label;
308 }
309
310 void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
311   // Find the return address (next instruction), too, so as to bracket the call
312   // instruction.
313   MachineBasicBlock::iterator RAI = CI;
314   ++RAI;
315
316   if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
317     MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
318     FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
319   }
320
321   if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
322     MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
323     FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
324   }
325 }
326
327 void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
328   for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
329        ++BBI)
330     for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
331          MI != ME; ++MI)
332       if (MI->isCall())
333         VisitCallPoint(MI);
334 }
335
336 void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
337   const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
338   assert(TFI && "TargetRegisterInfo not available!");
339
340   for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
341        RI != FI->roots_end();) {
342     // If the root references a dead object, no need to keep it.
343     if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
344       RI = FI->removeStackRoot(RI);
345     } else {
346       RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
347       ++RI;
348     }
349   }
350 }
351
352 bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
353   // Quick exit for functions that do not use GC.
354   if (!MF.getFunction()->hasGC())
355     return false;
356
357   FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
358   if (!FI->getStrategy().needsSafePoints())
359     return false;
360
361   TM = &MF.getTarget();
362   MMI = &getAnalysis<MachineModuleInfo>();
363   TII = TM->getSubtargetImpl()->getInstrInfo();
364
365   // Find the size of the stack frame.
366   FI->setFrameSize(MF.getFrameInfo()->getStackSize());
367
368   // Find all safe points.
369   if (FI->getStrategy().customSafePoints()) {
370     FI->getStrategy().findCustomSafePoints(*FI, MF);
371   } else {
372     FindSafePoints(MF);
373   }
374
375   // Find the stack offsets for all roots.
376   FindStackOffsets(MF);
377
378   return false;
379 }