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 #define DEBUG_TYPE "shadowstackgc"
29 #include "llvm/CodeGen/GCs.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/CodeGen/GCStrategy.h"
32 #include "llvm/IntrinsicInst.h"
33 #include "llvm/Module.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/IRBuilder.h"
41 class ShadowStackGC
: public GCStrategy
{
42 /// RootChain - This is the global linked-list that contains the chain of GC
46 /// StackEntryTy - Abstract type of a link in the shadow stack.
48 StructType
*StackEntryTy
;
49 StructType
*FrameMapTy
;
51 /// Roots - GC roots in the current function. Each is a pair of the
52 /// intrinsic call and its corresponding alloca.
53 std::vector
<std::pair
<CallInst
*,AllocaInst
*> > Roots
;
58 bool initializeCustomLowering(Module
&M
);
59 bool performCustomLowering(Function
&F
);
62 bool IsNullValue(Value
*V
);
63 Constant
*GetFrameMap(Function
&F
);
64 const Type
* GetConcreteStackEntryType(Function
&F
);
65 void CollectRoots(Function
&F
);
66 static GetElementPtrInst
*CreateGEP(LLVMContext
&Context
,
67 IRBuilder
<> &B
, Value
*BasePtr
,
68 int Idx1
, const char *Name
);
69 static GetElementPtrInst
*CreateGEP(LLVMContext
&Context
,
70 IRBuilder
<> &B
, Value
*BasePtr
,
71 int Idx1
, int Idx2
, const char *Name
);
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' and 'unwind' instructions.
113 while (StateBB
!= StateE
) {
114 BasicBlock
*CurBB
= StateBB
++;
116 // Branches and invokes do not escape, only unwind and return do.
117 TerminatorInst
*TI
= CurBB
->getTerminator();
118 if (!isa
<UnwindInst
>(TI
) && !isa
<ReturnInst
>(TI
))
121 Builder
.SetInsertPoint(TI
->getParent(), TI
);
127 // Find all 'call' instructions.
128 SmallVector
<Instruction
*,16> Calls
;
129 for (Function::iterator BB
= F
.begin(),
130 E
= F
.end(); BB
!= E
; ++BB
)
131 for (BasicBlock::iterator II
= BB
->begin(),
132 EE
= BB
->end(); II
!= EE
; ++II
)
133 if (CallInst
*CI
= dyn_cast
<CallInst
>(II
))
134 if (!CI
->getCalledFunction() ||
135 !CI
->getCalledFunction()->getIntrinsicID())
141 // Create a cleanup block.
142 BasicBlock
*CleanupBB
= BasicBlock::Create(F
.getContext(),
144 UnwindInst
*UI
= new UnwindInst(F
.getContext(), CleanupBB
);
146 // Transform the 'call' instructions into 'invoke's branching to the
147 // cleanup block. Go in reverse order to make prettier BB names.
148 SmallVector
<Value
*,16> Args
;
149 for (unsigned I
= Calls
.size(); I
!= 0; ) {
150 CallInst
*CI
= cast
<CallInst
>(Calls
[--I
]);
152 // Split the basic block containing the function call.
153 BasicBlock
*CallBB
= CI
->getParent();
155 CallBB
->splitBasicBlock(CI
, CallBB
->getName() + ".cont");
157 // Remove the unconditional branch inserted at the end of CallBB.
158 CallBB
->getInstList().pop_back();
159 NewBB
->getInstList().remove(CI
);
161 // Create a new invoke instruction.
164 Args
.append(CS
.arg_begin(), CS
.arg_end());
166 InvokeInst
*II
= InvokeInst::Create(CI
->getCalledValue(),
168 Args
.begin(), Args
.end(),
169 CI
->getName(), CallBB
);
170 II
->setCallingConv(CI
->getCallingConv());
171 II
->setAttributes(CI
->getAttributes());
172 CI
->replaceAllUsesWith(II
);
176 Builder
.SetInsertPoint(UI
->getParent(), UI
);
183 // -----------------------------------------------------------------------------
185 void llvm::linkShadowStackGC() { }
187 ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
192 Constant
*ShadowStackGC::GetFrameMap(Function
&F
) {
193 // doInitialization creates the abstract type of this value.
194 const Type
*VoidPtr
= Type::getInt8PtrTy(F
.getContext());
196 // Truncate the ShadowStackDescriptor if some metadata is null.
197 unsigned NumMeta
= 0;
198 SmallVector
<Constant
*, 16> Metadata
;
199 for (unsigned I
= 0; I
!= Roots
.size(); ++I
) {
200 Constant
*C
= cast
<Constant
>(Roots
[I
].first
->getArgOperand(1));
201 if (!C
->isNullValue())
203 Metadata
.push_back(ConstantExpr::getBitCast(C
, VoidPtr
));
205 Metadata
.resize(NumMeta
);
207 const Type
*Int32Ty
= Type::getInt32Ty(F
.getContext());
209 Constant
*BaseElts
[] = {
210 ConstantInt::get(Int32Ty
, Roots
.size(), false),
211 ConstantInt::get(Int32Ty
, NumMeta
, false),
214 Constant
*DescriptorElts
[] = {
215 ConstantStruct::get(FrameMapTy
, BaseElts
),
216 ConstantArray::get(ArrayType::get(VoidPtr
, NumMeta
), Metadata
)
219 Type
*EltTys
[] = { DescriptorElts
[0]->getType(),DescriptorElts
[1]->getType()};
220 StructType
*STy
= StructType::createNamed("gc_map."+utostr(NumMeta
), EltTys
);
222 Constant
*FrameMap
= ConstantStruct::get(STy
, DescriptorElts
);
224 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
225 // that, short of multithreaded LLVM, it should be safe; all that is
226 // necessary is that a simple Module::iterator loop not be invalidated.
227 // Appending to the GlobalVariable list is safe in that sense.
229 // All of the output passes emit globals last. The ExecutionEngine
230 // explicitly supports adding globals to the module after
233 // Still, if it isn't deemed acceptable, then this transformation needs
234 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
235 // (which uses a FunctionPassManager (which segfaults (not asserts) if
236 // provided a ModulePass))).
237 Constant
*GV
= new GlobalVariable(*F
.getParent(), FrameMap
->getType(), true,
238 GlobalVariable::InternalLinkage
,
239 FrameMap
, "__gc_" + F
.getName());
241 Constant
*GEPIndices
[2] = {
242 ConstantInt::get(Type::getInt32Ty(F
.getContext()), 0),
243 ConstantInt::get(Type::getInt32Ty(F
.getContext()), 0)
245 return ConstantExpr::getGetElementPtr(GV
, GEPIndices
, 2);
248 const Type
* ShadowStackGC::GetConcreteStackEntryType(Function
&F
) {
249 // doInitialization creates the generic version of this type.
250 std::vector
<Type
*> EltTys
;
251 EltTys
.push_back(StackEntryTy
);
252 for (size_t I
= 0; I
!= Roots
.size(); I
++)
253 EltTys
.push_back(Roots
[I
].second
->getAllocatedType());
255 return StructType::createNamed("gc_stackentry."+F
.getName().str(), EltTys
);
258 /// doInitialization - If this module uses the GC intrinsics, find them now. If
260 bool ShadowStackGC::initializeCustomLowering(Module
&M
) {
262 // int32_t NumRoots; // Number of roots in stack frame.
263 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
264 // void *Meta[]; // May be absent for roots without metadata.
266 std::vector
<Type
*> EltTys
;
267 // 32 bits is ok up to a 32GB stack frame. :)
268 EltTys
.push_back(Type::getInt32Ty(M
.getContext()));
269 // Specifies length of variable length array.
270 EltTys
.push_back(Type::getInt32Ty(M
.getContext()));
271 FrameMapTy
= StructType::createNamed("gc_map", EltTys
);
272 PointerType
*FrameMapPtrTy
= PointerType::getUnqual(FrameMapTy
);
274 // struct StackEntry {
275 // ShadowStackEntry *Next; // Caller's stack entry.
276 // FrameMap *Map; // Pointer to constant FrameMap.
277 // void *Roots[]; // Stack roots (in-place array, so we pretend).
280 StackEntryTy
= StructType::createNamed(M
.getContext(), "gc_stackentry");
283 EltTys
.push_back(PointerType::getUnqual(StackEntryTy
));
284 EltTys
.push_back(FrameMapPtrTy
);
285 StackEntryTy
->setBody(EltTys
);
286 const PointerType
*StackEntryPtrTy
= PointerType::getUnqual(StackEntryTy
);
288 // Get the root chain if it already exists.
289 Head
= M
.getGlobalVariable("llvm_gc_root_chain");
291 // If the root chain does not exist, insert a new one with linkonce
293 Head
= new GlobalVariable(M
, StackEntryPtrTy
, false,
294 GlobalValue::LinkOnceAnyLinkage
,
295 Constant::getNullValue(StackEntryPtrTy
),
296 "llvm_gc_root_chain");
297 } else if (Head
->hasExternalLinkage() && Head
->isDeclaration()) {
298 Head
->setInitializer(Constant::getNullValue(StackEntryPtrTy
));
299 Head
->setLinkage(GlobalValue::LinkOnceAnyLinkage
);
305 bool ShadowStackGC::IsNullValue(Value
*V
) {
306 if (Constant
*C
= dyn_cast
<Constant
>(V
))
307 return C
->isNullValue();
311 void ShadowStackGC::CollectRoots(Function
&F
) {
312 // FIXME: Account for original alignment. Could fragment the root array.
313 // Approach 1: Null initialize empty slots at runtime. Yuck.
314 // Approach 2: Emit a map of the array instead of just a count.
316 assert(Roots
.empty() && "Not cleaned up?");
318 SmallVector
<std::pair
<CallInst
*, AllocaInst
*>, 16> MetaRoots
;
320 for (Function::iterator BB
= F
.begin(), E
= F
.end(); BB
!= E
; ++BB
)
321 for (BasicBlock::iterator II
= BB
->begin(), E
= BB
->end(); II
!= E
;)
322 if (IntrinsicInst
*CI
= dyn_cast
<IntrinsicInst
>(II
++))
323 if (Function
*F
= CI
->getCalledFunction())
324 if (F
->getIntrinsicID() == Intrinsic::gcroot
) {
325 std::pair
<CallInst
*, AllocaInst
*> Pair
= std::make_pair(
326 CI
, cast
<AllocaInst
>(CI
->getArgOperand(0)->stripPointerCasts()));
327 if (IsNullValue(CI
->getArgOperand(1)))
328 Roots
.push_back(Pair
);
330 MetaRoots
.push_back(Pair
);
333 // Number roots with metadata (usually empty) at the beginning, so that the
334 // FrameMap::Meta array can be elided.
335 Roots
.insert(Roots
.begin(), MetaRoots
.begin(), MetaRoots
.end());
339 ShadowStackGC::CreateGEP(LLVMContext
&Context
, IRBuilder
<> &B
, Value
*BasePtr
,
340 int Idx
, int Idx2
, const char *Name
) {
341 Value
*Indices
[] = { ConstantInt::get(Type::getInt32Ty(Context
), 0),
342 ConstantInt::get(Type::getInt32Ty(Context
), Idx
),
343 ConstantInt::get(Type::getInt32Ty(Context
), Idx2
) };
344 Value
* Val
= B
.CreateGEP(BasePtr
, Indices
, Indices
+ 3, Name
);
346 assert(isa
<GetElementPtrInst
>(Val
) && "Unexpected folded constant");
348 return dyn_cast
<GetElementPtrInst
>(Val
);
352 ShadowStackGC::CreateGEP(LLVMContext
&Context
, IRBuilder
<> &B
, Value
*BasePtr
,
353 int Idx
, const char *Name
) {
354 Value
*Indices
[] = { ConstantInt::get(Type::getInt32Ty(Context
), 0),
355 ConstantInt::get(Type::getInt32Ty(Context
), Idx
) };
356 Value
*Val
= B
.CreateGEP(BasePtr
, Indices
, Indices
+ 2, Name
);
358 assert(isa
<GetElementPtrInst
>(Val
) && "Unexpected folded constant");
360 return dyn_cast
<GetElementPtrInst
>(Val
);
363 /// runOnFunction - Insert code to maintain the shadow stack.
364 bool ShadowStackGC::performCustomLowering(Function
&F
) {
365 LLVMContext
&Context
= F
.getContext();
367 // Find calls to llvm.gcroot.
370 // If there are no roots in this function, then there is no need to add a
371 // stack map entry for it.
375 // Build the constant map and figure the type of the shadow stack entry.
376 Value
*FrameMap
= GetFrameMap(F
);
377 const Type
*ConcreteStackEntryTy
= GetConcreteStackEntryType(F
);
379 // Build the shadow stack entry at the very start of the function.
380 BasicBlock::iterator IP
= F
.getEntryBlock().begin();
381 IRBuilder
<> AtEntry(IP
->getParent(), IP
);
383 Instruction
*StackEntry
= AtEntry
.CreateAlloca(ConcreteStackEntryTy
, 0,
386 while (isa
<AllocaInst
>(IP
)) ++IP
;
387 AtEntry
.SetInsertPoint(IP
->getParent(), IP
);
389 // Initialize the map pointer and load the current head of the shadow stack.
390 Instruction
*CurrentHead
= AtEntry
.CreateLoad(Head
, "gc_currhead");
391 Instruction
*EntryMapPtr
= CreateGEP(Context
, AtEntry
, StackEntry
,
393 AtEntry
.CreateStore(FrameMap
, EntryMapPtr
);
395 // After all the allocas...
396 for (unsigned I
= 0, E
= Roots
.size(); I
!= E
; ++I
) {
397 // For each root, find the corresponding slot in the aggregate...
398 Value
*SlotPtr
= CreateGEP(Context
, AtEntry
, StackEntry
, 1 + I
, "gc_root");
400 // And use it in lieu of the alloca.
401 AllocaInst
*OriginalAlloca
= Roots
[I
].second
;
402 SlotPtr
->takeName(OriginalAlloca
);
403 OriginalAlloca
->replaceAllUsesWith(SlotPtr
);
406 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
407 // really necessary (the collector would never see the intermediate state at
408 // runtime), but it's nicer not to push the half-initialized entry onto the
410 while (isa
<StoreInst
>(IP
)) ++IP
;
411 AtEntry
.SetInsertPoint(IP
->getParent(), IP
);
413 // Push the entry onto the shadow stack.
414 Instruction
*EntryNextPtr
= CreateGEP(Context
, AtEntry
,
415 StackEntry
,0,0,"gc_frame.next");
416 Instruction
*NewHeadVal
= CreateGEP(Context
, AtEntry
,
417 StackEntry
, 0, "gc_newhead");
418 AtEntry
.CreateStore(CurrentHead
, EntryNextPtr
);
419 AtEntry
.CreateStore(NewHeadVal
, Head
);
421 // For each instruction that escapes...
422 EscapeEnumerator
EE(F
, "gc_cleanup");
423 while (IRBuilder
<> *AtExit
= EE
.Next()) {
424 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
425 // AtEntry, since that would make the value live for the entire function.
426 Instruction
*EntryNextPtr2
= CreateGEP(Context
, *AtExit
, StackEntry
, 0, 0,
428 Value
*SavedHead
= AtExit
->CreateLoad(EntryNextPtr2
, "gc_savedhead");
429 AtExit
->CreateStore(SavedHead
, Head
);
432 // Delete the original allocas (which are no longer used) and the intrinsic
433 // calls (which are no longer valid). Doing this last avoids invalidating
435 for (unsigned I
= 0, E
= Roots
.size(); I
!= E
; ++I
) {
436 Roots
[I
].first
->eraseFromParent();
437 Roots
[I
].second
->eraseFromParent();