10b57cec5SDimitry Andric //===- ShadowStackGCLowering.cpp - Custom lowering for shadow-stack gc ----===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains the custom lowering code required by the shadow-stack GC
100b57cec5SDimitry Andric // strategy.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // This pass implements the code transformation described in this paper:
130b57cec5SDimitry Andric // "Accurate Garbage Collection in an Uncooperative Environment"
140b57cec5SDimitry Andric // Fergus Henderson, ISMM, 2002
150b57cec5SDimitry Andric //
160b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
170b57cec5SDimitry Andric
180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
20*5f7ddb14SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
220b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
230b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
240b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
250b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
26*5f7ddb14SDimitry Andric #include "llvm/IR/Dominators.h"
270b57cec5SDimitry Andric #include "llvm/IR/Function.h"
280b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
290b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
300b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
310b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
320b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
330b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
340b57cec5SDimitry Andric #include "llvm/IR/Module.h"
350b57cec5SDimitry Andric #include "llvm/IR/Type.h"
360b57cec5SDimitry Andric #include "llvm/IR/Value.h"
37480093f4SDimitry Andric #include "llvm/InitializePasses.h"
380b57cec5SDimitry Andric #include "llvm/Pass.h"
390b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
400b57cec5SDimitry Andric #include "llvm/Transforms/Utils/EscapeEnumerator.h"
410b57cec5SDimitry Andric #include <cassert>
420b57cec5SDimitry Andric #include <cstddef>
430b57cec5SDimitry Andric #include <string>
440b57cec5SDimitry Andric #include <utility>
450b57cec5SDimitry Andric #include <vector>
460b57cec5SDimitry Andric
470b57cec5SDimitry Andric using namespace llvm;
480b57cec5SDimitry Andric
490b57cec5SDimitry Andric #define DEBUG_TYPE "shadow-stack-gc-lowering"
500b57cec5SDimitry Andric
510b57cec5SDimitry Andric namespace {
520b57cec5SDimitry Andric
530b57cec5SDimitry Andric class ShadowStackGCLowering : public FunctionPass {
540b57cec5SDimitry Andric /// RootChain - This is the global linked-list that contains the chain of GC
550b57cec5SDimitry Andric /// roots.
560b57cec5SDimitry Andric GlobalVariable *Head = nullptr;
570b57cec5SDimitry Andric
580b57cec5SDimitry Andric /// StackEntryTy - Abstract type of a link in the shadow stack.
590b57cec5SDimitry Andric StructType *StackEntryTy = nullptr;
600b57cec5SDimitry Andric StructType *FrameMapTy = nullptr;
610b57cec5SDimitry Andric
620b57cec5SDimitry Andric /// Roots - GC roots in the current function. Each is a pair of the
630b57cec5SDimitry Andric /// intrinsic call and its corresponding alloca.
640b57cec5SDimitry Andric std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
650b57cec5SDimitry Andric
660b57cec5SDimitry Andric public:
670b57cec5SDimitry Andric static char ID;
680b57cec5SDimitry Andric
690b57cec5SDimitry Andric ShadowStackGCLowering();
700b57cec5SDimitry Andric
710b57cec5SDimitry Andric bool doInitialization(Module &M) override;
72*5f7ddb14SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override;
730b57cec5SDimitry Andric bool runOnFunction(Function &F) override;
740b57cec5SDimitry Andric
750b57cec5SDimitry Andric private:
760b57cec5SDimitry Andric bool IsNullValue(Value *V);
770b57cec5SDimitry Andric Constant *GetFrameMap(Function &F);
780b57cec5SDimitry Andric Type *GetConcreteStackEntryType(Function &F);
790b57cec5SDimitry Andric void CollectRoots(Function &F);
800b57cec5SDimitry Andric
810b57cec5SDimitry Andric static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
820b57cec5SDimitry Andric Type *Ty, Value *BasePtr, int Idx1,
830b57cec5SDimitry Andric const char *Name);
840b57cec5SDimitry Andric static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
850b57cec5SDimitry Andric Type *Ty, Value *BasePtr, int Idx1, int Idx2,
860b57cec5SDimitry Andric const char *Name);
870b57cec5SDimitry Andric };
880b57cec5SDimitry Andric
890b57cec5SDimitry Andric } // end anonymous namespace
900b57cec5SDimitry Andric
910b57cec5SDimitry Andric char ShadowStackGCLowering::ID = 0;
92*5f7ddb14SDimitry Andric char &llvm::ShadowStackGCLoweringID = ShadowStackGCLowering::ID;
930b57cec5SDimitry Andric
940b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, DEBUG_TYPE,
950b57cec5SDimitry Andric "Shadow Stack GC Lowering", false, false)
INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)960b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
97*5f7ddb14SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
980b57cec5SDimitry Andric INITIALIZE_PASS_END(ShadowStackGCLowering, DEBUG_TYPE,
990b57cec5SDimitry Andric "Shadow Stack GC Lowering", false, false)
1000b57cec5SDimitry Andric
1010b57cec5SDimitry Andric FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
1020b57cec5SDimitry Andric
ShadowStackGCLowering()1030b57cec5SDimitry Andric ShadowStackGCLowering::ShadowStackGCLowering() : FunctionPass(ID) {
1040b57cec5SDimitry Andric initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
1050b57cec5SDimitry Andric }
1060b57cec5SDimitry Andric
GetFrameMap(Function & F)1070b57cec5SDimitry Andric Constant *ShadowStackGCLowering::GetFrameMap(Function &F) {
1080b57cec5SDimitry Andric // doInitialization creates the abstract type of this value.
1090b57cec5SDimitry Andric Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
1100b57cec5SDimitry Andric
1110b57cec5SDimitry Andric // Truncate the ShadowStackDescriptor if some metadata is null.
1120b57cec5SDimitry Andric unsigned NumMeta = 0;
1130b57cec5SDimitry Andric SmallVector<Constant *, 16> Metadata;
1140b57cec5SDimitry Andric for (unsigned I = 0; I != Roots.size(); ++I) {
1150b57cec5SDimitry Andric Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
1160b57cec5SDimitry Andric if (!C->isNullValue())
1170b57cec5SDimitry Andric NumMeta = I + 1;
1180b57cec5SDimitry Andric Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
1190b57cec5SDimitry Andric }
1200b57cec5SDimitry Andric Metadata.resize(NumMeta);
1210b57cec5SDimitry Andric
1220b57cec5SDimitry Andric Type *Int32Ty = Type::getInt32Ty(F.getContext());
1230b57cec5SDimitry Andric
1240b57cec5SDimitry Andric Constant *BaseElts[] = {
1250b57cec5SDimitry Andric ConstantInt::get(Int32Ty, Roots.size(), false),
1260b57cec5SDimitry Andric ConstantInt::get(Int32Ty, NumMeta, false),
1270b57cec5SDimitry Andric };
1280b57cec5SDimitry Andric
1290b57cec5SDimitry Andric Constant *DescriptorElts[] = {
1300b57cec5SDimitry Andric ConstantStruct::get(FrameMapTy, BaseElts),
1310b57cec5SDimitry Andric ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
1320b57cec5SDimitry Andric
1330b57cec5SDimitry Andric Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
1340b57cec5SDimitry Andric StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
1350b57cec5SDimitry Andric
1360b57cec5SDimitry Andric Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
1370b57cec5SDimitry Andric
1380b57cec5SDimitry Andric // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
1390b57cec5SDimitry Andric // that, short of multithreaded LLVM, it should be safe; all that is
1400b57cec5SDimitry Andric // necessary is that a simple Module::iterator loop not be invalidated.
1410b57cec5SDimitry Andric // Appending to the GlobalVariable list is safe in that sense.
1420b57cec5SDimitry Andric //
1430b57cec5SDimitry Andric // All of the output passes emit globals last. The ExecutionEngine
1440b57cec5SDimitry Andric // explicitly supports adding globals to the module after
1450b57cec5SDimitry Andric // initialization.
1460b57cec5SDimitry Andric //
1470b57cec5SDimitry Andric // Still, if it isn't deemed acceptable, then this transformation needs
1480b57cec5SDimitry Andric // to be a ModulePass (which means it cannot be in the 'llc' pipeline
1490b57cec5SDimitry Andric // (which uses a FunctionPassManager (which segfaults (not asserts) if
1500b57cec5SDimitry Andric // provided a ModulePass))).
1510b57cec5SDimitry Andric Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
1520b57cec5SDimitry Andric GlobalVariable::InternalLinkage, FrameMap,
1530b57cec5SDimitry Andric "__gc_" + F.getName());
1540b57cec5SDimitry Andric
1550b57cec5SDimitry Andric Constant *GEPIndices[2] = {
1560b57cec5SDimitry Andric ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
1570b57cec5SDimitry Andric ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
1580b57cec5SDimitry Andric return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices);
1590b57cec5SDimitry Andric }
1600b57cec5SDimitry Andric
GetConcreteStackEntryType(Function & F)1610b57cec5SDimitry Andric Type *ShadowStackGCLowering::GetConcreteStackEntryType(Function &F) {
1620b57cec5SDimitry Andric // doInitialization creates the generic version of this type.
1630b57cec5SDimitry Andric std::vector<Type *> EltTys;
1640b57cec5SDimitry Andric EltTys.push_back(StackEntryTy);
1650b57cec5SDimitry Andric for (size_t I = 0; I != Roots.size(); I++)
1660b57cec5SDimitry Andric EltTys.push_back(Roots[I].second->getAllocatedType());
1670b57cec5SDimitry Andric
1680b57cec5SDimitry Andric return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str());
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric
1710b57cec5SDimitry Andric /// doInitialization - If this module uses the GC intrinsics, find them now. If
1720b57cec5SDimitry Andric /// not, exit fast.
doInitialization(Module & M)1730b57cec5SDimitry Andric bool ShadowStackGCLowering::doInitialization(Module &M) {
1740b57cec5SDimitry Andric bool Active = false;
1750b57cec5SDimitry Andric for (Function &F : M) {
1760b57cec5SDimitry Andric if (F.hasGC() && F.getGC() == std::string("shadow-stack")) {
1770b57cec5SDimitry Andric Active = true;
1780b57cec5SDimitry Andric break;
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric if (!Active)
1820b57cec5SDimitry Andric return false;
1830b57cec5SDimitry Andric
1840b57cec5SDimitry Andric // struct FrameMap {
1850b57cec5SDimitry Andric // int32_t NumRoots; // Number of roots in stack frame.
1860b57cec5SDimitry Andric // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
1870b57cec5SDimitry Andric // void *Meta[]; // May be absent for roots without metadata.
1880b57cec5SDimitry Andric // };
1890b57cec5SDimitry Andric std::vector<Type *> EltTys;
1900b57cec5SDimitry Andric // 32 bits is ok up to a 32GB stack frame. :)
1910b57cec5SDimitry Andric EltTys.push_back(Type::getInt32Ty(M.getContext()));
1920b57cec5SDimitry Andric // Specifies length of variable length array.
1930b57cec5SDimitry Andric EltTys.push_back(Type::getInt32Ty(M.getContext()));
1940b57cec5SDimitry Andric FrameMapTy = StructType::create(EltTys, "gc_map");
1950b57cec5SDimitry Andric PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
1960b57cec5SDimitry Andric
1970b57cec5SDimitry Andric // struct StackEntry {
1980b57cec5SDimitry Andric // ShadowStackEntry *Next; // Caller's stack entry.
1990b57cec5SDimitry Andric // FrameMap *Map; // Pointer to constant FrameMap.
2000b57cec5SDimitry Andric // void *Roots[]; // Stack roots (in-place array, so we pretend).
2010b57cec5SDimitry Andric // };
2020b57cec5SDimitry Andric
2030b57cec5SDimitry Andric StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
2040b57cec5SDimitry Andric
2050b57cec5SDimitry Andric EltTys.clear();
2060b57cec5SDimitry Andric EltTys.push_back(PointerType::getUnqual(StackEntryTy));
2070b57cec5SDimitry Andric EltTys.push_back(FrameMapPtrTy);
2080b57cec5SDimitry Andric StackEntryTy->setBody(EltTys);
2090b57cec5SDimitry Andric PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
2100b57cec5SDimitry Andric
2110b57cec5SDimitry Andric // Get the root chain if it already exists.
2120b57cec5SDimitry Andric Head = M.getGlobalVariable("llvm_gc_root_chain");
2130b57cec5SDimitry Andric if (!Head) {
2140b57cec5SDimitry Andric // If the root chain does not exist, insert a new one with linkonce
2150b57cec5SDimitry Andric // linkage!
2160b57cec5SDimitry Andric Head = new GlobalVariable(
2170b57cec5SDimitry Andric M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
2180b57cec5SDimitry Andric Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
2190b57cec5SDimitry Andric } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
2200b57cec5SDimitry Andric Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
2210b57cec5SDimitry Andric Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
2220b57cec5SDimitry Andric }
2230b57cec5SDimitry Andric
2240b57cec5SDimitry Andric return true;
2250b57cec5SDimitry Andric }
2260b57cec5SDimitry Andric
IsNullValue(Value * V)2270b57cec5SDimitry Andric bool ShadowStackGCLowering::IsNullValue(Value *V) {
2280b57cec5SDimitry Andric if (Constant *C = dyn_cast<Constant>(V))
2290b57cec5SDimitry Andric return C->isNullValue();
2300b57cec5SDimitry Andric return false;
2310b57cec5SDimitry Andric }
2320b57cec5SDimitry Andric
CollectRoots(Function & F)2330b57cec5SDimitry Andric void ShadowStackGCLowering::CollectRoots(Function &F) {
2340b57cec5SDimitry Andric // FIXME: Account for original alignment. Could fragment the root array.
2350b57cec5SDimitry Andric // Approach 1: Null initialize empty slots at runtime. Yuck.
2360b57cec5SDimitry Andric // Approach 2: Emit a map of the array instead of just a count.
2370b57cec5SDimitry Andric
2380b57cec5SDimitry Andric assert(Roots.empty() && "Not cleaned up?");
2390b57cec5SDimitry Andric
2400b57cec5SDimitry Andric SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
2410b57cec5SDimitry Andric
242*5f7ddb14SDimitry Andric for (BasicBlock &BB : F)
243*5f7ddb14SDimitry Andric for (BasicBlock::iterator II = BB.begin(), E = BB.end(); II != E;)
2440b57cec5SDimitry Andric if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
2450b57cec5SDimitry Andric if (Function *F = CI->getCalledFunction())
2460b57cec5SDimitry Andric if (F->getIntrinsicID() == Intrinsic::gcroot) {
2470b57cec5SDimitry Andric std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
2480b57cec5SDimitry Andric CI,
2490b57cec5SDimitry Andric cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
2500b57cec5SDimitry Andric if (IsNullValue(CI->getArgOperand(1)))
2510b57cec5SDimitry Andric Roots.push_back(Pair);
2520b57cec5SDimitry Andric else
2530b57cec5SDimitry Andric MetaRoots.push_back(Pair);
2540b57cec5SDimitry Andric }
2550b57cec5SDimitry Andric
2560b57cec5SDimitry Andric // Number roots with metadata (usually empty) at the beginning, so that the
2570b57cec5SDimitry Andric // FrameMap::Meta array can be elided.
2580b57cec5SDimitry Andric Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
2590b57cec5SDimitry Andric }
2600b57cec5SDimitry Andric
CreateGEP(LLVMContext & Context,IRBuilder<> & B,Type * Ty,Value * BasePtr,int Idx,int Idx2,const char * Name)2610b57cec5SDimitry Andric GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
2620b57cec5SDimitry Andric IRBuilder<> &B, Type *Ty,
2630b57cec5SDimitry Andric Value *BasePtr, int Idx,
2640b57cec5SDimitry Andric int Idx2,
2650b57cec5SDimitry Andric const char *Name) {
2660b57cec5SDimitry Andric Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
2670b57cec5SDimitry Andric ConstantInt::get(Type::getInt32Ty(Context), Idx),
2680b57cec5SDimitry Andric ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
2690b57cec5SDimitry Andric Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
2700b57cec5SDimitry Andric
2710b57cec5SDimitry Andric assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
2720b57cec5SDimitry Andric
2730b57cec5SDimitry Andric return dyn_cast<GetElementPtrInst>(Val);
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric
CreateGEP(LLVMContext & Context,IRBuilder<> & B,Type * Ty,Value * BasePtr,int Idx,const char * Name)2760b57cec5SDimitry Andric GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
2770b57cec5SDimitry Andric IRBuilder<> &B, Type *Ty, Value *BasePtr,
2780b57cec5SDimitry Andric int Idx, const char *Name) {
2790b57cec5SDimitry Andric Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
2800b57cec5SDimitry Andric ConstantInt::get(Type::getInt32Ty(Context), Idx)};
2810b57cec5SDimitry Andric Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
2820b57cec5SDimitry Andric
2830b57cec5SDimitry Andric assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
2840b57cec5SDimitry Andric
2850b57cec5SDimitry Andric return dyn_cast<GetElementPtrInst>(Val);
2860b57cec5SDimitry Andric }
2870b57cec5SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const288*5f7ddb14SDimitry Andric void ShadowStackGCLowering::getAnalysisUsage(AnalysisUsage &AU) const {
289*5f7ddb14SDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>();
290*5f7ddb14SDimitry Andric }
291*5f7ddb14SDimitry Andric
2920b57cec5SDimitry Andric /// runOnFunction - Insert code to maintain the shadow stack.
runOnFunction(Function & F)2930b57cec5SDimitry Andric bool ShadowStackGCLowering::runOnFunction(Function &F) {
2940b57cec5SDimitry Andric // Quick exit for functions that do not use the shadow stack GC.
2950b57cec5SDimitry Andric if (!F.hasGC() ||
2960b57cec5SDimitry Andric F.getGC() != std::string("shadow-stack"))
2970b57cec5SDimitry Andric return false;
2980b57cec5SDimitry Andric
2990b57cec5SDimitry Andric LLVMContext &Context = F.getContext();
3000b57cec5SDimitry Andric
3010b57cec5SDimitry Andric // Find calls to llvm.gcroot.
3020b57cec5SDimitry Andric CollectRoots(F);
3030b57cec5SDimitry Andric
3040b57cec5SDimitry Andric // If there are no roots in this function, then there is no need to add a
3050b57cec5SDimitry Andric // stack map entry for it.
3060b57cec5SDimitry Andric if (Roots.empty())
3070b57cec5SDimitry Andric return false;
3080b57cec5SDimitry Andric
309*5f7ddb14SDimitry Andric Optional<DomTreeUpdater> DTU;
310*5f7ddb14SDimitry Andric if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
311*5f7ddb14SDimitry Andric DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
312*5f7ddb14SDimitry Andric
3130b57cec5SDimitry Andric // Build the constant map and figure the type of the shadow stack entry.
3140b57cec5SDimitry Andric Value *FrameMap = GetFrameMap(F);
3150b57cec5SDimitry Andric Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
3160b57cec5SDimitry Andric
3170b57cec5SDimitry Andric // Build the shadow stack entry at the very start of the function.
3180b57cec5SDimitry Andric BasicBlock::iterator IP = F.getEntryBlock().begin();
3190b57cec5SDimitry Andric IRBuilder<> AtEntry(IP->getParent(), IP);
3200b57cec5SDimitry Andric
3210b57cec5SDimitry Andric Instruction *StackEntry =
3220b57cec5SDimitry Andric AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
3230b57cec5SDimitry Andric
3240b57cec5SDimitry Andric while (isa<AllocaInst>(IP))
3250b57cec5SDimitry Andric ++IP;
3260b57cec5SDimitry Andric AtEntry.SetInsertPoint(IP->getParent(), IP);
3270b57cec5SDimitry Andric
3280b57cec5SDimitry Andric // Initialize the map pointer and load the current head of the shadow stack.
3290b57cec5SDimitry Andric Instruction *CurrentHead =
3300b57cec5SDimitry Andric AtEntry.CreateLoad(StackEntryTy->getPointerTo(), Head, "gc_currhead");
3310b57cec5SDimitry Andric Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
3320b57cec5SDimitry Andric StackEntry, 0, 1, "gc_frame.map");
3330b57cec5SDimitry Andric AtEntry.CreateStore(FrameMap, EntryMapPtr);
3340b57cec5SDimitry Andric
3350b57cec5SDimitry Andric // After all the allocas...
3360b57cec5SDimitry Andric for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
3370b57cec5SDimitry Andric // For each root, find the corresponding slot in the aggregate...
3380b57cec5SDimitry Andric Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
3390b57cec5SDimitry Andric StackEntry, 1 + I, "gc_root");
3400b57cec5SDimitry Andric
3410b57cec5SDimitry Andric // And use it in lieu of the alloca.
3420b57cec5SDimitry Andric AllocaInst *OriginalAlloca = Roots[I].second;
3430b57cec5SDimitry Andric SlotPtr->takeName(OriginalAlloca);
3440b57cec5SDimitry Andric OriginalAlloca->replaceAllUsesWith(SlotPtr);
3450b57cec5SDimitry Andric }
3460b57cec5SDimitry Andric
3470b57cec5SDimitry Andric // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
3480b57cec5SDimitry Andric // really necessary (the collector would never see the intermediate state at
3490b57cec5SDimitry Andric // runtime), but it's nicer not to push the half-initialized entry onto the
3500b57cec5SDimitry Andric // shadow stack.
3510b57cec5SDimitry Andric while (isa<StoreInst>(IP))
3520b57cec5SDimitry Andric ++IP;
3530b57cec5SDimitry Andric AtEntry.SetInsertPoint(IP->getParent(), IP);
3540b57cec5SDimitry Andric
3550b57cec5SDimitry Andric // Push the entry onto the shadow stack.
3560b57cec5SDimitry Andric Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
3570b57cec5SDimitry Andric StackEntry, 0, 0, "gc_frame.next");
3580b57cec5SDimitry Andric Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
3590b57cec5SDimitry Andric StackEntry, 0, "gc_newhead");
3600b57cec5SDimitry Andric AtEntry.CreateStore(CurrentHead, EntryNextPtr);
3610b57cec5SDimitry Andric AtEntry.CreateStore(NewHeadVal, Head);
3620b57cec5SDimitry Andric
3630b57cec5SDimitry Andric // For each instruction that escapes...
364*5f7ddb14SDimitry Andric EscapeEnumerator EE(F, "gc_cleanup", /*HandleExceptions=*/true,
365*5f7ddb14SDimitry Andric DTU.hasValue() ? DTU.getPointer() : nullptr);
3660b57cec5SDimitry Andric while (IRBuilder<> *AtExit = EE.Next()) {
3670b57cec5SDimitry Andric // Pop the entry from the shadow stack. Don't reuse CurrentHead from
3680b57cec5SDimitry Andric // AtEntry, since that would make the value live for the entire function.
3690b57cec5SDimitry Andric Instruction *EntryNextPtr2 =
3700b57cec5SDimitry Andric CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
3710b57cec5SDimitry Andric "gc_frame.next");
3720b57cec5SDimitry Andric Value *SavedHead = AtExit->CreateLoad(StackEntryTy->getPointerTo(),
3730b57cec5SDimitry Andric EntryNextPtr2, "gc_savedhead");
3740b57cec5SDimitry Andric AtExit->CreateStore(SavedHead, Head);
3750b57cec5SDimitry Andric }
3760b57cec5SDimitry Andric
3770b57cec5SDimitry Andric // Delete the original allocas (which are no longer used) and the intrinsic
3780b57cec5SDimitry Andric // calls (which are no longer valid). Doing this last avoids invalidating
3790b57cec5SDimitry Andric // iterators.
3800b57cec5SDimitry Andric for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
3810b57cec5SDimitry Andric Roots[I].first->eraseFromParent();
3820b57cec5SDimitry Andric Roots[I].second->eraseFromParent();
3830b57cec5SDimitry Andric }
3840b57cec5SDimitry Andric
3850b57cec5SDimitry Andric Roots.clear();
3860b57cec5SDimitry Andric return true;
3870b57cec5SDimitry Andric }
388