Extract live range calculations from SplitKit.
[oota-llvm.git] / lib / CodeGen / ShadowStackGC.cpp
1 //===-- ShadowStackGC.cpp - GC support for uncooperative targets ----------===//
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 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 quite as efficient as algorithms which generate stack maps
13 // to identify roots.
14 //
15 // This pass implements the code transformation described in this paper:
16 //   "Accurate Garbage Collection in an Uncooperative Environment"
17 //   Fergus Henderson, ISMM, 2002
18 //
19 // In runtime/GC/SemiSpace.cpp is a prototype runtime which is compatible with
20 // ShadowStackGC.
21 //
22 // In order to support this particular transformation, all stack roots are
23 // coallocated in the stack. This allows a fully target-independent stack map
24 // while introducing only minor runtime overhead.
25 //
26 //===----------------------------------------------------------------------===//
27
28 #define DEBUG_TYPE "shadowstackgc"
29 #include "llvm/CodeGen/GCs.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/CodeGen/GCStrategy.h"
32 #include "llvm/IntrinsicInst.h"
33 #include "llvm/Module.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/IRBuilder.h"
36
37 using namespace llvm;
38
39 namespace {
40
41   class ShadowStackGC : public GCStrategy {
42     /// RootChain - This is the global linked-list that contains the chain of GC
43     /// roots.
44     GlobalVariable *Head;
45
46     /// StackEntryTy - Abstract type of a link in the shadow stack.
47     ///
48     StructType *StackEntryTy;
49     StructType *FrameMapTy;
50
51     /// Roots - GC roots in the current function. Each is a pair of the
52     /// intrinsic call and its corresponding alloca.
53     std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
54
55   public:
56     ShadowStackGC();
57
58     bool initializeCustomLowering(Module &M);
59     bool performCustomLowering(Function &F);
60
61   private:
62     bool IsNullValue(Value *V);
63     Constant *GetFrameMap(Function &F);
64     Type* GetConcreteStackEntryType(Function &F);
65     void CollectRoots(Function &F);
66     static GetElementPtrInst *CreateGEP(LLVMContext &Context, 
67                                         IRBuilder<> &B, Value *BasePtr,
68                                         int Idx1, const char *Name);
69     static GetElementPtrInst *CreateGEP(LLVMContext &Context,
70                                         IRBuilder<> &B, Value *BasePtr,
71                                         int Idx1, int Idx2, const char *Name);
72   };
73
74 }
75
76 static GCRegistry::Add<ShadowStackGC>
77 X("shadow-stack", "Very portable GC for uncooperative code generators");
78
79 namespace {
80   /// EscapeEnumerator - This is a little algorithm to find all escape points
81   /// from a function so that "finally"-style code can be inserted. In addition
82   /// to finding the existing return and unwind instructions, it also (if
83   /// necessary) transforms any call instructions into invokes and sends them to
84   /// a landing pad.
85   ///
86   /// It's wrapped up in a state machine using the same transform C# uses for
87   /// 'yield return' enumerators, This transform allows it to be non-allocating.
88   class EscapeEnumerator {
89     Function &F;
90     const char *CleanupBBName;
91
92     // State.
93     int State;
94     Function::iterator StateBB, StateE;
95     IRBuilder<> Builder;
96
97   public:
98     EscapeEnumerator(Function &F, const char *N = "cleanup")
99       : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
100
101     IRBuilder<> *Next() {
102       switch (State) {
103       default:
104         return 0;
105
106       case 0:
107         StateBB = F.begin();
108         StateE = F.end();
109         State = 1;
110
111       case 1:
112         // Find all 'return' and 'unwind' instructions.
113         while (StateBB != StateE) {
114           BasicBlock *CurBB = StateBB++;
115
116           // Branches and invokes do not escape, only unwind, resume, and return
117           // do.
118           TerminatorInst *TI = CurBB->getTerminator();
119           if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI) &&
120               !isa<ResumeInst>(TI))
121             continue;
122
123           Builder.SetInsertPoint(TI->getParent(), TI);
124           return &Builder;
125         }
126
127         State = 2;
128
129         // Find all 'call' instructions.
130         SmallVector<Instruction*,16> Calls;
131         for (Function::iterator BB = F.begin(),
132                                 E = F.end(); BB != E; ++BB)
133           for (BasicBlock::iterator II = BB->begin(),
134                                     EE = BB->end(); II != EE; ++II)
135             if (CallInst *CI = dyn_cast<CallInst>(II))
136               if (!CI->getCalledFunction() ||
137                   !CI->getCalledFunction()->getIntrinsicID())
138                 Calls.push_back(CI);
139
140         if (Calls.empty())
141           return 0;
142
143         // Create a cleanup block.
144         BasicBlock *CleanupBB = BasicBlock::Create(F.getContext(),
145                                                    CleanupBBName, &F);
146         UnwindInst *UI = new UnwindInst(F.getContext(), CleanupBB);
147
148         // Transform the 'call' instructions into 'invoke's branching to the
149         // cleanup block. Go in reverse order to make prettier BB names.
150         SmallVector<Value*,16> Args;
151         for (unsigned I = Calls.size(); I != 0; ) {
152           CallInst *CI = cast<CallInst>(Calls[--I]);
153
154           // Split the basic block containing the function call.
155           BasicBlock *CallBB = CI->getParent();
156           BasicBlock *NewBB =
157             CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
158
159           // Remove the unconditional branch inserted at the end of CallBB.
160           CallBB->getInstList().pop_back();
161           NewBB->getInstList().remove(CI);
162
163           // Create a new invoke instruction.
164           Args.clear();
165           CallSite CS(CI);
166           Args.append(CS.arg_begin(), CS.arg_end());
167
168           InvokeInst *II = InvokeInst::Create(CI->getCalledValue(),
169                                               NewBB, CleanupBB,
170                                               Args, CI->getName(), CallBB);
171           II->setCallingConv(CI->getCallingConv());
172           II->setAttributes(CI->getAttributes());
173           CI->replaceAllUsesWith(II);
174           delete CI;
175         }
176
177         Builder.SetInsertPoint(UI->getParent(), UI);
178         return &Builder;
179       }
180     }
181   };
182 }
183
184 // -----------------------------------------------------------------------------
185
186 void llvm::linkShadowStackGC() { }
187
188 ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
189   InitRoots = true;
190   CustomRoots = true;
191 }
192
193 Constant *ShadowStackGC::GetFrameMap(Function &F) {
194   // doInitialization creates the abstract type of this value.
195   Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
196
197   // Truncate the ShadowStackDescriptor if some metadata is null.
198   unsigned NumMeta = 0;
199   SmallVector<Constant*, 16> Metadata;
200   for (unsigned I = 0; I != Roots.size(); ++I) {
201     Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
202     if (!C->isNullValue())
203       NumMeta = I + 1;
204     Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
205   }
206   Metadata.resize(NumMeta);
207
208   Type *Int32Ty = Type::getInt32Ty(F.getContext());
209   
210   Constant *BaseElts[] = {
211     ConstantInt::get(Int32Ty, Roots.size(), false),
212     ConstantInt::get(Int32Ty, NumMeta, false),
213   };
214
215   Constant *DescriptorElts[] = {
216     ConstantStruct::get(FrameMapTy, BaseElts),
217     ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)
218   };
219
220   Type *EltTys[] = { DescriptorElts[0]->getType(),DescriptorElts[1]->getType()};
221   StructType *STy = StructType::create(EltTys, "gc_map."+utostr(NumMeta));
222   
223   Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
224
225   // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
226   //        that, short of multithreaded LLVM, it should be safe; all that is
227   //        necessary is that a simple Module::iterator loop not be invalidated.
228   //        Appending to the GlobalVariable list is safe in that sense.
229   //
230   //        All of the output passes emit globals last. The ExecutionEngine
231   //        explicitly supports adding globals to the module after
232   //        initialization.
233   //
234   //        Still, if it isn't deemed acceptable, then this transformation needs
235   //        to be a ModulePass (which means it cannot be in the 'llc' pipeline
236   //        (which uses a FunctionPassManager (which segfaults (not asserts) if
237   //        provided a ModulePass))).
238   Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
239                                     GlobalVariable::InternalLinkage,
240                                     FrameMap, "__gc_" + F.getName());
241
242   Constant *GEPIndices[2] = {
243                           ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
244                           ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)
245                           };
246   return ConstantExpr::getGetElementPtr(GV, GEPIndices);
247 }
248
249 Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
250   // doInitialization creates the generic version of this type.
251   std::vector<Type*> EltTys;
252   EltTys.push_back(StackEntryTy);
253   for (size_t I = 0; I != Roots.size(); I++)
254     EltTys.push_back(Roots[I].second->getAllocatedType());
255   
256   return StructType::create(EltTys, "gc_stackentry."+F.getName().str());
257 }
258
259 /// doInitialization - If this module uses the GC intrinsics, find them now. If
260 /// not, exit fast.
261 bool ShadowStackGC::initializeCustomLowering(Module &M) {
262   // struct FrameMap {
263   //   int32_t NumRoots; // Number of roots in stack frame.
264   //   int32_t NumMeta;  // Number of metadata descriptors. May be < NumRoots.
265   //   void *Meta[];     // May be absent for roots without metadata.
266   // };
267   std::vector<Type*> EltTys;
268   // 32 bits is ok up to a 32GB stack frame. :)
269   EltTys.push_back(Type::getInt32Ty(M.getContext()));
270   // Specifies length of variable length array. 
271   EltTys.push_back(Type::getInt32Ty(M.getContext()));
272   FrameMapTy = StructType::create(EltTys, "gc_map");
273   PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
274
275   // struct StackEntry {
276   //   ShadowStackEntry *Next; // Caller's stack entry.
277   //   FrameMap *Map;          // Pointer to constant FrameMap.
278   //   void *Roots[];          // Stack roots (in-place array, so we pretend).
279   // };
280   
281   StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
282   
283   EltTys.clear();
284   EltTys.push_back(PointerType::getUnqual(StackEntryTy));
285   EltTys.push_back(FrameMapPtrTy);
286   StackEntryTy->setBody(EltTys);
287   PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
288
289   // Get the root chain if it already exists.
290   Head = M.getGlobalVariable("llvm_gc_root_chain");
291   if (!Head) {
292     // If the root chain does not exist, insert a new one with linkonce
293     // linkage!
294     Head = new GlobalVariable(M, StackEntryPtrTy, false,
295                               GlobalValue::LinkOnceAnyLinkage,
296                               Constant::getNullValue(StackEntryPtrTy),
297                               "llvm_gc_root_chain");
298   } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
299     Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
300     Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
301   }
302
303   return true;
304 }
305
306 bool ShadowStackGC::IsNullValue(Value *V) {
307   if (Constant *C = dyn_cast<Constant>(V))
308     return C->isNullValue();
309   return false;
310 }
311
312 void ShadowStackGC::CollectRoots(Function &F) {
313   // FIXME: Account for original alignment. Could fragment the root array.
314   //   Approach 1: Null initialize empty slots at runtime. Yuck.
315   //   Approach 2: Emit a map of the array instead of just a count.
316
317   assert(Roots.empty() && "Not cleaned up?");
318
319   SmallVector<std::pair<CallInst*, AllocaInst*>, 16> MetaRoots;
320
321   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
322     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
323       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
324         if (Function *F = CI->getCalledFunction())
325           if (F->getIntrinsicID() == Intrinsic::gcroot) {
326             std::pair<CallInst*, AllocaInst*> Pair = std::make_pair(
327               CI, cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
328             if (IsNullValue(CI->getArgOperand(1)))
329               Roots.push_back(Pair);
330             else
331               MetaRoots.push_back(Pair);
332           }
333
334   // Number roots with metadata (usually empty) at the beginning, so that the
335   // FrameMap::Meta array can be elided.
336   Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
337 }
338
339 GetElementPtrInst *
340 ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
341                          int Idx, int Idx2, const char *Name) {
342   Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
343                        ConstantInt::get(Type::getInt32Ty(Context), Idx),
344                        ConstantInt::get(Type::getInt32Ty(Context), Idx2) };
345   Value* Val = B.CreateGEP(BasePtr, Indices, Name);
346
347   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
348
349   return dyn_cast<GetElementPtrInst>(Val);
350 }
351
352 GetElementPtrInst *
353 ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
354                          int Idx, const char *Name) {
355   Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
356                        ConstantInt::get(Type::getInt32Ty(Context), Idx) };
357   Value *Val = B.CreateGEP(BasePtr, Indices, Name);
358
359   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
360
361   return dyn_cast<GetElementPtrInst>(Val);
362 }
363
364 /// runOnFunction - Insert code to maintain the shadow stack.
365 bool ShadowStackGC::performCustomLowering(Function &F) {
366   LLVMContext &Context = F.getContext();
367   
368   // Find calls to llvm.gcroot.
369   CollectRoots(F);
370
371   // If there are no roots in this function, then there is no need to add a
372   // stack map entry for it.
373   if (Roots.empty())
374     return false;
375
376   // Build the constant map and figure the type of the shadow stack entry.
377   Value *FrameMap = GetFrameMap(F);
378   Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
379
380   // Build the shadow stack entry at the very start of the function.
381   BasicBlock::iterator IP = F.getEntryBlock().begin();
382   IRBuilder<> AtEntry(IP->getParent(), IP);
383
384   Instruction *StackEntry   = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
385                                                    "gc_frame");
386
387   while (isa<AllocaInst>(IP)) ++IP;
388   AtEntry.SetInsertPoint(IP->getParent(), IP);
389
390   // Initialize the map pointer and load the current head of the shadow stack.
391   Instruction *CurrentHead  = AtEntry.CreateLoad(Head, "gc_currhead");
392   Instruction *EntryMapPtr  = CreateGEP(Context, AtEntry, StackEntry,
393                                         0,1,"gc_frame.map");
394   AtEntry.CreateStore(FrameMap, EntryMapPtr);
395
396   // After all the allocas...
397   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
398     // For each root, find the corresponding slot in the aggregate...
399     Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root");
400
401     // And use it in lieu of the alloca.
402     AllocaInst *OriginalAlloca = Roots[I].second;
403     SlotPtr->takeName(OriginalAlloca);
404     OriginalAlloca->replaceAllUsesWith(SlotPtr);
405   }
406
407   // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
408   // really necessary (the collector would never see the intermediate state at
409   // runtime), but it's nicer not to push the half-initialized entry onto the
410   // shadow stack.
411   while (isa<StoreInst>(IP)) ++IP;
412   AtEntry.SetInsertPoint(IP->getParent(), IP);
413
414   // Push the entry onto the shadow stack.
415   Instruction *EntryNextPtr = CreateGEP(Context, AtEntry,
416                                         StackEntry,0,0,"gc_frame.next");
417   Instruction *NewHeadVal   = CreateGEP(Context, AtEntry, 
418                                         StackEntry, 0, "gc_newhead");
419   AtEntry.CreateStore(CurrentHead, EntryNextPtr);
420   AtEntry.CreateStore(NewHeadVal, Head);
421
422   // For each instruction that escapes...
423   EscapeEnumerator EE(F, "gc_cleanup");
424   while (IRBuilder<> *AtExit = EE.Next()) {
425     // Pop the entry from the shadow stack. Don't reuse CurrentHead from
426     // AtEntry, since that would make the value live for the entire function.
427     Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0,
428                                            "gc_frame.next");
429     Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
430                        AtExit->CreateStore(SavedHead, Head);
431   }
432
433   // Delete the original allocas (which are no longer used) and the intrinsic
434   // calls (which are no longer valid). Doing this last avoids invalidating
435   // iterators.
436   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
437     Roots[I].first->eraseFromParent();
438     Roots[I].second->eraseFromParent();
439   }
440
441   Roots.clear();
442   return true;
443 }