d51189cf497fec62e997238454457934b8f42295
[oota-llvm.git] / lib / Transforms / Scalar / LowerGC.cpp
1 //===-- LowerGC.cpp - Provide GC support for targets that don't -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements lowering for the llvm.gc* intrinsics for targets that do
11 // not natively support them (which includes the C backend).  Note that the code
12 // generated is not as efficient as it would be for targets that natively
13 // support the GC intrinsics, but it is useful for getting new targets
14 // up-and-running quickly.
15 //
16 // This pass implements the code transformation described in this paper:
17 //   "Accurate Garbage Collection in an Uncooperative Environment"
18 //   Fergus Henderson, ISMM, 2002
19 //
20 //===----------------------------------------------------------------------===//
21
22 #define DEBUG_TYPE "lowergc"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/Pass.h"
29 using namespace llvm;
30
31 namespace {
32   class LowerGC : public FunctionPass {
33     /// GCRootInt, GCReadInt, GCWriteInt - The function prototypes for the
34     /// llvm.gcread/llvm.gcwrite/llvm.gcroot intrinsics.
35     Function *GCRootInt, *GCReadInt, *GCWriteInt;
36
37     /// GCRead/GCWrite - These are the functions provided by the garbage
38     /// collector for read/write barriers.
39     Function *GCRead, *GCWrite;
40
41     /// RootChain - This is the global linked-list that contains the chain of GC
42     /// roots.
43     GlobalVariable *RootChain;
44
45     /// MainRootRecordType - This is the type for a function root entry if it
46     /// had zero roots.
47     const Type *MainRootRecordType;
48   public:
49     LowerGC() : GCRootInt(0), GCReadInt(0), GCWriteInt(0),
50                 GCRead(0), GCWrite(0), RootChain(0), MainRootRecordType(0) {}
51     virtual bool doInitialization(Module &M);
52     virtual bool runOnFunction(Function &F);
53
54   private:
55     const StructType *getRootRecordType(unsigned NumRoots);
56   };
57
58   RegisterOpt<LowerGC>
59   X("lowergc", "Lower GC intrinsics, for GCless code generators");
60 }
61
62 /// createLowerGCPass - This function returns an instance of the "lowergc"
63 /// pass, which lowers garbage collection intrinsics to normal LLVM code.
64 FunctionPass *llvm::createLowerGCPass() {
65   return new LowerGC();
66 }
67
68 /// getRootRecordType - This function creates and returns the type for a root
69 /// record containing 'NumRoots' roots.
70 const StructType *LowerGC::getRootRecordType(unsigned NumRoots) {
71   // Build a struct that is a type used for meta-data/root pairs.
72   std::vector<const Type *> ST;
73   ST.push_back(GCRootInt->getFunctionType()->getParamType(0));
74   ST.push_back(GCRootInt->getFunctionType()->getParamType(1));
75   StructType *PairTy = StructType::get(ST);
76
77   // Build the array of pairs.
78   ArrayType *PairArrTy = ArrayType::get(PairTy, NumRoots);
79
80   // Now build the recursive list type.
81   PATypeHolder RootListH =
82     MainRootRecordType ? (Type*)MainRootRecordType : (Type*)OpaqueType::get();
83   ST.clear();
84   ST.push_back(PointerType::get(RootListH));         // Prev pointer
85   ST.push_back(Type::UIntTy);                        // NumElements in array
86   ST.push_back(PairArrTy);                           // The pairs
87   StructType *RootList = StructType::get(ST);
88   if (MainRootRecordType)
89     return RootList;
90
91   assert(NumRoots == 0 && "The main struct type should have zero entries!");
92   cast<OpaqueType>((Type*)RootListH.get())->refineAbstractTypeTo(RootList);
93   MainRootRecordType = RootListH;
94   return cast<StructType>(RootListH.get());
95 }
96
97 /// doInitialization - If this module uses the GC intrinsics, find them now.  If
98 /// not, this pass does not do anything.
99 bool LowerGC::doInitialization(Module &M) {
100   GCRootInt  = M.getNamedFunction("llvm.gcroot");
101   GCReadInt  = M.getNamedFunction("llvm.gcread");
102   GCWriteInt = M.getNamedFunction("llvm.gcwrite");
103   if (!GCRootInt && !GCReadInt && !GCWriteInt) return false;
104
105   PointerType *VoidPtr = PointerType::get(Type::SByteTy);
106   PointerType *VoidPtrPtr = PointerType::get(VoidPtr);
107
108   // If the program is using read/write barriers, find the implementations of
109   // them from the GC runtime library.
110   if (GCReadInt)        // Make:  sbyte* %llvm_gc_read(sbyte**)
111     GCRead = M.getOrInsertFunction("llvm_gc_read", VoidPtr, VoidPtr, VoidPtrPtr,
112                                    (Type *)0);
113   if (GCWriteInt)       // Make:  void %llvm_gc_write(sbyte*, sbyte**)
114     GCWrite = M.getOrInsertFunction("llvm_gc_write", Type::VoidTy,
115                                     VoidPtr, VoidPtr, VoidPtrPtr, (Type *)0);
116
117   // If the program has GC roots, get or create the global root list.
118   if (GCRootInt) {
119     const StructType *RootListTy = getRootRecordType(0);
120     const Type *PRLTy = PointerType::get(RootListTy);
121     M.addTypeName("llvm_gc_root_ty", RootListTy);
122
123     // Get the root chain if it already exists.
124     RootChain = M.getGlobalVariable("llvm_gc_root_chain", PRLTy);
125     if (RootChain == 0) {
126       // If the root chain does not exist, insert a new one with linkonce
127       // linkage!
128       RootChain = new GlobalVariable(PRLTy, false,
129                                      GlobalValue::LinkOnceLinkage,
130                                      Constant::getNullValue(PRLTy),
131                                      "llvm_gc_root_chain", &M);
132     } else if (RootChain->hasExternalLinkage() && RootChain->isExternal()) {
133       RootChain->setInitializer(Constant::getNullValue(PRLTy));
134       RootChain->setLinkage(GlobalValue::LinkOnceLinkage);
135     }
136   }
137   return true;
138 }
139
140 /// Coerce - If the specified operand number of the specified instruction does
141 /// not have the specified type, insert a cast.
142 static void Coerce(Instruction *I, unsigned OpNum, Type *Ty) {
143   if (I->getOperand(OpNum)->getType() != Ty) {
144     if (Constant *C = dyn_cast<Constant>(I->getOperand(OpNum)))
145       I->setOperand(OpNum, ConstantExpr::getCast(C, Ty));
146     else {
147       CastInst *CI = new CastInst(I->getOperand(OpNum), Ty, "", I);
148       I->setOperand(OpNum, CI);
149     }
150   }
151 }
152
153 /// runOnFunction - If the program is using GC intrinsics, replace any
154 /// read/write intrinsics with the appropriate read/write barrier calls, then
155 /// inline them.  Finally, build the data structures for
156 bool LowerGC::runOnFunction(Function &F) {
157   // Quick exit for programs that are not using GC mechanisms.
158   if (!GCRootInt && !GCReadInt && !GCWriteInt) return false;
159
160   PointerType *VoidPtr    = PointerType::get(Type::SByteTy);
161   PointerType *VoidPtrPtr = PointerType::get(VoidPtr);
162
163   // If there are read/write barriers in the program, perform a quick pass over
164   // the function eliminating them.  While we are at it, remember where we see
165   // calls to llvm.gcroot.
166   std::vector<CallInst*> GCRoots;
167   std::vector<CallInst*> NormalCalls;
168
169   bool MadeChange = false;
170   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
171     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
172       if (CallInst *CI = dyn_cast<CallInst>(II++)) {
173         if (!CI->getCalledFunction() ||
174             !CI->getCalledFunction()->getIntrinsicID())
175           NormalCalls.push_back(CI);   // Remember all normal function calls.
176
177         if (Function *F = CI->getCalledFunction())
178           if (F == GCRootInt)
179             GCRoots.push_back(CI);
180           else if (F == GCReadInt || F == GCWriteInt) {
181             if (F == GCWriteInt) {
182               // Change a llvm.gcwrite call to call llvm_gc_write instead.
183               CI->setOperand(0, GCWrite);
184               // Insert casts of the operands as needed.
185               Coerce(CI, 1, VoidPtr);
186               Coerce(CI, 2, VoidPtr);
187               Coerce(CI, 3, VoidPtrPtr);
188             } else {
189               Coerce(CI, 1, VoidPtr);
190               Coerce(CI, 2, VoidPtrPtr);
191               if (CI->getType() == VoidPtr) {
192                 CI->setOperand(0, GCRead);
193               } else {
194                 // Create a whole new call to replace the old one.
195                 CallInst *NC = new CallInst(GCRead, CI->getOperand(1),
196                                             CI->getOperand(2),
197                                             CI->getName(), CI);
198                 Value *NV = new CastInst(NC, CI->getType(), "", CI);
199                 CI->replaceAllUsesWith(NV);
200                 BB->getInstList().erase(CI);
201                 CI = NC;
202               }
203             }
204
205             MadeChange = true;
206           }
207       }
208
209   // If there are no GC roots in this function, then there is no need to create
210   // a GC list record for it.
211   if (GCRoots.empty()) return MadeChange;
212
213   // Okay, there are GC roots in this function.  On entry to the function, add a
214   // record to the llvm_gc_root_chain, and remove it on exit.
215
216   // Create the alloca, and zero it out.
217   const StructType *RootListTy = getRootRecordType(GCRoots.size());
218   AllocaInst *AI = new AllocaInst(RootListTy, 0, "gcroots", F.begin()->begin());
219
220   // Insert the memset call after all of the allocas in the function.
221   BasicBlock::iterator IP = AI;
222   while (isa<AllocaInst>(IP)) ++IP;
223
224   Constant *Zero = ConstantUInt::get(Type::UIntTy, 0);
225   Constant *One  = ConstantUInt::get(Type::UIntTy, 1);
226
227   // Get a pointer to the prev pointer.
228   std::vector<Value*> Par;
229   Par.push_back(Zero);
230   Par.push_back(Zero);
231   Value *PrevPtrPtr = new GetElementPtrInst(AI, Par, "prevptrptr", IP);
232
233   // Load the previous pointer.
234   Value *PrevPtr = new LoadInst(RootChain, "prevptr", IP);
235   // Store the previous pointer into the prevptrptr
236   new StoreInst(PrevPtr, PrevPtrPtr, IP);
237
238   // Set the number of elements in this record.
239   Par[1] = ConstantUInt::get(Type::UIntTy, 1);
240   Value *NumEltsPtr = new GetElementPtrInst(AI, Par, "numeltsptr", IP);
241   new StoreInst(ConstantUInt::get(Type::UIntTy, GCRoots.size()), NumEltsPtr,IP);
242
243   Par[1] = ConstantUInt::get(Type::UIntTy, 2);
244   Par.resize(4);
245
246   const PointerType *PtrLocTy =
247     cast<PointerType>(GCRootInt->getFunctionType()->getParamType(0));
248   Constant *Null = ConstantPointerNull::get(PtrLocTy);
249
250   // Initialize all of the gcroot records now, and eliminate them as we go.
251   for (unsigned i = 0, e = GCRoots.size(); i != e; ++i) {
252     // Initialize the meta-data pointer.
253     Par[2] = ConstantUInt::get(Type::UIntTy, i);
254     Par[3] = One;
255     Value *MetaDataPtr = new GetElementPtrInst(AI, Par, "MetaDataPtr", IP);
256     assert(isa<Constant>(GCRoots[i]->getOperand(2)) && "Must be a constant");
257     new StoreInst(GCRoots[i]->getOperand(2), MetaDataPtr, IP);
258
259     // Initialize the root pointer to null on entry to the function.
260     Par[3] = Zero;
261     Value *RootPtrPtr = new GetElementPtrInst(AI, Par, "RootEntPtr", IP);
262     new StoreInst(Null, RootPtrPtr, IP);
263
264     // Each occurrance of the llvm.gcroot intrinsic now turns into an
265     // initialization of the slot with the address and a zeroing out of the
266     // address specified.
267     new StoreInst(Constant::getNullValue(PtrLocTy->getElementType()),
268                   GCRoots[i]->getOperand(1), GCRoots[i]);
269     new StoreInst(GCRoots[i]->getOperand(1), RootPtrPtr, GCRoots[i]);
270     GCRoots[i]->getParent()->getInstList().erase(GCRoots[i]);
271   }
272
273   // Now that the record is all initialized, store the pointer into the global
274   // pointer.
275   Value *C = new CastInst(AI, PointerType::get(MainRootRecordType), "", IP);
276   new StoreInst(C, RootChain, IP);
277
278   // On exit from the function we have to remove the entry from the GC root
279   // chain.  Doing this is straight-forward for return and unwind instructions:
280   // just insert the appropriate copy.
281   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
282     if (isa<UnwindInst>(BB->getTerminator()) ||
283         isa<ReturnInst>(BB->getTerminator())) {
284       // We could reuse the PrevPtr loaded on entry to the function, but this
285       // would make the value live for the whole function, which is probably a
286       // bad idea.  Just reload the value out of our stack entry.
287       PrevPtr = new LoadInst(PrevPtrPtr, "prevptr", BB->getTerminator());
288       new StoreInst(PrevPtr, RootChain, BB->getTerminator());
289     }
290
291   // If an exception is thrown from a callee we have to make sure to
292   // unconditionally take the record off the stack.  For this reason, we turn
293   // all call instructions into invoke whose cleanup pops the entry off the
294   // stack.  We only insert one cleanup block, which is shared by all invokes.
295   if (!NormalCalls.empty()) {
296     // Create the shared cleanup block.
297     BasicBlock *Cleanup = new BasicBlock("gc_cleanup", &F);
298     UnwindInst *UI = new UnwindInst(Cleanup);
299     PrevPtr = new LoadInst(PrevPtrPtr, "prevptr", UI);
300     new StoreInst(PrevPtr, RootChain, UI);
301
302     // Loop over all of the function calls, turning them into invokes.
303     while (!NormalCalls.empty()) {
304       CallInst *CI = NormalCalls.back();
305       BasicBlock *CBB = CI->getParent();
306       NormalCalls.pop_back();
307
308       // Split the basic block containing the function call.
309       BasicBlock *NewBB = CBB->splitBasicBlock(CI, CBB->getName()+".cont");
310
311       // Remove the unconditional branch inserted at the end of the CBB.
312       CBB->getInstList().pop_back();
313       NewBB->getInstList().remove(CI);
314
315       // Create a new invoke instruction.
316       Value *II = new InvokeInst(CI->getCalledValue(), NewBB, Cleanup,
317                                  std::vector<Value*>(CI->op_begin()+1,
318                                                      CI->op_end()),
319                                  CI->getName(), CBB);
320       CI->replaceAllUsesWith(II);
321       delete CI;
322     }
323   }
324
325   return true;
326 }