1 //===-- ShadowStackGCLowering.cpp - Custom lowering for shadow-stack gc ---===//
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 contains the custom lowering code required by the shadow-stack GC
13 // This pass implements the code transformation described in this paper:
14 // "Accurate Garbage Collection in an Uncooperative Environment"
15 // Fergus Henderson, ISMM, 2002
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/CodeGen/GCStrategy.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
30 #define DEBUG_TYPE "shadow-stack-gc-lowering"
34 class ShadowStackGCLowering : public FunctionPass {
35 /// RootChain - This is the global linked-list that contains the chain of GC
39 /// StackEntryTy - Abstract type of a link in the shadow stack.
41 StructType *StackEntryTy;
42 StructType *FrameMapTy;
44 /// Roots - GC roots in the current function. Each is a pair of the
45 /// intrinsic call and its corresponding alloca.
46 std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
50 ShadowStackGCLowering();
52 bool doInitialization(Module &M) override;
53 bool runOnFunction(Function &F) override;
56 bool IsNullValue(Value *V);
57 Constant *GetFrameMap(Function &F);
58 Type *GetConcreteStackEntryType(Function &F);
59 void CollectRoots(Function &F);
60 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
61 Type *Ty, Value *BasePtr, int Idx1,
63 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
64 Type *Ty, Value *BasePtr, int Idx1, int Idx2,
69 INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, DEBUG_TYPE,
70 "Shadow Stack GC Lowering", false, false)
71 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
72 INITIALIZE_PASS_END(ShadowStackGCLowering, DEBUG_TYPE,
73 "Shadow Stack GC Lowering", false, false)
75 FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
77 char ShadowStackGCLowering::ID = 0;
79 ShadowStackGCLowering::ShadowStackGCLowering()
80 : FunctionPass(ID), Head(nullptr), StackEntryTy(nullptr),
82 initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
85 Constant *ShadowStackGCLowering::GetFrameMap(Function &F) {
86 // doInitialization creates the abstract type of this value.
87 Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
89 // Truncate the ShadowStackDescriptor if some metadata is null.
91 SmallVector<Constant *, 16> Metadata;
92 for (unsigned I = 0; I != Roots.size(); ++I) {
93 Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
94 if (!C->isNullValue())
96 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
98 Metadata.resize(NumMeta);
100 Type *Int32Ty = Type::getInt32Ty(F.getContext());
102 Constant *BaseElts[] = {
103 ConstantInt::get(Int32Ty, Roots.size(), false),
104 ConstantInt::get(Int32Ty, NumMeta, false),
107 Constant *DescriptorElts[] = {
108 ConstantStruct::get(FrameMapTy, BaseElts),
109 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
111 Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
112 StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
114 Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
116 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
117 // that, short of multithreaded LLVM, it should be safe; all that is
118 // necessary is that a simple Module::iterator loop not be invalidated.
119 // Appending to the GlobalVariable list is safe in that sense.
121 // All of the output passes emit globals last. The ExecutionEngine
122 // explicitly supports adding globals to the module after
125 // Still, if it isn't deemed acceptable, then this transformation needs
126 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
127 // (which uses a FunctionPassManager (which segfaults (not asserts) if
128 // provided a ModulePass))).
129 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
130 GlobalVariable::InternalLinkage, FrameMap,
131 "__gc_" + F.getName());
133 Constant *GEPIndices[2] = {
134 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
135 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
136 return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices);
139 Type *ShadowStackGCLowering::GetConcreteStackEntryType(Function &F) {
140 // doInitialization creates the generic version of this type.
141 std::vector<Type *> EltTys;
142 EltTys.push_back(StackEntryTy);
143 for (size_t I = 0; I != Roots.size(); I++)
144 EltTys.push_back(Roots[I].second->getAllocatedType());
146 return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str());
149 /// doInitialization - If this module uses the GC intrinsics, find them now. If
151 bool ShadowStackGCLowering::doInitialization(Module &M) {
153 for (Function &F : M) {
154 if (F.hasGC() && F.getGC() == std::string("shadow-stack")) {
163 // int32_t NumRoots; // Number of roots in stack frame.
164 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
165 // void *Meta[]; // May be absent for roots without metadata.
167 std::vector<Type *> EltTys;
168 // 32 bits is ok up to a 32GB stack frame. :)
169 EltTys.push_back(Type::getInt32Ty(M.getContext()));
170 // Specifies length of variable length array.
171 EltTys.push_back(Type::getInt32Ty(M.getContext()));
172 FrameMapTy = StructType::create(EltTys, "gc_map");
173 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
175 // struct StackEntry {
176 // ShadowStackEntry *Next; // Caller's stack entry.
177 // FrameMap *Map; // Pointer to constant FrameMap.
178 // void *Roots[]; // Stack roots (in-place array, so we pretend).
181 StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
184 EltTys.push_back(PointerType::getUnqual(StackEntryTy));
185 EltTys.push_back(FrameMapPtrTy);
186 StackEntryTy->setBody(EltTys);
187 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
189 // Get the root chain if it already exists.
190 Head = M.getGlobalVariable("llvm_gc_root_chain");
192 // If the root chain does not exist, insert a new one with linkonce
194 Head = new GlobalVariable(
195 M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
196 Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
197 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
198 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
199 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
205 bool ShadowStackGCLowering::IsNullValue(Value *V) {
206 if (Constant *C = dyn_cast<Constant>(V))
207 return C->isNullValue();
211 void ShadowStackGCLowering::CollectRoots(Function &F) {
212 // FIXME: Account for original alignment. Could fragment the root array.
213 // Approach 1: Null initialize empty slots at runtime. Yuck.
214 // Approach 2: Emit a map of the array instead of just a count.
216 assert(Roots.empty() && "Not cleaned up?");
218 SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
220 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
221 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
222 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
223 if (Function *F = CI->getCalledFunction())
224 if (F->getIntrinsicID() == Intrinsic::gcroot) {
225 std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
227 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
228 if (IsNullValue(CI->getArgOperand(1)))
229 Roots.push_back(Pair);
231 MetaRoots.push_back(Pair);
234 // Number roots with metadata (usually empty) at the beginning, so that the
235 // FrameMap::Meta array can be elided.
236 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
239 GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
240 IRBuilder<> &B, Type *Ty,
241 Value *BasePtr, int Idx,
244 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
245 ConstantInt::get(Type::getInt32Ty(Context), Idx),
246 ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
247 Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
249 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
251 return dyn_cast<GetElementPtrInst>(Val);
254 GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
255 IRBuilder<> &B, Type *Ty, Value *BasePtr,
256 int Idx, const char *Name) {
257 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
258 ConstantInt::get(Type::getInt32Ty(Context), Idx)};
259 Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
261 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
263 return dyn_cast<GetElementPtrInst>(Val);
266 /// runOnFunction - Insert code to maintain the shadow stack.
267 bool ShadowStackGCLowering::runOnFunction(Function &F) {
268 // Quick exit for functions that do not use the shadow stack GC.
270 F.getGC() != std::string("shadow-stack"))
273 LLVMContext &Context = F.getContext();
275 // Find calls to llvm.gcroot.
278 // If there are no roots in this function, then there is no need to add a
279 // stack map entry for it.
283 // Build the constant map and figure the type of the shadow stack entry.
284 Value *FrameMap = GetFrameMap(F);
285 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
287 // Build the shadow stack entry at the very start of the function.
288 BasicBlock::iterator IP = F.getEntryBlock().begin();
289 IRBuilder<> AtEntry(IP->getParent(), IP);
291 Instruction *StackEntry =
292 AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
294 while (isa<AllocaInst>(IP))
296 AtEntry.SetInsertPoint(IP->getParent(), IP);
298 // Initialize the map pointer and load the current head of the shadow stack.
299 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
300 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
301 StackEntry, 0, 1, "gc_frame.map");
302 AtEntry.CreateStore(FrameMap, EntryMapPtr);
304 // After all the allocas...
305 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
306 // For each root, find the corresponding slot in the aggregate...
307 Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
308 StackEntry, 1 + I, "gc_root");
310 // And use it in lieu of the alloca.
311 AllocaInst *OriginalAlloca = Roots[I].second;
312 SlotPtr->takeName(OriginalAlloca);
313 OriginalAlloca->replaceAllUsesWith(SlotPtr);
316 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
317 // really necessary (the collector would never see the intermediate state at
318 // runtime), but it's nicer not to push the half-initialized entry onto the
320 while (isa<StoreInst>(IP))
322 AtEntry.SetInsertPoint(IP->getParent(), IP);
324 // Push the entry onto the shadow stack.
325 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
326 StackEntry, 0, 0, "gc_frame.next");
327 Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
328 StackEntry, 0, "gc_newhead");
329 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
330 AtEntry.CreateStore(NewHeadVal, Head);
332 // For each instruction that escapes...
333 EscapeEnumerator EE(F, "gc_cleanup");
334 while (IRBuilder<> *AtExit = EE.Next()) {
335 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
336 // AtEntry, since that would make the value live for the entire function.
337 Instruction *EntryNextPtr2 =
338 CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
340 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
341 AtExit->CreateStore(SavedHead, Head);
344 // Delete the original allocas (which are no longer used) and the intrinsic
345 // calls (which are no longer valid). Doing this last avoids invalidating
347 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
348 Roots[I].first->eraseFromParent();
349 Roots[I].second->eraseFromParent();