1193323Sed//===-- ShadowStackGC.cpp - GC support for uncooperative targets ----------===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This file implements lowering for the llvm.gc* intrinsics for targets that do 11193323Sed// not natively support them (which includes the C backend). Note that the code 12193323Sed// generated is not quite as efficient as algorithms which generate stack maps 13193323Sed// to identify roots. 14193323Sed// 15193323Sed// This pass implements the code transformation described in this paper: 16193323Sed// "Accurate Garbage Collection in an Uncooperative Environment" 17193323Sed// Fergus Henderson, ISMM, 2002 18193323Sed// 19193323Sed// In runtime/GC/SemiSpace.cpp is a prototype runtime which is compatible with 20193323Sed// ShadowStackGC. 21193323Sed// 22193323Sed// In order to support this particular transformation, all stack roots are 23193323Sed// coallocated in the stack. This allows a fully target-independent stack map 24193323Sed// while introducing only minor runtime overhead. 25193323Sed// 26193323Sed//===----------------------------------------------------------------------===// 27193323Sed 28193323Sed#define DEBUG_TYPE "shadowstackgc" 29249423Sdim#include "llvm/CodeGen/GCs.h" 30193323Sed#include "llvm/ADT/StringExtras.h" 31193323Sed#include "llvm/CodeGen/GCStrategy.h" 32249423Sdim#include "llvm/IR/IRBuilder.h" 33249423Sdim#include "llvm/IR/IntrinsicInst.h" 34249423Sdim#include "llvm/IR/Module.h" 35210299Sed#include "llvm/Support/CallSite.h" 36193323Sed 37193323Sedusing namespace llvm; 38193323Sed 39193323Sednamespace { 40193323Sed 41198892Srdivacky class ShadowStackGC : public GCStrategy { 42193323Sed /// RootChain - This is the global linked-list that contains the chain of GC 43193323Sed /// roots. 44193323Sed GlobalVariable *Head; 45193323Sed 46193323Sed /// StackEntryTy - Abstract type of a link in the shadow stack. 47193323Sed /// 48224145Sdim StructType *StackEntryTy; 49224145Sdim StructType *FrameMapTy; 50193323Sed 51193323Sed /// Roots - GC roots in the current function. Each is a pair of the 52193323Sed /// intrinsic call and its corresponding alloca. 53193323Sed std::vector<std::pair<CallInst*,AllocaInst*> > Roots; 54193323Sed 55193323Sed public: 56193323Sed ShadowStackGC(); 57193323Sed 58193323Sed bool initializeCustomLowering(Module &M); 59193323Sed bool performCustomLowering(Function &F); 60193323Sed 61193323Sed private: 62193323Sed bool IsNullValue(Value *V); 63193323Sed Constant *GetFrameMap(Function &F); 64226633Sdim Type* GetConcreteStackEntryType(Function &F); 65193323Sed void CollectRoots(Function &F); 66198090Srdivacky static GetElementPtrInst *CreateGEP(LLVMContext &Context, 67198090Srdivacky IRBuilder<> &B, Value *BasePtr, 68193323Sed int Idx1, const char *Name); 69198090Srdivacky static GetElementPtrInst *CreateGEP(LLVMContext &Context, 70198090Srdivacky IRBuilder<> &B, Value *BasePtr, 71193323Sed int Idx1, int Idx2, const char *Name); 72193323Sed }; 73193323Sed 74193323Sed} 75193323Sed 76193323Sedstatic GCRegistry::Add<ShadowStackGC> 77193323SedX("shadow-stack", "Very portable GC for uncooperative code generators"); 78193323Sed 79193323Sednamespace { 80193323Sed /// EscapeEnumerator - This is a little algorithm to find all escape points 81193323Sed /// from a function so that "finally"-style code can be inserted. In addition 82193323Sed /// to finding the existing return and unwind instructions, it also (if 83193323Sed /// necessary) transforms any call instructions into invokes and sends them to 84193323Sed /// a landing pad. 85193323Sed /// 86193323Sed /// It's wrapped up in a state machine using the same transform C# uses for 87193323Sed /// 'yield return' enumerators, This transform allows it to be non-allocating. 88198892Srdivacky class EscapeEnumerator { 89193323Sed Function &F; 90193323Sed const char *CleanupBBName; 91193323Sed 92193323Sed // State. 93193323Sed int State; 94193323Sed Function::iterator StateBB, StateE; 95193323Sed IRBuilder<> Builder; 96193323Sed 97193323Sed public: 98193323Sed EscapeEnumerator(Function &F, const char *N = "cleanup") 99198090Srdivacky : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {} 100193323Sed 101193323Sed IRBuilder<> *Next() { 102193323Sed switch (State) { 103193323Sed default: 104193323Sed return 0; 105193323Sed 106193323Sed case 0: 107193323Sed StateBB = F.begin(); 108193323Sed StateE = F.end(); 109193323Sed State = 1; 110193323Sed 111193323Sed case 1: 112226633Sdim // Find all 'return', 'resume', and 'unwind' instructions. 113193323Sed while (StateBB != StateE) { 114193323Sed BasicBlock *CurBB = StateBB++; 115193323Sed 116226633Sdim // Branches and invokes do not escape, only unwind, resume, and return 117226633Sdim // do. 118193323Sed TerminatorInst *TI = CurBB->getTerminator(); 119234353Sdim if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI)) 120193323Sed continue; 121193323Sed 122193323Sed Builder.SetInsertPoint(TI->getParent(), TI); 123193323Sed return &Builder; 124193323Sed } 125193323Sed 126193323Sed State = 2; 127193323Sed 128193323Sed // Find all 'call' instructions. 129193323Sed SmallVector<Instruction*,16> Calls; 130193323Sed for (Function::iterator BB = F.begin(), 131193323Sed E = F.end(); BB != E; ++BB) 132193323Sed for (BasicBlock::iterator II = BB->begin(), 133193323Sed EE = BB->end(); II != EE; ++II) 134193323Sed if (CallInst *CI = dyn_cast<CallInst>(II)) 135193323Sed if (!CI->getCalledFunction() || 136193323Sed !CI->getCalledFunction()->getIntrinsicID()) 137193323Sed Calls.push_back(CI); 138193323Sed 139193323Sed if (Calls.empty()) 140193323Sed return 0; 141193323Sed 142193323Sed // Create a cleanup block. 143226633Sdim LLVMContext &C = F.getContext(); 144226633Sdim BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F); 145226633Sdim Type *ExnTy = StructType::get(Type::getInt8PtrTy(C), 146226633Sdim Type::getInt32Ty(C), NULL); 147226633Sdim Constant *PersFn = 148226633Sdim F.getParent()-> 149226633Sdim getOrInsertFunction("__gcc_personality_v0", 150226633Sdim FunctionType::get(Type::getInt32Ty(C), true)); 151226633Sdim LandingPadInst *LPad = LandingPadInst::Create(ExnTy, PersFn, 1, 152226633Sdim "cleanup.lpad", 153226633Sdim CleanupBB); 154226633Sdim LPad->setCleanup(true); 155226633Sdim ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB); 156193323Sed 157193323Sed // Transform the 'call' instructions into 'invoke's branching to the 158193323Sed // cleanup block. Go in reverse order to make prettier BB names. 159193323Sed SmallVector<Value*,16> Args; 160193323Sed for (unsigned I = Calls.size(); I != 0; ) { 161193323Sed CallInst *CI = cast<CallInst>(Calls[--I]); 162193323Sed 163193323Sed // Split the basic block containing the function call. 164193323Sed BasicBlock *CallBB = CI->getParent(); 165193323Sed BasicBlock *NewBB = 166193323Sed CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont"); 167193323Sed 168193323Sed // Remove the unconditional branch inserted at the end of CallBB. 169193323Sed CallBB->getInstList().pop_back(); 170193323Sed NewBB->getInstList().remove(CI); 171193323Sed 172193323Sed // Create a new invoke instruction. 173193323Sed Args.clear(); 174210299Sed CallSite CS(CI); 175210299Sed Args.append(CS.arg_begin(), CS.arg_end()); 176193323Sed 177207618Srdivacky InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), 178193323Sed NewBB, CleanupBB, 179224145Sdim Args, CI->getName(), CallBB); 180193323Sed II->setCallingConv(CI->getCallingConv()); 181193323Sed II->setAttributes(CI->getAttributes()); 182193323Sed CI->replaceAllUsesWith(II); 183193323Sed delete CI; 184193323Sed } 185193323Sed 186226633Sdim Builder.SetInsertPoint(RI->getParent(), RI); 187193323Sed return &Builder; 188193323Sed } 189193323Sed } 190193323Sed }; 191193323Sed} 192193323Sed 193193323Sed// ----------------------------------------------------------------------------- 194193323Sed 195193323Sedvoid llvm::linkShadowStackGC() { } 196193323Sed 197193323SedShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) { 198193323Sed InitRoots = true; 199193323Sed CustomRoots = true; 200193323Sed} 201193323Sed 202193323SedConstant *ShadowStackGC::GetFrameMap(Function &F) { 203193323Sed // doInitialization creates the abstract type of this value. 204226633Sdim Type *VoidPtr = Type::getInt8PtrTy(F.getContext()); 205193323Sed 206193323Sed // Truncate the ShadowStackDescriptor if some metadata is null. 207193323Sed unsigned NumMeta = 0; 208224145Sdim SmallVector<Constant*, 16> Metadata; 209193323Sed for (unsigned I = 0; I != Roots.size(); ++I) { 210210299Sed Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1)); 211193323Sed if (!C->isNullValue()) 212193323Sed NumMeta = I + 1; 213193323Sed Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr)); 214193323Sed } 215224145Sdim Metadata.resize(NumMeta); 216193323Sed 217226633Sdim Type *Int32Ty = Type::getInt32Ty(F.getContext()); 218224145Sdim 219193323Sed Constant *BaseElts[] = { 220224145Sdim ConstantInt::get(Int32Ty, Roots.size(), false), 221224145Sdim ConstantInt::get(Int32Ty, NumMeta, false), 222193323Sed }; 223193323Sed 224193323Sed Constant *DescriptorElts[] = { 225224145Sdim ConstantStruct::get(FrameMapTy, BaseElts), 226224145Sdim ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata) 227193323Sed }; 228193323Sed 229224145Sdim Type *EltTys[] = { DescriptorElts[0]->getType(),DescriptorElts[1]->getType()}; 230226633Sdim StructType *STy = StructType::create(EltTys, "gc_map."+utostr(NumMeta)); 231224145Sdim 232224145Sdim Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts); 233193323Sed 234193323Sed // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems 235193323Sed // that, short of multithreaded LLVM, it should be safe; all that is 236193323Sed // necessary is that a simple Module::iterator loop not be invalidated. 237193323Sed // Appending to the GlobalVariable list is safe in that sense. 238193323Sed // 239193323Sed // All of the output passes emit globals last. The ExecutionEngine 240193323Sed // explicitly supports adding globals to the module after 241193323Sed // initialization. 242193323Sed // 243193323Sed // Still, if it isn't deemed acceptable, then this transformation needs 244193323Sed // to be a ModulePass (which means it cannot be in the 'llc' pipeline 245193323Sed // (which uses a FunctionPassManager (which segfaults (not asserts) if 246193323Sed // provided a ModulePass))). 247198090Srdivacky Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true, 248193323Sed GlobalVariable::InternalLinkage, 249198090Srdivacky FrameMap, "__gc_" + F.getName()); 250193323Sed 251198090Srdivacky Constant *GEPIndices[2] = { 252198090Srdivacky ConstantInt::get(Type::getInt32Ty(F.getContext()), 0), 253198090Srdivacky ConstantInt::get(Type::getInt32Ty(F.getContext()), 0) 254198090Srdivacky }; 255226633Sdim return ConstantExpr::getGetElementPtr(GV, GEPIndices); 256193323Sed} 257193323Sed 258226633SdimType* ShadowStackGC::GetConcreteStackEntryType(Function &F) { 259193323Sed // doInitialization creates the generic version of this type. 260224145Sdim std::vector<Type*> EltTys; 261193323Sed EltTys.push_back(StackEntryTy); 262193323Sed for (size_t I = 0; I != Roots.size(); I++) 263193323Sed EltTys.push_back(Roots[I].second->getAllocatedType()); 264224145Sdim 265226633Sdim return StructType::create(EltTys, "gc_stackentry."+F.getName().str()); 266193323Sed} 267193323Sed 268193323Sed/// doInitialization - If this module uses the GC intrinsics, find them now. If 269193323Sed/// not, exit fast. 270193323Sedbool ShadowStackGC::initializeCustomLowering(Module &M) { 271193323Sed // struct FrameMap { 272193323Sed // int32_t NumRoots; // Number of roots in stack frame. 273193323Sed // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots. 274193323Sed // void *Meta[]; // May be absent for roots without metadata. 275193323Sed // }; 276224145Sdim std::vector<Type*> EltTys; 277198090Srdivacky // 32 bits is ok up to a 32GB stack frame. :) 278198090Srdivacky EltTys.push_back(Type::getInt32Ty(M.getContext())); 279198090Srdivacky // Specifies length of variable length array. 280198090Srdivacky EltTys.push_back(Type::getInt32Ty(M.getContext())); 281226633Sdim FrameMapTy = StructType::create(EltTys, "gc_map"); 282193323Sed PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy); 283193323Sed 284193323Sed // struct StackEntry { 285193323Sed // ShadowStackEntry *Next; // Caller's stack entry. 286193323Sed // FrameMap *Map; // Pointer to constant FrameMap. 287193323Sed // void *Roots[]; // Stack roots (in-place array, so we pretend). 288193323Sed // }; 289224145Sdim 290226633Sdim StackEntryTy = StructType::create(M.getContext(), "gc_stackentry"); 291224145Sdim 292193323Sed EltTys.clear(); 293224145Sdim EltTys.push_back(PointerType::getUnqual(StackEntryTy)); 294193323Sed EltTys.push_back(FrameMapPtrTy); 295224145Sdim StackEntryTy->setBody(EltTys); 296226633Sdim PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy); 297193323Sed 298193323Sed // Get the root chain if it already exists. 299193323Sed Head = M.getGlobalVariable("llvm_gc_root_chain"); 300193323Sed if (!Head) { 301193323Sed // If the root chain does not exist, insert a new one with linkonce 302193323Sed // linkage! 303198090Srdivacky Head = new GlobalVariable(M, StackEntryPtrTy, false, 304193323Sed GlobalValue::LinkOnceAnyLinkage, 305193323Sed Constant::getNullValue(StackEntryPtrTy), 306198090Srdivacky "llvm_gc_root_chain"); 307193323Sed } else if (Head->hasExternalLinkage() && Head->isDeclaration()) { 308193323Sed Head->setInitializer(Constant::getNullValue(StackEntryPtrTy)); 309193323Sed Head->setLinkage(GlobalValue::LinkOnceAnyLinkage); 310193323Sed } 311193323Sed 312193323Sed return true; 313193323Sed} 314193323Sed 315193323Sedbool ShadowStackGC::IsNullValue(Value *V) { 316193323Sed if (Constant *C = dyn_cast<Constant>(V)) 317193323Sed return C->isNullValue(); 318193323Sed return false; 319193323Sed} 320193323Sed 321193323Sedvoid ShadowStackGC::CollectRoots(Function &F) { 322193323Sed // FIXME: Account for original alignment. Could fragment the root array. 323193323Sed // Approach 1: Null initialize empty slots at runtime. Yuck. 324193323Sed // Approach 2: Emit a map of the array instead of just a count. 325193323Sed 326193323Sed assert(Roots.empty() && "Not cleaned up?"); 327193323Sed 328210299Sed SmallVector<std::pair<CallInst*, AllocaInst*>, 16> MetaRoots; 329193323Sed 330193323Sed for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 331193323Sed for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) 332193323Sed if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) 333193323Sed if (Function *F = CI->getCalledFunction()) 334193323Sed if (F->getIntrinsicID() == Intrinsic::gcroot) { 335210299Sed std::pair<CallInst*, AllocaInst*> Pair = std::make_pair( 336210299Sed CI, cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts())); 337210299Sed if (IsNullValue(CI->getArgOperand(1))) 338193323Sed Roots.push_back(Pair); 339193323Sed else 340193323Sed MetaRoots.push_back(Pair); 341193323Sed } 342193323Sed 343193323Sed // Number roots with metadata (usually empty) at the beginning, so that the 344193323Sed // FrameMap::Meta array can be elided. 345193323Sed Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end()); 346193323Sed} 347193323Sed 348193323SedGetElementPtrInst * 349198090SrdivackyShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr, 350193323Sed int Idx, int Idx2, const char *Name) { 351198090Srdivacky Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0), 352198090Srdivacky ConstantInt::get(Type::getInt32Ty(Context), Idx), 353198090Srdivacky ConstantInt::get(Type::getInt32Ty(Context), Idx2) }; 354226633Sdim Value* Val = B.CreateGEP(BasePtr, Indices, Name); 355193323Sed 356193323Sed assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant"); 357193323Sed 358193323Sed return dyn_cast<GetElementPtrInst>(Val); 359193323Sed} 360193323Sed 361193323SedGetElementPtrInst * 362198090SrdivackyShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr, 363193323Sed int Idx, const char *Name) { 364198090Srdivacky Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0), 365198090Srdivacky ConstantInt::get(Type::getInt32Ty(Context), Idx) }; 366226633Sdim Value *Val = B.CreateGEP(BasePtr, Indices, Name); 367193323Sed 368193323Sed assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant"); 369193323Sed 370193323Sed return dyn_cast<GetElementPtrInst>(Val); 371193323Sed} 372193323Sed 373193323Sed/// runOnFunction - Insert code to maintain the shadow stack. 374193323Sedbool ShadowStackGC::performCustomLowering(Function &F) { 375198090Srdivacky LLVMContext &Context = F.getContext(); 376198090Srdivacky 377193323Sed // Find calls to llvm.gcroot. 378193323Sed CollectRoots(F); 379193323Sed 380193323Sed // If there are no roots in this function, then there is no need to add a 381193323Sed // stack map entry for it. 382193323Sed if (Roots.empty()) 383193323Sed return false; 384193323Sed 385193323Sed // Build the constant map and figure the type of the shadow stack entry. 386193323Sed Value *FrameMap = GetFrameMap(F); 387226633Sdim Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F); 388193323Sed 389193323Sed // Build the shadow stack entry at the very start of the function. 390193323Sed BasicBlock::iterator IP = F.getEntryBlock().begin(); 391193323Sed IRBuilder<> AtEntry(IP->getParent(), IP); 392193323Sed 393193323Sed Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0, 394193323Sed "gc_frame"); 395193323Sed 396193323Sed while (isa<AllocaInst>(IP)) ++IP; 397193323Sed AtEntry.SetInsertPoint(IP->getParent(), IP); 398193323Sed 399193323Sed // Initialize the map pointer and load the current head of the shadow stack. 400193323Sed Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead"); 401198090Srdivacky Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, StackEntry, 402198090Srdivacky 0,1,"gc_frame.map"); 403224145Sdim AtEntry.CreateStore(FrameMap, EntryMapPtr); 404193323Sed 405193323Sed // After all the allocas... 406193323Sed for (unsigned I = 0, E = Roots.size(); I != E; ++I) { 407193323Sed // For each root, find the corresponding slot in the aggregate... 408198090Srdivacky Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root"); 409193323Sed 410193323Sed // And use it in lieu of the alloca. 411193323Sed AllocaInst *OriginalAlloca = Roots[I].second; 412193323Sed SlotPtr->takeName(OriginalAlloca); 413193323Sed OriginalAlloca->replaceAllUsesWith(SlotPtr); 414193323Sed } 415193323Sed 416193323Sed // Move past the original stores inserted by GCStrategy::InitRoots. This isn't 417193323Sed // really necessary (the collector would never see the intermediate state at 418193323Sed // runtime), but it's nicer not to push the half-initialized entry onto the 419193323Sed // shadow stack. 420193323Sed while (isa<StoreInst>(IP)) ++IP; 421193323Sed AtEntry.SetInsertPoint(IP->getParent(), IP); 422193323Sed 423193323Sed // Push the entry onto the shadow stack. 424198090Srdivacky Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, 425198090Srdivacky StackEntry,0,0,"gc_frame.next"); 426198090Srdivacky Instruction *NewHeadVal = CreateGEP(Context, AtEntry, 427198090Srdivacky StackEntry, 0, "gc_newhead"); 428198090Srdivacky AtEntry.CreateStore(CurrentHead, EntryNextPtr); 429198090Srdivacky AtEntry.CreateStore(NewHeadVal, Head); 430193323Sed 431193323Sed // For each instruction that escapes... 432193323Sed EscapeEnumerator EE(F, "gc_cleanup"); 433193323Sed while (IRBuilder<> *AtExit = EE.Next()) { 434193323Sed // Pop the entry from the shadow stack. Don't reuse CurrentHead from 435193323Sed // AtEntry, since that would make the value live for the entire function. 436198090Srdivacky Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0, 437193323Sed "gc_frame.next"); 438193323Sed Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead"); 439193323Sed AtExit->CreateStore(SavedHead, Head); 440193323Sed } 441193323Sed 442193323Sed // Delete the original allocas (which are no longer used) and the intrinsic 443193323Sed // calls (which are no longer valid). Doing this last avoids invalidating 444193323Sed // iterators. 445193323Sed for (unsigned I = 0, E = Roots.size(); I != E; ++I) { 446193323Sed Roots[I].first->eraseFromParent(); 447193323Sed Roots[I].second->eraseFromParent(); 448193323Sed } 449193323Sed 450193323Sed Roots.clear(); 451193323Sed return true; 452193323Sed} 453