1 //===-- ShadowStackGC.cpp - GC support for uncooperative targets ----------===//
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 implements lowering for the llvm.gc* intrinsics for targets that do
11 // not natively support them (which includes the C backend). Note that the code
12 // generated is not quite as efficient as algorithms which generate stack maps
15 // This pass implements the code transformation described in this paper:
16 // "Accurate Garbage Collection in an Uncooperative Environment"
17 // Fergus Henderson, ISMM, 2002
19 // In runtime/GC/SemiSpace.cpp is a prototype runtime which is compatible with
22 // In order to support this particular transformation, all stack roots are
23 // coallocated in the stack. This allows a fully target-independent stack map
24 // while introducing only minor runtime overhead.
26 //===----------------------------------------------------------------------===//
28 #include "llvm/CodeGen/GCs.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/GCStrategy.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
38 #define DEBUG_TYPE "shadowstackgc"
42 class ShadowStackGC : public GCStrategy {
43 /// RootChain - This is the global linked-list that contains the chain of GC
47 /// StackEntryTy - Abstract type of a link in the shadow stack.
49 StructType *StackEntryTy;
50 StructType *FrameMapTy;
52 /// Roots - GC roots in the current function. Each is a pair of the
53 /// intrinsic call and its corresponding alloca.
54 std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
59 bool initializeCustomLowering(Module &M) override;
60 bool performCustomLowering(Function &F) override;
63 bool IsNullValue(Value *V);
64 Constant *GetFrameMap(Function &F);
65 Type *GetConcreteStackEntryType(Function &F);
66 void CollectRoots(Function &F);
67 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
68 Value *BasePtr, int Idx1,
70 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
71 Value *BasePtr, int Idx1, int Idx2,
76 static GCRegistry::Add<ShadowStackGC>
77 X("shadow-stack", "Very portable GC for uncooperative code generators");
80 /// EscapeEnumerator - This is a little algorithm to find all escape points
81 /// from a function so that "finally"-style code can be inserted. In addition
82 /// to finding the existing return and unwind instructions, it also (if
83 /// necessary) transforms any call instructions into invokes and sends them to
86 /// It's wrapped up in a state machine using the same transform C# uses for
87 /// 'yield return' enumerators, This transform allows it to be non-allocating.
88 class EscapeEnumerator {
90 const char *CleanupBBName;
94 Function::iterator StateBB, StateE;
98 EscapeEnumerator(Function &F, const char *N = "cleanup")
99 : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
101 IRBuilder<> *Next() {
112 // Find all 'return', 'resume', and 'unwind' instructions.
113 while (StateBB != StateE) {
114 BasicBlock *CurBB = StateBB++;
116 // Branches and invokes do not escape, only unwind, resume, and return
118 TerminatorInst *TI = CurBB->getTerminator();
119 if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI))
122 Builder.SetInsertPoint(TI->getParent(), TI);
128 // Find all 'call' instructions.
129 SmallVector<Instruction *, 16> Calls;
130 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
131 for (BasicBlock::iterator II = BB->begin(), EE = BB->end(); II != EE;
133 if (CallInst *CI = dyn_cast<CallInst>(II))
134 if (!CI->getCalledFunction() ||
135 !CI->getCalledFunction()->getIntrinsicID())
141 // Create a cleanup block.
142 LLVMContext &C = F.getContext();
143 BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F);
145 StructType::get(Type::getInt8PtrTy(C), Type::getInt32Ty(C), nullptr);
146 Constant *PersFn = F.getParent()->getOrInsertFunction(
147 "__gcc_personality_v0", FunctionType::get(Type::getInt32Ty(C), true));
148 LandingPadInst *LPad =
149 LandingPadInst::Create(ExnTy, PersFn, 1, "cleanup.lpad", CleanupBB);
150 LPad->setCleanup(true);
151 ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB);
153 // Transform the 'call' instructions into 'invoke's branching to the
154 // cleanup block. Go in reverse order to make prettier BB names.
155 SmallVector<Value *, 16> Args;
156 for (unsigned I = Calls.size(); I != 0;) {
157 CallInst *CI = cast<CallInst>(Calls[--I]);
159 // Split the basic block containing the function call.
160 BasicBlock *CallBB = CI->getParent();
162 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
164 // Remove the unconditional branch inserted at the end of CallBB.
165 CallBB->getInstList().pop_back();
166 NewBB->getInstList().remove(CI);
168 // Create a new invoke instruction.
171 Args.append(CS.arg_begin(), CS.arg_end());
174 InvokeInst::Create(CI->getCalledValue(), NewBB, CleanupBB, Args,
175 CI->getName(), CallBB);
176 II->setCallingConv(CI->getCallingConv());
177 II->setAttributes(CI->getAttributes());
178 CI->replaceAllUsesWith(II);
182 Builder.SetInsertPoint(RI->getParent(), RI);
189 // -----------------------------------------------------------------------------
191 void llvm::linkShadowStackGC() {}
193 ShadowStackGC::ShadowStackGC() : Head(nullptr), StackEntryTy(nullptr) {
198 Constant *ShadowStackGC::GetFrameMap(Function &F) {
199 // doInitialization creates the abstract type of this value.
200 Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
202 // Truncate the ShadowStackDescriptor if some metadata is null.
203 unsigned NumMeta = 0;
204 SmallVector<Constant *, 16> Metadata;
205 for (unsigned I = 0; I != Roots.size(); ++I) {
206 Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
207 if (!C->isNullValue())
209 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
211 Metadata.resize(NumMeta);
213 Type *Int32Ty = Type::getInt32Ty(F.getContext());
215 Constant *BaseElts[] = {
216 ConstantInt::get(Int32Ty, Roots.size(), false),
217 ConstantInt::get(Int32Ty, NumMeta, false),
220 Constant *DescriptorElts[] = {
221 ConstantStruct::get(FrameMapTy, BaseElts),
222 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
224 Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
225 StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
227 Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
229 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
230 // that, short of multithreaded LLVM, it should be safe; all that is
231 // necessary is that a simple Module::iterator loop not be invalidated.
232 // Appending to the GlobalVariable list is safe in that sense.
234 // All of the output passes emit globals last. The ExecutionEngine
235 // explicitly supports adding globals to the module after
238 // Still, if it isn't deemed acceptable, then this transformation needs
239 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
240 // (which uses a FunctionPassManager (which segfaults (not asserts) if
241 // provided a ModulePass))).
242 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
243 GlobalVariable::InternalLinkage, FrameMap,
244 "__gc_" + F.getName());
246 Constant *GEPIndices[2] = {
247 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
248 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
249 return ConstantExpr::getGetElementPtr(GV, GEPIndices);
252 Type *ShadowStackGC::GetConcreteStackEntryType(Function &F) {
253 // doInitialization creates the generic version of this type.
254 std::vector<Type *> EltTys;
255 EltTys.push_back(StackEntryTy);
256 for (size_t I = 0; I != Roots.size(); I++)
257 EltTys.push_back(Roots[I].second->getAllocatedType());
259 return StructType::create(EltTys, "gc_stackentry." + F.getName().str());
262 /// doInitialization - If this module uses the GC intrinsics, find them now. If
264 bool ShadowStackGC::initializeCustomLowering(Module &M) {
266 // int32_t NumRoots; // Number of roots in stack frame.
267 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
268 // void *Meta[]; // May be absent for roots without metadata.
270 std::vector<Type *> EltTys;
271 // 32 bits is ok up to a 32GB stack frame. :)
272 EltTys.push_back(Type::getInt32Ty(M.getContext()));
273 // Specifies length of variable length array.
274 EltTys.push_back(Type::getInt32Ty(M.getContext()));
275 FrameMapTy = StructType::create(EltTys, "gc_map");
276 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
278 // struct StackEntry {
279 // ShadowStackEntry *Next; // Caller's stack entry.
280 // FrameMap *Map; // Pointer to constant FrameMap.
281 // void *Roots[]; // Stack roots (in-place array, so we pretend).
284 StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
287 EltTys.push_back(PointerType::getUnqual(StackEntryTy));
288 EltTys.push_back(FrameMapPtrTy);
289 StackEntryTy->setBody(EltTys);
290 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
292 // Get the root chain if it already exists.
293 Head = M.getGlobalVariable("llvm_gc_root_chain");
295 // If the root chain does not exist, insert a new one with linkonce
297 Head = new GlobalVariable(
298 M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
299 Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
300 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
301 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
302 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
308 bool ShadowStackGC::IsNullValue(Value *V) {
309 if (Constant *C = dyn_cast<Constant>(V))
310 return C->isNullValue();
314 void ShadowStackGC::CollectRoots(Function &F) {
315 // FIXME: Account for original alignment. Could fragment the root array.
316 // Approach 1: Null initialize empty slots at runtime. Yuck.
317 // Approach 2: Emit a map of the array instead of just a count.
319 assert(Roots.empty() && "Not cleaned up?");
321 SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
323 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
324 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
325 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
326 if (Function *F = CI->getCalledFunction())
327 if (F->getIntrinsicID() == Intrinsic::gcroot) {
328 std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
330 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
331 if (IsNullValue(CI->getArgOperand(1)))
332 Roots.push_back(Pair);
334 MetaRoots.push_back(Pair);
337 // Number roots with metadata (usually empty) at the beginning, so that the
338 // FrameMap::Meta array can be elided.
339 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
342 GetElementPtrInst *ShadowStackGC::CreateGEP(LLVMContext &Context,
343 IRBuilder<> &B, Value *BasePtr,
346 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
347 ConstantInt::get(Type::getInt32Ty(Context), Idx),
348 ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
349 Value *Val = B.CreateGEP(BasePtr, Indices, Name);
351 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
353 return dyn_cast<GetElementPtrInst>(Val);
356 GetElementPtrInst *ShadowStackGC::CreateGEP(LLVMContext &Context,
357 IRBuilder<> &B, Value *BasePtr,
358 int Idx, const char *Name) {
359 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
360 ConstantInt::get(Type::getInt32Ty(Context), Idx)};
361 Value *Val = B.CreateGEP(BasePtr, Indices, Name);
363 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
365 return dyn_cast<GetElementPtrInst>(Val);
368 /// runOnFunction - Insert code to maintain the shadow stack.
369 bool ShadowStackGC::performCustomLowering(Function &F) {
370 LLVMContext &Context = F.getContext();
372 // Find calls to llvm.gcroot.
375 // If there are no roots in this function, then there is no need to add a
376 // stack map entry for it.
380 // Build the constant map and figure the type of the shadow stack entry.
381 Value *FrameMap = GetFrameMap(F);
382 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
384 // Build the shadow stack entry at the very start of the function.
385 BasicBlock::iterator IP = F.getEntryBlock().begin();
386 IRBuilder<> AtEntry(IP->getParent(), IP);
388 Instruction *StackEntry =
389 AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
391 while (isa<AllocaInst>(IP))
393 AtEntry.SetInsertPoint(IP->getParent(), IP);
395 // Initialize the map pointer and load the current head of the shadow stack.
396 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
397 Instruction *EntryMapPtr =
398 CreateGEP(Context, AtEntry, StackEntry, 0, 1, "gc_frame.map");
399 AtEntry.CreateStore(FrameMap, EntryMapPtr);
401 // After all the allocas...
402 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
403 // For each root, find the corresponding slot in the aggregate...
404 Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root");
406 // And use it in lieu of the alloca.
407 AllocaInst *OriginalAlloca = Roots[I].second;
408 SlotPtr->takeName(OriginalAlloca);
409 OriginalAlloca->replaceAllUsesWith(SlotPtr);
412 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
413 // really necessary (the collector would never see the intermediate state at
414 // runtime), but it's nicer not to push the half-initialized entry onto the
416 while (isa<StoreInst>(IP))
418 AtEntry.SetInsertPoint(IP->getParent(), IP);
420 // Push the entry onto the shadow stack.
421 Instruction *EntryNextPtr =
422 CreateGEP(Context, AtEntry, StackEntry, 0, 0, "gc_frame.next");
423 Instruction *NewHeadVal =
424 CreateGEP(Context, AtEntry, StackEntry, 0, "gc_newhead");
425 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
426 AtEntry.CreateStore(NewHeadVal, Head);
428 // For each instruction that escapes...
429 EscapeEnumerator EE(F, "gc_cleanup");
430 while (IRBuilder<> *AtExit = EE.Next()) {
431 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
432 // AtEntry, since that would make the value live for the entire function.
433 Instruction *EntryNextPtr2 =
434 CreateGEP(Context, *AtExit, StackEntry, 0, 0, "gc_frame.next");
435 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
436 AtExit->CreateStore(SavedHead, Head);
439 // Delete the original allocas (which are no longer used) and the intrinsic
440 // calls (which are no longer valid). Doing this last avoids invalidating
442 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
443 Roots[I].first->eraseFromParent();
444 Roots[I].second->eraseFromParent();