1044eb2f6SDimitry Andric //===- ShadowStackGCLowering.cpp - Custom lowering for shadow-stack gc ----===//
25a5ac124SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65a5ac124SDimitry Andric //
75a5ac124SDimitry Andric //===----------------------------------------------------------------------===//
85a5ac124SDimitry Andric //
95a5ac124SDimitry Andric // This file contains the custom lowering code required by the shadow-stack GC
105a5ac124SDimitry Andric // strategy.
1101095a5dSDimitry Andric //
1201095a5dSDimitry Andric // This pass implements the code transformation described in this paper:
1301095a5dSDimitry Andric // "Accurate Garbage Collection in an Uncooperative Environment"
1401095a5dSDimitry Andric // Fergus Henderson, ISMM, 2002
155a5ac124SDimitry Andric //
165a5ac124SDimitry Andric //===----------------------------------------------------------------------===//
175a5ac124SDimitry Andric
18aca2e42cSDimitry Andric #include "llvm/CodeGen/ShadowStackGCLowering.h"
19044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
205a5ac124SDimitry Andric #include "llvm/ADT/StringExtras.h"
21344a3780SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
22aca2e42cSDimitry Andric #include "llvm/CodeGen/GCMetadata.h"
237ab83427SDimitry Andric #include "llvm/CodeGen/Passes.h"
24044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
25044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
26044eb2f6SDimitry Andric #include "llvm/IR/Constants.h"
27044eb2f6SDimitry Andric #include "llvm/IR/DerivedTypes.h"
28344a3780SDimitry Andric #include "llvm/IR/Dominators.h"
29044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
30044eb2f6SDimitry Andric #include "llvm/IR/GlobalValue.h"
31044eb2f6SDimitry Andric #include "llvm/IR/GlobalVariable.h"
325a5ac124SDimitry Andric #include "llvm/IR/IRBuilder.h"
33044eb2f6SDimitry Andric #include "llvm/IR/Instructions.h"
345a5ac124SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
35044eb2f6SDimitry Andric #include "llvm/IR/Intrinsics.h"
365a5ac124SDimitry Andric #include "llvm/IR/Module.h"
37044eb2f6SDimitry Andric #include "llvm/IR/Type.h"
38044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
39706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
40044eb2f6SDimitry Andric #include "llvm/Pass.h"
41044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
42b915e9e0SDimitry Andric #include "llvm/Transforms/Utils/EscapeEnumerator.h"
43044eb2f6SDimitry Andric #include <cassert>
44e3b55780SDimitry Andric #include <optional>
45044eb2f6SDimitry Andric #include <string>
46044eb2f6SDimitry Andric #include <utility>
47044eb2f6SDimitry Andric #include <vector>
485a5ac124SDimitry Andric
495a5ac124SDimitry Andric using namespace llvm;
505a5ac124SDimitry Andric
51ab44ce3dSDimitry Andric #define DEBUG_TYPE "shadow-stack-gc-lowering"
525a5ac124SDimitry Andric
535a5ac124SDimitry Andric namespace {
545a5ac124SDimitry Andric
55aca2e42cSDimitry Andric class ShadowStackGCLoweringImpl {
565a5ac124SDimitry Andric /// RootChain - This is the global linked-list that contains the chain of GC
575a5ac124SDimitry Andric /// roots.
58044eb2f6SDimitry Andric GlobalVariable *Head = nullptr;
595a5ac124SDimitry Andric
605a5ac124SDimitry Andric /// StackEntryTy - Abstract type of a link in the shadow stack.
61044eb2f6SDimitry Andric StructType *StackEntryTy = nullptr;
62044eb2f6SDimitry Andric StructType *FrameMapTy = nullptr;
635a5ac124SDimitry Andric
645a5ac124SDimitry Andric /// Roots - GC roots in the current function. Each is a pair of the
655a5ac124SDimitry Andric /// intrinsic call and its corresponding alloca.
665a5ac124SDimitry Andric std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
675a5ac124SDimitry Andric
685a5ac124SDimitry Andric public:
69aca2e42cSDimitry Andric ShadowStackGCLoweringImpl() = default;
70044eb2f6SDimitry Andric
71aca2e42cSDimitry Andric bool doInitialization(Module &M);
72aca2e42cSDimitry Andric bool runOnFunction(Function &F, DomTreeUpdater *DTU);
735a5ac124SDimitry Andric
745a5ac124SDimitry Andric private:
755a5ac124SDimitry Andric bool IsNullValue(Value *V);
765a5ac124SDimitry Andric Constant *GetFrameMap(Function &F);
775a5ac124SDimitry Andric Type *GetConcreteStackEntryType(Function &F);
785a5ac124SDimitry Andric void CollectRoots(Function &F);
79044eb2f6SDimitry Andric
805a5ac124SDimitry Andric static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
815a5ac124SDimitry Andric Type *Ty, Value *BasePtr, int Idx1,
825a5ac124SDimitry Andric const char *Name);
835a5ac124SDimitry Andric static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
845a5ac124SDimitry Andric Type *Ty, Value *BasePtr, int Idx1, int Idx2,
855a5ac124SDimitry Andric const char *Name);
865a5ac124SDimitry Andric };
87044eb2f6SDimitry Andric
88aca2e42cSDimitry Andric class ShadowStackGCLowering : public FunctionPass {
89aca2e42cSDimitry Andric ShadowStackGCLoweringImpl Impl;
90aca2e42cSDimitry Andric
91aca2e42cSDimitry Andric public:
92aca2e42cSDimitry Andric static char ID;
93aca2e42cSDimitry Andric
94aca2e42cSDimitry Andric ShadowStackGCLowering();
95aca2e42cSDimitry Andric
doInitialization(Module & M)96aca2e42cSDimitry Andric bool doInitialization(Module &M) override { return Impl.doInitialization(M); }
getAnalysisUsage(AnalysisUsage & AU) const97aca2e42cSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
98aca2e42cSDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>();
99aca2e42cSDimitry Andric }
runOnFunction(Function & F)100aca2e42cSDimitry Andric bool runOnFunction(Function &F) override {
101aca2e42cSDimitry Andric std::optional<DomTreeUpdater> DTU;
102aca2e42cSDimitry Andric if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
103aca2e42cSDimitry Andric DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
104aca2e42cSDimitry Andric return Impl.runOnFunction(F, DTU ? &*DTU : nullptr);
105aca2e42cSDimitry Andric }
106aca2e42cSDimitry Andric };
107aca2e42cSDimitry Andric
108044eb2f6SDimitry Andric } // end anonymous namespace
109044eb2f6SDimitry Andric
run(Module & M,ModuleAnalysisManager & MAM)110aca2e42cSDimitry Andric PreservedAnalyses ShadowStackGCLoweringPass::run(Module &M,
111aca2e42cSDimitry Andric ModuleAnalysisManager &MAM) {
112aca2e42cSDimitry Andric auto &Map = MAM.getResult<CollectorMetadataAnalysis>(M);
113aca2e42cSDimitry Andric if (Map.StrategyMap.contains("shadow-stack"))
114aca2e42cSDimitry Andric return PreservedAnalyses::all();
115aca2e42cSDimitry Andric
116aca2e42cSDimitry Andric ShadowStackGCLoweringImpl Impl;
117aca2e42cSDimitry Andric bool Changed = Impl.doInitialization(M);
118aca2e42cSDimitry Andric for (auto &F : M) {
119aca2e42cSDimitry Andric auto &FAM =
120aca2e42cSDimitry Andric MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
121aca2e42cSDimitry Andric auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
122aca2e42cSDimitry Andric DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
123aca2e42cSDimitry Andric Changed |= Impl.runOnFunction(F, DT ? &DTU : nullptr);
124aca2e42cSDimitry Andric }
125aca2e42cSDimitry Andric
126aca2e42cSDimitry Andric if (!Changed)
127aca2e42cSDimitry Andric return PreservedAnalyses::all();
128aca2e42cSDimitry Andric PreservedAnalyses PA;
129aca2e42cSDimitry Andric PA.preserve<DominatorTreeAnalysis>();
130aca2e42cSDimitry Andric return PA;
131aca2e42cSDimitry Andric }
132aca2e42cSDimitry Andric
133044eb2f6SDimitry Andric char ShadowStackGCLowering::ID = 0;
134344a3780SDimitry Andric char &llvm::ShadowStackGCLoweringID = ShadowStackGCLowering::ID;
1355a5ac124SDimitry Andric
136ab44ce3dSDimitry Andric INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, DEBUG_TYPE,
1375a5ac124SDimitry Andric "Shadow Stack GC Lowering", false, false)
INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)1385a5ac124SDimitry Andric INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
139344a3780SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
140ab44ce3dSDimitry Andric INITIALIZE_PASS_END(ShadowStackGCLowering, DEBUG_TYPE,
1415a5ac124SDimitry Andric "Shadow Stack GC Lowering", false, false)
1425a5ac124SDimitry Andric
1435a5ac124SDimitry Andric FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
1445a5ac124SDimitry Andric
ShadowStackGCLowering()145044eb2f6SDimitry Andric ShadowStackGCLowering::ShadowStackGCLowering() : FunctionPass(ID) {
1465a5ac124SDimitry Andric initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
1475a5ac124SDimitry Andric }
1485a5ac124SDimitry Andric
GetFrameMap(Function & F)149aca2e42cSDimitry Andric Constant *ShadowStackGCLoweringImpl::GetFrameMap(Function &F) {
1505a5ac124SDimitry Andric // doInitialization creates the abstract type of this value.
151b1c73532SDimitry Andric Type *VoidPtr = PointerType::getUnqual(F.getContext());
1525a5ac124SDimitry Andric
1535a5ac124SDimitry Andric // Truncate the ShadowStackDescriptor if some metadata is null.
1545a5ac124SDimitry Andric unsigned NumMeta = 0;
1555a5ac124SDimitry Andric SmallVector<Constant *, 16> Metadata;
1565a5ac124SDimitry Andric for (unsigned I = 0; I != Roots.size(); ++I) {
1575a5ac124SDimitry Andric Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
1585a5ac124SDimitry Andric if (!C->isNullValue())
1595a5ac124SDimitry Andric NumMeta = I + 1;
16099aabd70SDimitry Andric Metadata.push_back(C);
1615a5ac124SDimitry Andric }
1625a5ac124SDimitry Andric Metadata.resize(NumMeta);
1635a5ac124SDimitry Andric
1645a5ac124SDimitry Andric Type *Int32Ty = Type::getInt32Ty(F.getContext());
1655a5ac124SDimitry Andric
1665a5ac124SDimitry Andric Constant *BaseElts[] = {
1675a5ac124SDimitry Andric ConstantInt::get(Int32Ty, Roots.size(), false),
1685a5ac124SDimitry Andric ConstantInt::get(Int32Ty, NumMeta, false),
1695a5ac124SDimitry Andric };
1705a5ac124SDimitry Andric
1715a5ac124SDimitry Andric Constant *DescriptorElts[] = {
1725a5ac124SDimitry Andric ConstantStruct::get(FrameMapTy, BaseElts),
1735a5ac124SDimitry Andric ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
1745a5ac124SDimitry Andric
1755a5ac124SDimitry Andric Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
1765a5ac124SDimitry Andric StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
1775a5ac124SDimitry Andric
1785a5ac124SDimitry Andric Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
1795a5ac124SDimitry Andric
1805a5ac124SDimitry Andric // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
1815a5ac124SDimitry Andric // that, short of multithreaded LLVM, it should be safe; all that is
1825a5ac124SDimitry Andric // necessary is that a simple Module::iterator loop not be invalidated.
1835a5ac124SDimitry Andric // Appending to the GlobalVariable list is safe in that sense.
1845a5ac124SDimitry Andric //
1855a5ac124SDimitry Andric // All of the output passes emit globals last. The ExecutionEngine
1865a5ac124SDimitry Andric // explicitly supports adding globals to the module after
1875a5ac124SDimitry Andric // initialization.
1885a5ac124SDimitry Andric //
1895a5ac124SDimitry Andric // Still, if it isn't deemed acceptable, then this transformation needs
1905a5ac124SDimitry Andric // to be a ModulePass (which means it cannot be in the 'llc' pipeline
1915a5ac124SDimitry Andric // (which uses a FunctionPassManager (which segfaults (not asserts) if
1925a5ac124SDimitry Andric // provided a ModulePass))).
1935a5ac124SDimitry Andric Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
1945a5ac124SDimitry Andric GlobalVariable::InternalLinkage, FrameMap,
1955a5ac124SDimitry Andric "__gc_" + F.getName());
1965a5ac124SDimitry Andric
1975a5ac124SDimitry Andric Constant *GEPIndices[2] = {
1985a5ac124SDimitry Andric ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
1995a5ac124SDimitry Andric ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
2005a5ac124SDimitry Andric return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices);
2015a5ac124SDimitry Andric }
2025a5ac124SDimitry Andric
GetConcreteStackEntryType(Function & F)203aca2e42cSDimitry Andric Type *ShadowStackGCLoweringImpl::GetConcreteStackEntryType(Function &F) {
2045a5ac124SDimitry Andric // doInitialization creates the generic version of this type.
2055a5ac124SDimitry Andric std::vector<Type *> EltTys;
2065a5ac124SDimitry Andric EltTys.push_back(StackEntryTy);
20777fc4c14SDimitry Andric for (const std::pair<CallInst *, AllocaInst *> &Root : Roots)
20877fc4c14SDimitry Andric EltTys.push_back(Root.second->getAllocatedType());
2095a5ac124SDimitry Andric
2105a5ac124SDimitry Andric return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str());
2115a5ac124SDimitry Andric }
2125a5ac124SDimitry Andric
2135a5ac124SDimitry Andric /// doInitialization - If this module uses the GC intrinsics, find them now. If
2145a5ac124SDimitry Andric /// not, exit fast.
doInitialization(Module & M)215aca2e42cSDimitry Andric bool ShadowStackGCLoweringImpl::doInitialization(Module &M) {
2165a5ac124SDimitry Andric bool Active = false;
2175a5ac124SDimitry Andric for (Function &F : M) {
21899aabd70SDimitry Andric if (F.hasGC() && F.getGC() == "shadow-stack") {
2195a5ac124SDimitry Andric Active = true;
2205a5ac124SDimitry Andric break;
2215a5ac124SDimitry Andric }
2225a5ac124SDimitry Andric }
2235a5ac124SDimitry Andric if (!Active)
2245a5ac124SDimitry Andric return false;
2255a5ac124SDimitry Andric
2265a5ac124SDimitry Andric // struct FrameMap {
2275a5ac124SDimitry Andric // int32_t NumRoots; // Number of roots in stack frame.
2285a5ac124SDimitry Andric // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
2295a5ac124SDimitry Andric // void *Meta[]; // May be absent for roots without metadata.
2305a5ac124SDimitry Andric // };
2315a5ac124SDimitry Andric std::vector<Type *> EltTys;
2325a5ac124SDimitry Andric // 32 bits is ok up to a 32GB stack frame. :)
2335a5ac124SDimitry Andric EltTys.push_back(Type::getInt32Ty(M.getContext()));
2345a5ac124SDimitry Andric // Specifies length of variable length array.
2355a5ac124SDimitry Andric EltTys.push_back(Type::getInt32Ty(M.getContext()));
2365a5ac124SDimitry Andric FrameMapTy = StructType::create(EltTys, "gc_map");
2375a5ac124SDimitry Andric PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
2385a5ac124SDimitry Andric
2395a5ac124SDimitry Andric // struct StackEntry {
2405a5ac124SDimitry Andric // ShadowStackEntry *Next; // Caller's stack entry.
2415a5ac124SDimitry Andric // FrameMap *Map; // Pointer to constant FrameMap.
2425a5ac124SDimitry Andric // void *Roots[]; // Stack roots (in-place array, so we pretend).
2435a5ac124SDimitry Andric // };
2445a5ac124SDimitry Andric
2455a5ac124SDimitry Andric StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
2465a5ac124SDimitry Andric
2475a5ac124SDimitry Andric EltTys.clear();
2485a5ac124SDimitry Andric EltTys.push_back(PointerType::getUnqual(StackEntryTy));
2495a5ac124SDimitry Andric EltTys.push_back(FrameMapPtrTy);
2505a5ac124SDimitry Andric StackEntryTy->setBody(EltTys);
2515a5ac124SDimitry Andric PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
2525a5ac124SDimitry Andric
2535a5ac124SDimitry Andric // Get the root chain if it already exists.
2545a5ac124SDimitry Andric Head = M.getGlobalVariable("llvm_gc_root_chain");
2555a5ac124SDimitry Andric if (!Head) {
2565a5ac124SDimitry Andric // If the root chain does not exist, insert a new one with linkonce
2575a5ac124SDimitry Andric // linkage!
2585a5ac124SDimitry Andric Head = new GlobalVariable(
2595a5ac124SDimitry Andric M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
2605a5ac124SDimitry Andric Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
2615a5ac124SDimitry Andric } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
2625a5ac124SDimitry Andric Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
2635a5ac124SDimitry Andric Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
2645a5ac124SDimitry Andric }
2655a5ac124SDimitry Andric
2665a5ac124SDimitry Andric return true;
2675a5ac124SDimitry Andric }
2685a5ac124SDimitry Andric
IsNullValue(Value * V)269aca2e42cSDimitry Andric bool ShadowStackGCLoweringImpl::IsNullValue(Value *V) {
2705a5ac124SDimitry Andric if (Constant *C = dyn_cast<Constant>(V))
2715a5ac124SDimitry Andric return C->isNullValue();
2725a5ac124SDimitry Andric return false;
2735a5ac124SDimitry Andric }
2745a5ac124SDimitry Andric
CollectRoots(Function & F)275aca2e42cSDimitry Andric void ShadowStackGCLoweringImpl::CollectRoots(Function &F) {
2765a5ac124SDimitry Andric // FIXME: Account for original alignment. Could fragment the root array.
2775a5ac124SDimitry Andric // Approach 1: Null initialize empty slots at runtime. Yuck.
2785a5ac124SDimitry Andric // Approach 2: Emit a map of the array instead of just a count.
2795a5ac124SDimitry Andric
2805a5ac124SDimitry Andric assert(Roots.empty() && "Not cleaned up?");
2815a5ac124SDimitry Andric
2825a5ac124SDimitry Andric SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
2835a5ac124SDimitry Andric
284344a3780SDimitry Andric for (BasicBlock &BB : F)
28577fc4c14SDimitry Andric for (Instruction &I : BB)
28677fc4c14SDimitry Andric if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(&I))
2875a5ac124SDimitry Andric if (Function *F = CI->getCalledFunction())
2885a5ac124SDimitry Andric if (F->getIntrinsicID() == Intrinsic::gcroot) {
2895a5ac124SDimitry Andric std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
2905a5ac124SDimitry Andric CI,
2915a5ac124SDimitry Andric cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
2925a5ac124SDimitry Andric if (IsNullValue(CI->getArgOperand(1)))
2935a5ac124SDimitry Andric Roots.push_back(Pair);
2945a5ac124SDimitry Andric else
2955a5ac124SDimitry Andric MetaRoots.push_back(Pair);
2965a5ac124SDimitry Andric }
2975a5ac124SDimitry Andric
2985a5ac124SDimitry Andric // Number roots with metadata (usually empty) at the beginning, so that the
2995a5ac124SDimitry Andric // FrameMap::Meta array can be elided.
3005a5ac124SDimitry Andric Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
3015a5ac124SDimitry Andric }
3025a5ac124SDimitry Andric
303aca2e42cSDimitry Andric GetElementPtrInst *
CreateGEP(LLVMContext & Context,IRBuilder<> & B,Type * Ty,Value * BasePtr,int Idx,int Idx2,const char * Name)304aca2e42cSDimitry Andric ShadowStackGCLoweringImpl::CreateGEP(LLVMContext &Context, IRBuilder<> &B,
305aca2e42cSDimitry Andric Type *Ty, Value *BasePtr, int Idx,
306aca2e42cSDimitry Andric int Idx2, const char *Name) {
3075a5ac124SDimitry Andric Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
3085a5ac124SDimitry Andric ConstantInt::get(Type::getInt32Ty(Context), Idx),
3095a5ac124SDimitry Andric ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
3105a5ac124SDimitry Andric Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
3115a5ac124SDimitry Andric
3125a5ac124SDimitry Andric assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
3135a5ac124SDimitry Andric
3145a5ac124SDimitry Andric return dyn_cast<GetElementPtrInst>(Val);
3155a5ac124SDimitry Andric }
3165a5ac124SDimitry Andric
CreateGEP(LLVMContext & Context,IRBuilder<> & B,Type * Ty,Value * BasePtr,int Idx,const char * Name)317aca2e42cSDimitry Andric GetElementPtrInst *ShadowStackGCLoweringImpl::CreateGEP(LLVMContext &Context,
318aca2e42cSDimitry Andric IRBuilder<> &B,
319aca2e42cSDimitry Andric Type *Ty,
320aca2e42cSDimitry Andric Value *BasePtr, int Idx,
321aca2e42cSDimitry Andric const char *Name) {
3225a5ac124SDimitry Andric Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
3235a5ac124SDimitry Andric ConstantInt::get(Type::getInt32Ty(Context), Idx)};
3245a5ac124SDimitry Andric Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
3255a5ac124SDimitry Andric
3265a5ac124SDimitry Andric assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
3275a5ac124SDimitry Andric
3285a5ac124SDimitry Andric return dyn_cast<GetElementPtrInst>(Val);
3295a5ac124SDimitry Andric }
3305a5ac124SDimitry Andric
3315a5ac124SDimitry Andric /// runOnFunction - Insert code to maintain the shadow stack.
runOnFunction(Function & F,DomTreeUpdater * DTU)332aca2e42cSDimitry Andric bool ShadowStackGCLoweringImpl::runOnFunction(Function &F,
333aca2e42cSDimitry Andric DomTreeUpdater *DTU) {
3345a5ac124SDimitry Andric // Quick exit for functions that do not use the shadow stack GC.
33599aabd70SDimitry Andric if (!F.hasGC() || F.getGC() != "shadow-stack")
3365a5ac124SDimitry Andric return false;
3375a5ac124SDimitry Andric
3385a5ac124SDimitry Andric LLVMContext &Context = F.getContext();
3395a5ac124SDimitry Andric
3405a5ac124SDimitry Andric // Find calls to llvm.gcroot.
3415a5ac124SDimitry Andric CollectRoots(F);
3425a5ac124SDimitry Andric
3435a5ac124SDimitry Andric // If there are no roots in this function, then there is no need to add a
3445a5ac124SDimitry Andric // stack map entry for it.
3455a5ac124SDimitry Andric if (Roots.empty())
3465a5ac124SDimitry Andric return false;
3475a5ac124SDimitry Andric
3485a5ac124SDimitry Andric // Build the constant map and figure the type of the shadow stack entry.
3495a5ac124SDimitry Andric Value *FrameMap = GetFrameMap(F);
3505a5ac124SDimitry Andric Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
3515a5ac124SDimitry Andric
3525a5ac124SDimitry Andric // Build the shadow stack entry at the very start of the function.
3535a5ac124SDimitry Andric BasicBlock::iterator IP = F.getEntryBlock().begin();
3545a5ac124SDimitry Andric IRBuilder<> AtEntry(IP->getParent(), IP);
3555a5ac124SDimitry Andric
3565a5ac124SDimitry Andric Instruction *StackEntry =
3575a5ac124SDimitry Andric AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
3585a5ac124SDimitry Andric
359e3b55780SDimitry Andric AtEntry.SetInsertPointPastAllocas(&F);
360e3b55780SDimitry Andric IP = AtEntry.GetInsertPoint();
3615a5ac124SDimitry Andric
3625a5ac124SDimitry Andric // Initialize the map pointer and load the current head of the shadow stack.
363e6d15924SDimitry Andric Instruction *CurrentHead =
364b1c73532SDimitry Andric AtEntry.CreateLoad(AtEntry.getPtrTy(), Head, "gc_currhead");
3655a5ac124SDimitry Andric Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
3665a5ac124SDimitry Andric StackEntry, 0, 1, "gc_frame.map");
3675a5ac124SDimitry Andric AtEntry.CreateStore(FrameMap, EntryMapPtr);
3685a5ac124SDimitry Andric
3695a5ac124SDimitry Andric // After all the allocas...
3705a5ac124SDimitry Andric for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
3715a5ac124SDimitry Andric // For each root, find the corresponding slot in the aggregate...
3725a5ac124SDimitry Andric Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
3735a5ac124SDimitry Andric StackEntry, 1 + I, "gc_root");
3745a5ac124SDimitry Andric
3755a5ac124SDimitry Andric // And use it in lieu of the alloca.
3765a5ac124SDimitry Andric AllocaInst *OriginalAlloca = Roots[I].second;
3775a5ac124SDimitry Andric SlotPtr->takeName(OriginalAlloca);
3785a5ac124SDimitry Andric OriginalAlloca->replaceAllUsesWith(SlotPtr);
3795a5ac124SDimitry Andric }
3805a5ac124SDimitry Andric
3815a5ac124SDimitry Andric // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
3825a5ac124SDimitry Andric // really necessary (the collector would never see the intermediate state at
3835a5ac124SDimitry Andric // runtime), but it's nicer not to push the half-initialized entry onto the
3845a5ac124SDimitry Andric // shadow stack.
3855a5ac124SDimitry Andric while (isa<StoreInst>(IP))
3865a5ac124SDimitry Andric ++IP;
3875a5ac124SDimitry Andric AtEntry.SetInsertPoint(IP->getParent(), IP);
3885a5ac124SDimitry Andric
3895a5ac124SDimitry Andric // Push the entry onto the shadow stack.
3905a5ac124SDimitry Andric Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
3915a5ac124SDimitry Andric StackEntry, 0, 0, "gc_frame.next");
3925a5ac124SDimitry Andric Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
3935a5ac124SDimitry Andric StackEntry, 0, "gc_newhead");
3945a5ac124SDimitry Andric AtEntry.CreateStore(CurrentHead, EntryNextPtr);
3955a5ac124SDimitry Andric AtEntry.CreateStore(NewHeadVal, Head);
3965a5ac124SDimitry Andric
3975a5ac124SDimitry Andric // For each instruction that escapes...
398aca2e42cSDimitry Andric EscapeEnumerator EE(F, "gc_cleanup", /*HandleExceptions=*/true, DTU);
3995a5ac124SDimitry Andric while (IRBuilder<> *AtExit = EE.Next()) {
4005a5ac124SDimitry Andric // Pop the entry from the shadow stack. Don't reuse CurrentHead from
4015a5ac124SDimitry Andric // AtEntry, since that would make the value live for the entire function.
4025a5ac124SDimitry Andric Instruction *EntryNextPtr2 =
4035a5ac124SDimitry Andric CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
4045a5ac124SDimitry Andric "gc_frame.next");
405b1c73532SDimitry Andric Value *SavedHead =
406b1c73532SDimitry Andric AtExit->CreateLoad(AtExit->getPtrTy(), EntryNextPtr2, "gc_savedhead");
4075a5ac124SDimitry Andric AtExit->CreateStore(SavedHead, Head);
4085a5ac124SDimitry Andric }
4095a5ac124SDimitry Andric
4105a5ac124SDimitry Andric // Delete the original allocas (which are no longer used) and the intrinsic
4115a5ac124SDimitry Andric // calls (which are no longer valid). Doing this last avoids invalidating
4125a5ac124SDimitry Andric // iterators.
41377fc4c14SDimitry Andric for (std::pair<CallInst *, AllocaInst *> &Root : Roots) {
41477fc4c14SDimitry Andric Root.first->eraseFromParent();
41577fc4c14SDimitry Andric Root.second->eraseFromParent();
4165a5ac124SDimitry Andric }
4175a5ac124SDimitry Andric
4185a5ac124SDimitry Andric Roots.clear();
4195a5ac124SDimitry Andric return true;
4205a5ac124SDimitry Andric }
421