1 //===-- ShadowStackGC.cpp - GC support for uncooperative targets ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
15 // This pass implements the code transformation described in this paper:
16 // "Accurate Garbage Collection in an Uncooperative Environment"
17 // Fergus Henderson, ISMM, 2002
19 // In runtime/GC/SemiSpace.cpp is a prototype runtime which is compatible with
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.
26 //===----------------------------------------------------------------------===//
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"
41 class ShadowStackGC : public GCStrategy {
42 /// RootChain - This is the global linked-list that contains the chain of GC
46 /// StackEntryTy - Abstract type of a link in the shadow stack.
48 StructType *StackEntryTy;
49 StructType *FrameMapTy;
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;
58 bool initializeCustomLowering(Module &M);
59 bool performCustomLowering(Function &F);
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);
76 static GCRegistry::Add<ShadowStackGC>
77 X("shadow-stack", "Very portable GC for uncooperative code generators");
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
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 {
90 const char *CleanupBBName;
94 Function::iterator StateBB, StateE;
98 EscapeEnumerator(Function &F, const char *N = "cleanup")
99 : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
101 IRBuilder<> *Next() {
112 // Find all 'return', 'resume', and 'unwind' instructions.
113 while (StateBB != StateE) {
114 BasicBlock *CurBB = StateBB++;
116 // Branches and invokes do not escape, only unwind, resume, and return
118 TerminatorInst *TI = CurBB->getTerminator();
119 if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI) &&
120 !isa<ResumeInst>(TI))
123 Builder.SetInsertPoint(TI->getParent(), TI);
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())
143 // Create a cleanup block.
144 LLVMContext &C = F.getContext();
145 BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F);
146 Type *ExnTy = StructType::get(Type::getInt8PtrTy(C),
147 Type::getInt32Ty(C), NULL);
148 // FIXME: Assuming the C++ personality function probably isn't the best
149 // thing in the world.
152 getOrInsertFunction("__gxx_personality_v0",
153 FunctionType::get(Type::getInt32Ty(C), true));
154 LandingPadInst *LPad = LandingPadInst::Create(ExnTy, PersFn, 1,
157 LPad->setCleanup(true);
158 ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB);
160 // Transform the 'call' instructions into 'invoke's branching to the
161 // cleanup block. Go in reverse order to make prettier BB names.
162 SmallVector<Value*,16> Args;
163 for (unsigned I = Calls.size(); I != 0; ) {
164 CallInst *CI = cast<CallInst>(Calls[--I]);
166 // Split the basic block containing the function call.
167 BasicBlock *CallBB = CI->getParent();
169 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
171 // Remove the unconditional branch inserted at the end of CallBB.
172 CallBB->getInstList().pop_back();
173 NewBB->getInstList().remove(CI);
175 // Create a new invoke instruction.
178 Args.append(CS.arg_begin(), CS.arg_end());
180 InvokeInst *II = InvokeInst::Create(CI->getCalledValue(),
182 Args, CI->getName(), CallBB);
183 II->setCallingConv(CI->getCallingConv());
184 II->setAttributes(CI->getAttributes());
185 CI->replaceAllUsesWith(II);
189 Builder.SetInsertPoint(RI->getParent(), RI);
196 // -----------------------------------------------------------------------------
198 void llvm::linkShadowStackGC() { }
200 ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
205 Constant *ShadowStackGC::GetFrameMap(Function &F) {
206 // doInitialization creates the abstract type of this value.
207 Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
209 // Truncate the ShadowStackDescriptor if some metadata is null.
210 unsigned NumMeta = 0;
211 SmallVector<Constant*, 16> Metadata;
212 for (unsigned I = 0; I != Roots.size(); ++I) {
213 Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
214 if (!C->isNullValue())
216 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
218 Metadata.resize(NumMeta);
220 Type *Int32Ty = Type::getInt32Ty(F.getContext());
222 Constant *BaseElts[] = {
223 ConstantInt::get(Int32Ty, Roots.size(), false),
224 ConstantInt::get(Int32Ty, NumMeta, false),
227 Constant *DescriptorElts[] = {
228 ConstantStruct::get(FrameMapTy, BaseElts),
229 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)
232 Type *EltTys[] = { DescriptorElts[0]->getType(),DescriptorElts[1]->getType()};
233 StructType *STy = StructType::create(EltTys, "gc_map."+utostr(NumMeta));
235 Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
237 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
238 // that, short of multithreaded LLVM, it should be safe; all that is
239 // necessary is that a simple Module::iterator loop not be invalidated.
240 // Appending to the GlobalVariable list is safe in that sense.
242 // All of the output passes emit globals last. The ExecutionEngine
243 // explicitly supports adding globals to the module after
246 // Still, if it isn't deemed acceptable, then this transformation needs
247 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
248 // (which uses a FunctionPassManager (which segfaults (not asserts) if
249 // provided a ModulePass))).
250 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
251 GlobalVariable::InternalLinkage,
252 FrameMap, "__gc_" + F.getName());
254 Constant *GEPIndices[2] = {
255 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
256 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)
258 return ConstantExpr::getGetElementPtr(GV, GEPIndices);
261 Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
262 // doInitialization creates the generic version of this type.
263 std::vector<Type*> EltTys;
264 EltTys.push_back(StackEntryTy);
265 for (size_t I = 0; I != Roots.size(); I++)
266 EltTys.push_back(Roots[I].second->getAllocatedType());
268 return StructType::create(EltTys, "gc_stackentry."+F.getName().str());
271 /// doInitialization - If this module uses the GC intrinsics, find them now. If
273 bool ShadowStackGC::initializeCustomLowering(Module &M) {
275 // int32_t NumRoots; // Number of roots in stack frame.
276 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
277 // void *Meta[]; // May be absent for roots without metadata.
279 std::vector<Type*> EltTys;
280 // 32 bits is ok up to a 32GB stack frame. :)
281 EltTys.push_back(Type::getInt32Ty(M.getContext()));
282 // Specifies length of variable length array.
283 EltTys.push_back(Type::getInt32Ty(M.getContext()));
284 FrameMapTy = StructType::create(EltTys, "gc_map");
285 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
287 // struct StackEntry {
288 // ShadowStackEntry *Next; // Caller's stack entry.
289 // FrameMap *Map; // Pointer to constant FrameMap.
290 // void *Roots[]; // Stack roots (in-place array, so we pretend).
293 StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
296 EltTys.push_back(PointerType::getUnqual(StackEntryTy));
297 EltTys.push_back(FrameMapPtrTy);
298 StackEntryTy->setBody(EltTys);
299 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
301 // Get the root chain if it already exists.
302 Head = M.getGlobalVariable("llvm_gc_root_chain");
304 // If the root chain does not exist, insert a new one with linkonce
306 Head = new GlobalVariable(M, StackEntryPtrTy, false,
307 GlobalValue::LinkOnceAnyLinkage,
308 Constant::getNullValue(StackEntryPtrTy),
309 "llvm_gc_root_chain");
310 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
311 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
312 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
318 bool ShadowStackGC::IsNullValue(Value *V) {
319 if (Constant *C = dyn_cast<Constant>(V))
320 return C->isNullValue();
324 void ShadowStackGC::CollectRoots(Function &F) {
325 // FIXME: Account for original alignment. Could fragment the root array.
326 // Approach 1: Null initialize empty slots at runtime. Yuck.
327 // Approach 2: Emit a map of the array instead of just a count.
329 assert(Roots.empty() && "Not cleaned up?");
331 SmallVector<std::pair<CallInst*, AllocaInst*>, 16> MetaRoots;
333 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
334 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
335 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
336 if (Function *F = CI->getCalledFunction())
337 if (F->getIntrinsicID() == Intrinsic::gcroot) {
338 std::pair<CallInst*, AllocaInst*> Pair = std::make_pair(
339 CI, cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
340 if (IsNullValue(CI->getArgOperand(1)))
341 Roots.push_back(Pair);
343 MetaRoots.push_back(Pair);
346 // Number roots with metadata (usually empty) at the beginning, so that the
347 // FrameMap::Meta array can be elided.
348 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
352 ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
353 int Idx, int Idx2, const char *Name) {
354 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
355 ConstantInt::get(Type::getInt32Ty(Context), Idx),
356 ConstantInt::get(Type::getInt32Ty(Context), Idx2) };
357 Value* Val = B.CreateGEP(BasePtr, Indices, Name);
359 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
361 return dyn_cast<GetElementPtrInst>(Val);
365 ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
366 int Idx, const char *Name) {
367 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
368 ConstantInt::get(Type::getInt32Ty(Context), Idx) };
369 Value *Val = B.CreateGEP(BasePtr, Indices, Name);
371 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
373 return dyn_cast<GetElementPtrInst>(Val);
376 /// runOnFunction - Insert code to maintain the shadow stack.
377 bool ShadowStackGC::performCustomLowering(Function &F) {
378 LLVMContext &Context = F.getContext();
380 // Find calls to llvm.gcroot.
383 // If there are no roots in this function, then there is no need to add a
384 // stack map entry for it.
388 // Build the constant map and figure the type of the shadow stack entry.
389 Value *FrameMap = GetFrameMap(F);
390 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
392 // Build the shadow stack entry at the very start of the function.
393 BasicBlock::iterator IP = F.getEntryBlock().begin();
394 IRBuilder<> AtEntry(IP->getParent(), IP);
396 Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
399 while (isa<AllocaInst>(IP)) ++IP;
400 AtEntry.SetInsertPoint(IP->getParent(), IP);
402 // Initialize the map pointer and load the current head of the shadow stack.
403 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
404 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, StackEntry,
406 AtEntry.CreateStore(FrameMap, EntryMapPtr);
408 // After all the allocas...
409 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
410 // For each root, find the corresponding slot in the aggregate...
411 Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root");
413 // And use it in lieu of the alloca.
414 AllocaInst *OriginalAlloca = Roots[I].second;
415 SlotPtr->takeName(OriginalAlloca);
416 OriginalAlloca->replaceAllUsesWith(SlotPtr);
419 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
420 // really necessary (the collector would never see the intermediate state at
421 // runtime), but it's nicer not to push the half-initialized entry onto the
423 while (isa<StoreInst>(IP)) ++IP;
424 AtEntry.SetInsertPoint(IP->getParent(), IP);
426 // Push the entry onto the shadow stack.
427 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry,
428 StackEntry,0,0,"gc_frame.next");
429 Instruction *NewHeadVal = CreateGEP(Context, AtEntry,
430 StackEntry, 0, "gc_newhead");
431 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
432 AtEntry.CreateStore(NewHeadVal, Head);
434 // For each instruction that escapes...
435 EscapeEnumerator EE(F, "gc_cleanup");
436 while (IRBuilder<> *AtExit = EE.Next()) {
437 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
438 // AtEntry, since that would make the value live for the entire function.
439 Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0,
441 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
442 AtExit->CreateStore(SavedHead, Head);
445 // Delete the original allocas (which are no longer used) and the intrinsic
446 // calls (which are no longer valid). Doing this last avoids invalidating
448 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
449 Roots[I].first->eraseFromParent();
450 Roots[I].second->eraseFromParent();