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