X-Git-Url: http://plrg.eecs.uci.edu/git/?a=blobdiff_plain;f=lib%2FCodeGen%2FShadowStackGC.cpp;h=f7c64dac61246ed0d58957d8493c25a6bfc4d9bd;hb=4a183c6b87717e02487ac32a01fdf5724c7c3077;hp=efe7c0a6a9d4bff1f7313629a8c6f00ad7a389c3;hpb=3d29df3e8a203b167d8071ea6f805b21db18a5af;p=oota-llvm.git diff --git a/lib/CodeGen/ShadowStackGC.cpp b/lib/CodeGen/ShadowStackGC.cpp index efe7c0a6a9d..f7c64dac612 100644 --- a/lib/CodeGen/ShadowStackGC.cpp +++ b/lib/CodeGen/ShadowStackGC.cpp @@ -25,27 +25,29 @@ // //===----------------------------------------------------------------------===// -#define DEBUG_TYPE "shadowstackgc" #include "llvm/CodeGen/GCs.h" #include "llvm/ADT/StringExtras.h" #include "llvm/CodeGen/GCStrategy.h" -#include "llvm/IntrinsicInst.h" -#include "llvm/Module.h" -#include "llvm/Support/Compiler.h" -#include "llvm/Support/IRBuilder.h" +#include "llvm/IR/CallSite.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/Module.h" using namespace llvm; +#define DEBUG_TYPE "shadowstackgc" + namespace { - class VISIBILITY_HIDDEN ShadowStackGC : public GCStrategy { + class ShadowStackGC : public GCStrategy { /// RootChain - This is the global linked-list that contains the chain of GC /// roots. GlobalVariable *Head; /// StackEntryTy - Abstract type of a link in the shadow stack. /// - const StructType *StackEntryTy; + StructType *StackEntryTy; + StructType *FrameMapTy; /// Roots - GC roots in the current function. Each is a pair of the /// intrinsic call and its corresponding alloca. @@ -54,17 +56,19 @@ namespace { public: ShadowStackGC(); - bool initializeCustomLowering(Module &M); - bool performCustomLowering(Function &F); + bool initializeCustomLowering(Module &M) override; + bool performCustomLowering(Function &F) override; private: bool IsNullValue(Value *V); Constant *GetFrameMap(Function &F); - const Type* GetConcreteStackEntryType(Function &F); + Type* GetConcreteStackEntryType(Function &F); void CollectRoots(Function &F); - static GetElementPtrInst *CreateGEP(IRBuilder<> &B, Value *BasePtr, + static GetElementPtrInst *CreateGEP(LLVMContext &Context, + IRBuilder<> &B, Value *BasePtr, int Idx1, const char *Name); - static GetElementPtrInst *CreateGEP(IRBuilder<> &B, Value *BasePtr, + static GetElementPtrInst *CreateGEP(LLVMContext &Context, + IRBuilder<> &B, Value *BasePtr, int Idx1, int Idx2, const char *Name); }; @@ -82,7 +86,7 @@ namespace { /// /// It's wrapped up in a state machine using the same transform C# uses for /// 'yield return' enumerators, This transform allows it to be non-allocating. - class VISIBILITY_HIDDEN EscapeEnumerator { + class EscapeEnumerator { Function &F; const char *CleanupBBName; @@ -93,12 +97,12 @@ namespace { public: EscapeEnumerator(Function &F, const char *N = "cleanup") - : F(F), CleanupBBName(N), State(0) {} + : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {} IRBuilder<> *Next() { switch (State) { default: - return 0; + return nullptr; case 0: StateBB = F.begin(); @@ -106,13 +110,14 @@ namespace { State = 1; case 1: - // Find all 'return' and 'unwind' instructions. + // Find all 'return', 'resume', and 'unwind' instructions. while (StateBB != StateE) { BasicBlock *CurBB = StateBB++; - // Branches and invokes do not escape, only unwind and return do. + // Branches and invokes do not escape, only unwind, resume, and return + // do. TerminatorInst *TI = CurBB->getTerminator(); - if (!isa(TI) && !isa(TI)) + if (!isa(TI) && !isa(TI)) continue; Builder.SetInsertPoint(TI->getParent(), TI); @@ -133,11 +138,22 @@ namespace { Calls.push_back(CI); if (Calls.empty()) - return 0; + return nullptr; // Create a cleanup block. - BasicBlock *CleanupBB = BasicBlock::Create(CleanupBBName, &F); - UnwindInst *UI = new UnwindInst(CleanupBB); + LLVMContext &C = F.getContext(); + BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F); + Type *ExnTy = StructType::get(Type::getInt8PtrTy(C), + Type::getInt32Ty(C), NULL); + Constant *PersFn = + F.getParent()-> + getOrInsertFunction("__gcc_personality_v0", + FunctionType::get(Type::getInt32Ty(C), true)); + LandingPadInst *LPad = LandingPadInst::Create(ExnTy, PersFn, 1, + "cleanup.lpad", + CleanupBB); + LPad->setCleanup(true); + ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB); // Transform the 'call' instructions into 'invoke's branching to the // cleanup block. Go in reverse order to make prettier BB names. @@ -156,19 +172,19 @@ namespace { // Create a new invoke instruction. Args.clear(); - Args.append(CI->op_begin() + 1, CI->op_end()); + CallSite CS(CI); + Args.append(CS.arg_begin(), CS.arg_end()); - InvokeInst *II = InvokeInst::Create(CI->getOperand(0), + InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), NewBB, CleanupBB, - Args.begin(), Args.end(), - CI->getName(), CallBB); + Args, CI->getName(), CallBB); II->setCallingConv(CI->getCallingConv()); II->setAttributes(CI->getAttributes()); CI->replaceAllUsesWith(II); delete CI; } - Builder.SetInsertPoint(UI->getParent(), UI); + Builder.SetInsertPoint(RI->getParent(), RI); return &Builder; } } @@ -179,42 +195,42 @@ namespace { void llvm::linkShadowStackGC() { } -ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) { +ShadowStackGC::ShadowStackGC() : Head(nullptr), StackEntryTy(nullptr) { InitRoots = true; CustomRoots = true; } Constant *ShadowStackGC::GetFrameMap(Function &F) { // doInitialization creates the abstract type of this value. - - Type *VoidPtr = PointerType::getUnqual(Type::Int8Ty); + Type *VoidPtr = Type::getInt8PtrTy(F.getContext()); // Truncate the ShadowStackDescriptor if some metadata is null. unsigned NumMeta = 0; - SmallVector Metadata; + SmallVector Metadata; for (unsigned I = 0; I != Roots.size(); ++I) { - Constant *C = cast(Roots[I].first->getOperand(2)); + Constant *C = cast(Roots[I].first->getArgOperand(1)); if (!C->isNullValue()) NumMeta = I + 1; Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr)); } + Metadata.resize(NumMeta); + Type *Int32Ty = Type::getInt32Ty(F.getContext()); + Constant *BaseElts[] = { - ConstantInt::get(Type::Int32Ty, Roots.size(), false), - ConstantInt::get(Type::Int32Ty, NumMeta, false), + ConstantInt::get(Int32Ty, Roots.size(), false), + ConstantInt::get(Int32Ty, NumMeta, false), }; Constant *DescriptorElts[] = { - ConstantStruct::get(BaseElts, 2), - ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), - Metadata.begin(), NumMeta) + ConstantStruct::get(FrameMapTy, BaseElts), + ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata) }; - Constant *FrameMap = ConstantStruct::get(DescriptorElts, 2); - - std::string TypeName("gc_map."); - TypeName += utostr(NumMeta); - F.getParent()->addTypeName(TypeName, FrameMap->getType()); + Type *EltTys[] = { DescriptorElts[0]->getType(),DescriptorElts[1]->getType()}; + StructType *STy = StructType::create(EltTys, "gc_map."+utostr(NumMeta)); + + Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts); // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems // that, short of multithreaded LLVM, it should be safe; all that is @@ -229,29 +245,25 @@ Constant *ShadowStackGC::GetFrameMap(Function &F) { // to be a ModulePass (which means it cannot be in the 'llc' pipeline // (which uses a FunctionPassManager (which segfaults (not asserts) if // provided a ModulePass))). - Constant *GV = new GlobalVariable(*F.getContext(), FrameMap->getType(), true, + Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true, GlobalVariable::InternalLinkage, - FrameMap, "__gc_" + F.getName(), - F.getParent()); + FrameMap, "__gc_" + F.getName()); - Constant *GEPIndices[2] = { ConstantInt::get(Type::Int32Ty, 0), - ConstantInt::get(Type::Int32Ty, 0) }; - return ConstantExpr::getGetElementPtr(GV, GEPIndices, 2); + Constant *GEPIndices[2] = { + ConstantInt::get(Type::getInt32Ty(F.getContext()), 0), + ConstantInt::get(Type::getInt32Ty(F.getContext()), 0) + }; + return ConstantExpr::getGetElementPtr(GV, GEPIndices); } -const Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) { +Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) { // doInitialization creates the generic version of this type. - std::vector EltTys; + std::vector EltTys; EltTys.push_back(StackEntryTy); for (size_t I = 0; I != Roots.size(); I++) EltTys.push_back(Roots[I].second->getAllocatedType()); - Type *Ty = StructType::get(EltTys); - - std::string TypeName("gc_stackentry."); - TypeName += F.getName(); - F.getParent()->addTypeName(TypeName, Ty); - - return Ty; + + return StructType::create(EltTys, "gc_stackentry."+F.getName().str()); } /// doInitialization - If this module uses the GC intrinsics, find them now. If @@ -262,11 +274,12 @@ bool ShadowStackGC::initializeCustomLowering(Module &M) { // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots. // void *Meta[]; // May be absent for roots without metadata. // }; - std::vector EltTys; - EltTys.push_back(Type::Int32Ty); // 32 bits is ok up to a 32GB stack frame. :) - EltTys.push_back(Type::Int32Ty); // Specifies length of variable length array. - StructType *FrameMapTy = StructType::get(EltTys); - M.addTypeName("gc_map", FrameMapTy); + std::vector EltTys; + // 32 bits is ok up to a 32GB stack frame. :) + EltTys.push_back(Type::getInt32Ty(M.getContext())); + // Specifies length of variable length array. + EltTys.push_back(Type::getInt32Ty(M.getContext())); + FrameMapTy = StructType::create(EltTys, "gc_map"); PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy); // struct StackEntry { @@ -274,28 +287,24 @@ bool ShadowStackGC::initializeCustomLowering(Module &M) { // FrameMap *Map; // Pointer to constant FrameMap. // void *Roots[]; // Stack roots (in-place array, so we pretend). // }; - OpaqueType *RecursiveTy = OpaqueType::get(); - + + StackEntryTy = StructType::create(M.getContext(), "gc_stackentry"); + EltTys.clear(); - EltTys.push_back(PointerType::getUnqual(RecursiveTy)); + EltTys.push_back(PointerType::getUnqual(StackEntryTy)); EltTys.push_back(FrameMapPtrTy); - PATypeHolder LinkTyH = StructType::get(EltTys); - - RecursiveTy->refineAbstractTypeTo(LinkTyH.get()); - StackEntryTy = cast(LinkTyH.get()); - const PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy); - M.addTypeName("gc_stackentry", LinkTyH.get()); // FIXME: Is this safe from - // a FunctionPass? + StackEntryTy->setBody(EltTys); + PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy); // Get the root chain if it already exists. Head = M.getGlobalVariable("llvm_gc_root_chain"); if (!Head) { // If the root chain does not exist, insert a new one with linkonce // linkage! - Head = new GlobalVariable(M.getContext(), StackEntryPtrTy, false, + Head = new GlobalVariable(M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage, Constant::getNullValue(StackEntryPtrTy), - "llvm_gc_root_chain", &M); + "llvm_gc_root_chain"); } else if (Head->hasExternalLinkage() && Head->isDeclaration()) { Head->setInitializer(Constant::getNullValue(StackEntryPtrTy)); Head->setLinkage(GlobalValue::LinkOnceAnyLinkage); @@ -317,16 +326,16 @@ void ShadowStackGC::CollectRoots(Function &F) { assert(Roots.empty() && "Not cleaned up?"); - SmallVector,16> MetaRoots; + SmallVector, 16> MetaRoots; for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) if (IntrinsicInst *CI = dyn_cast(II++)) if (Function *F = CI->getCalledFunction()) if (F->getIntrinsicID() == Intrinsic::gcroot) { - std::pair Pair = std::make_pair( - CI, cast(CI->getOperand(1)->stripPointerCasts())); - if (IsNullValue(CI->getOperand(2))) + std::pair Pair = std::make_pair( + CI, cast(CI->getArgOperand(0)->stripPointerCasts())); + if (IsNullValue(CI->getArgOperand(1))) Roots.push_back(Pair); else MetaRoots.push_back(Pair); @@ -338,12 +347,12 @@ void ShadowStackGC::CollectRoots(Function &F) { } GetElementPtrInst * -ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr, +ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr, int Idx, int Idx2, const char *Name) { - Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0), - ConstantInt::get(Type::Int32Ty, Idx), - ConstantInt::get(Type::Int32Ty, Idx2) }; - Value* Val = B.CreateGEP(BasePtr, Indices, Indices + 3, Name); + Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0), + ConstantInt::get(Type::getInt32Ty(Context), Idx), + ConstantInt::get(Type::getInt32Ty(Context), Idx2) }; + Value* Val = B.CreateGEP(BasePtr, Indices, Name); assert(isa(Val) && "Unexpected folded constant"); @@ -351,11 +360,11 @@ ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr, } GetElementPtrInst * -ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr, +ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr, int Idx, const char *Name) { - Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0), - ConstantInt::get(Type::Int32Ty, Idx) }; - Value *Val = B.CreateGEP(BasePtr, Indices, Indices + 2, Name); + Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0), + ConstantInt::get(Type::getInt32Ty(Context), Idx) }; + Value *Val = B.CreateGEP(BasePtr, Indices, Name); assert(isa(Val) && "Unexpected folded constant"); @@ -364,6 +373,8 @@ ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr, /// runOnFunction - Insert code to maintain the shadow stack. bool ShadowStackGC::performCustomLowering(Function &F) { + LLVMContext &Context = F.getContext(); + // Find calls to llvm.gcroot. CollectRoots(F); @@ -374,27 +385,28 @@ bool ShadowStackGC::performCustomLowering(Function &F) { // Build the constant map and figure the type of the shadow stack entry. Value *FrameMap = GetFrameMap(F); - const Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F); + Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F); // Build the shadow stack entry at the very start of the function. BasicBlock::iterator IP = F.getEntryBlock().begin(); IRBuilder<> AtEntry(IP->getParent(), IP); - Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0, - "gc_frame"); + Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, + "gc_frame"); while (isa(IP)) ++IP; AtEntry.SetInsertPoint(IP->getParent(), IP); // Initialize the map pointer and load the current head of the shadow stack. Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead"); - Instruction *EntryMapPtr = CreateGEP(AtEntry, StackEntry,0,1,"gc_frame.map"); - AtEntry.CreateStore(FrameMap, EntryMapPtr); + Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, StackEntry, + 0,1,"gc_frame.map"); + AtEntry.CreateStore(FrameMap, EntryMapPtr); // After all the allocas... for (unsigned I = 0, E = Roots.size(); I != E; ++I) { // For each root, find the corresponding slot in the aggregate... - Value *SlotPtr = CreateGEP(AtEntry, StackEntry, 1 + I, "gc_root"); + Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root"); // And use it in lieu of the alloca. AllocaInst *OriginalAlloca = Roots[I].second; @@ -410,17 +422,19 @@ bool ShadowStackGC::performCustomLowering(Function &F) { AtEntry.SetInsertPoint(IP->getParent(), IP); // Push the entry onto the shadow stack. - Instruction *EntryNextPtr = CreateGEP(AtEntry,StackEntry,0,0,"gc_frame.next"); - Instruction *NewHeadVal = CreateGEP(AtEntry,StackEntry, 0, "gc_newhead"); - AtEntry.CreateStore(CurrentHead, EntryNextPtr); - AtEntry.CreateStore(NewHeadVal, Head); + Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, + StackEntry,0,0,"gc_frame.next"); + Instruction *NewHeadVal = CreateGEP(Context, AtEntry, + StackEntry, 0, "gc_newhead"); + AtEntry.CreateStore(CurrentHead, EntryNextPtr); + AtEntry.CreateStore(NewHeadVal, Head); // For each instruction that escapes... EscapeEnumerator EE(F, "gc_cleanup"); while (IRBuilder<> *AtExit = EE.Next()) { // Pop the entry from the shadow stack. Don't reuse CurrentHead from // AtEntry, since that would make the value live for the entire function. - Instruction *EntryNextPtr2 = CreateGEP(*AtExit, StackEntry, 0, 0, + Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0, "gc_frame.next"); Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead"); AtExit->CreateStore(SavedHead, Head);