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/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
47 #define DEBUG_TYPE "shadow-stack-gc-lowering"
51 class ShadowStackGCLowering
: public FunctionPass
{
52 /// RootChain - This is the global linked-list that contains the chain of GC
54 GlobalVariable
*Head
= nullptr;
56 /// StackEntryTy - Abstract type of a link in the shadow stack.
57 StructType
*StackEntryTy
= nullptr;
58 StructType
*FrameMapTy
= nullptr;
60 /// Roots - GC roots in the current function. Each is a pair of the
61 /// intrinsic call and its corresponding alloca.
62 std::vector
<std::pair
<CallInst
*, AllocaInst
*>> Roots
;
67 ShadowStackGCLowering();
69 bool doInitialization(Module
&M
) override
;
70 bool runOnFunction(Function
&F
) override
;
73 bool IsNullValue(Value
*V
);
74 Constant
*GetFrameMap(Function
&F
);
75 Type
*GetConcreteStackEntryType(Function
&F
);
76 void CollectRoots(Function
&F
);
78 static GetElementPtrInst
*CreateGEP(LLVMContext
&Context
, IRBuilder
<> &B
,
79 Type
*Ty
, Value
*BasePtr
, int Idx1
,
81 static GetElementPtrInst
*CreateGEP(LLVMContext
&Context
, IRBuilder
<> &B
,
82 Type
*Ty
, Value
*BasePtr
, int Idx1
, int Idx2
,
86 } // end anonymous namespace
88 char ShadowStackGCLowering::ID
= 0;
90 INITIALIZE_PASS_BEGIN(ShadowStackGCLowering
, DEBUG_TYPE
,
91 "Shadow Stack GC Lowering", false, false)
92 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo
)
93 INITIALIZE_PASS_END(ShadowStackGCLowering
, DEBUG_TYPE
,
94 "Shadow Stack GC Lowering", false, false)
96 FunctionPass
*llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
98 ShadowStackGCLowering::ShadowStackGCLowering() : FunctionPass(ID
) {
99 initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
102 Constant
*ShadowStackGCLowering::GetFrameMap(Function
&F
) {
103 // doInitialization creates the abstract type of this value.
104 Type
*VoidPtr
= Type::getInt8PtrTy(F
.getContext());
106 // Truncate the ShadowStackDescriptor if some metadata is null.
107 unsigned NumMeta
= 0;
108 SmallVector
<Constant
*, 16> Metadata
;
109 for (unsigned I
= 0; I
!= Roots
.size(); ++I
) {
110 Constant
*C
= cast
<Constant
>(Roots
[I
].first
->getArgOperand(1));
111 if (!C
->isNullValue())
113 Metadata
.push_back(ConstantExpr::getBitCast(C
, VoidPtr
));
115 Metadata
.resize(NumMeta
);
117 Type
*Int32Ty
= Type::getInt32Ty(F
.getContext());
119 Constant
*BaseElts
[] = {
120 ConstantInt::get(Int32Ty
, Roots
.size(), false),
121 ConstantInt::get(Int32Ty
, NumMeta
, false),
124 Constant
*DescriptorElts
[] = {
125 ConstantStruct::get(FrameMapTy
, BaseElts
),
126 ConstantArray::get(ArrayType::get(VoidPtr
, NumMeta
), Metadata
)};
128 Type
*EltTys
[] = {DescriptorElts
[0]->getType(), DescriptorElts
[1]->getType()};
129 StructType
*STy
= StructType::create(EltTys
, "gc_map." + utostr(NumMeta
));
131 Constant
*FrameMap
= ConstantStruct::get(STy
, DescriptorElts
);
133 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
134 // that, short of multithreaded LLVM, it should be safe; all that is
135 // necessary is that a simple Module::iterator loop not be invalidated.
136 // Appending to the GlobalVariable list is safe in that sense.
138 // All of the output passes emit globals last. The ExecutionEngine
139 // explicitly supports adding globals to the module after
142 // Still, if it isn't deemed acceptable, then this transformation needs
143 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
144 // (which uses a FunctionPassManager (which segfaults (not asserts) if
145 // provided a ModulePass))).
146 Constant
*GV
= new GlobalVariable(*F
.getParent(), FrameMap
->getType(), true,
147 GlobalVariable::InternalLinkage
, FrameMap
,
148 "__gc_" + F
.getName());
150 Constant
*GEPIndices
[2] = {
151 ConstantInt::get(Type::getInt32Ty(F
.getContext()), 0),
152 ConstantInt::get(Type::getInt32Ty(F
.getContext()), 0)};
153 return ConstantExpr::getGetElementPtr(FrameMap
->getType(), GV
, GEPIndices
);
156 Type
*ShadowStackGCLowering::GetConcreteStackEntryType(Function
&F
) {
157 // doInitialization creates the generic version of this type.
158 std::vector
<Type
*> EltTys
;
159 EltTys
.push_back(StackEntryTy
);
160 for (size_t I
= 0; I
!= Roots
.size(); I
++)
161 EltTys
.push_back(Roots
[I
].second
->getAllocatedType());
163 return StructType::create(EltTys
, ("gc_stackentry." + F
.getName()).str());
166 /// doInitialization - If this module uses the GC intrinsics, find them now. If
168 bool ShadowStackGCLowering::doInitialization(Module
&M
) {
170 for (Function
&F
: M
) {
171 if (F
.hasGC() && F
.getGC() == std::string("shadow-stack")) {
180 // int32_t NumRoots; // Number of roots in stack frame.
181 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
182 // void *Meta[]; // May be absent for roots without metadata.
184 std::vector
<Type
*> EltTys
;
185 // 32 bits is ok up to a 32GB stack frame. :)
186 EltTys
.push_back(Type::getInt32Ty(M
.getContext()));
187 // Specifies length of variable length array.
188 EltTys
.push_back(Type::getInt32Ty(M
.getContext()));
189 FrameMapTy
= StructType::create(EltTys
, "gc_map");
190 PointerType
*FrameMapPtrTy
= PointerType::getUnqual(FrameMapTy
);
192 // struct StackEntry {
193 // ShadowStackEntry *Next; // Caller's stack entry.
194 // FrameMap *Map; // Pointer to constant FrameMap.
195 // void *Roots[]; // Stack roots (in-place array, so we pretend).
198 StackEntryTy
= StructType::create(M
.getContext(), "gc_stackentry");
201 EltTys
.push_back(PointerType::getUnqual(StackEntryTy
));
202 EltTys
.push_back(FrameMapPtrTy
);
203 StackEntryTy
->setBody(EltTys
);
204 PointerType
*StackEntryPtrTy
= PointerType::getUnqual(StackEntryTy
);
206 // Get the root chain if it already exists.
207 Head
= M
.getGlobalVariable("llvm_gc_root_chain");
209 // If the root chain does not exist, insert a new one with linkonce
211 Head
= new GlobalVariable(
212 M
, StackEntryPtrTy
, false, GlobalValue::LinkOnceAnyLinkage
,
213 Constant::getNullValue(StackEntryPtrTy
), "llvm_gc_root_chain");
214 } else if (Head
->hasExternalLinkage() && Head
->isDeclaration()) {
215 Head
->setInitializer(Constant::getNullValue(StackEntryPtrTy
));
216 Head
->setLinkage(GlobalValue::LinkOnceAnyLinkage
);
222 bool ShadowStackGCLowering::IsNullValue(Value
*V
) {
223 if (Constant
*C
= dyn_cast
<Constant
>(V
))
224 return C
->isNullValue();
228 void ShadowStackGCLowering::CollectRoots(Function
&F
) {
229 // FIXME: Account for original alignment. Could fragment the root array.
230 // Approach 1: Null initialize empty slots at runtime. Yuck.
231 // Approach 2: Emit a map of the array instead of just a count.
233 assert(Roots
.empty() && "Not cleaned up?");
235 SmallVector
<std::pair
<CallInst
*, AllocaInst
*>, 16> MetaRoots
;
237 for (Function::iterator BB
= F
.begin(), E
= F
.end(); BB
!= E
; ++BB
)
238 for (BasicBlock::iterator II
= BB
->begin(), E
= BB
->end(); II
!= E
;)
239 if (IntrinsicInst
*CI
= dyn_cast
<IntrinsicInst
>(II
++))
240 if (Function
*F
= CI
->getCalledFunction())
241 if (F
->getIntrinsicID() == Intrinsic::gcroot
) {
242 std::pair
<CallInst
*, AllocaInst
*> Pair
= std::make_pair(
244 cast
<AllocaInst
>(CI
->getArgOperand(0)->stripPointerCasts()));
245 if (IsNullValue(CI
->getArgOperand(1)))
246 Roots
.push_back(Pair
);
248 MetaRoots
.push_back(Pair
);
251 // Number roots with metadata (usually empty) at the beginning, so that the
252 // FrameMap::Meta array can be elided.
253 Roots
.insert(Roots
.begin(), MetaRoots
.begin(), MetaRoots
.end());
256 GetElementPtrInst
*ShadowStackGCLowering::CreateGEP(LLVMContext
&Context
,
257 IRBuilder
<> &B
, Type
*Ty
,
258 Value
*BasePtr
, int Idx
,
261 Value
*Indices
[] = {ConstantInt::get(Type::getInt32Ty(Context
), 0),
262 ConstantInt::get(Type::getInt32Ty(Context
), Idx
),
263 ConstantInt::get(Type::getInt32Ty(Context
), Idx2
)};
264 Value
*Val
= B
.CreateGEP(Ty
, BasePtr
, Indices
, Name
);
266 assert(isa
<GetElementPtrInst
>(Val
) && "Unexpected folded constant");
268 return dyn_cast
<GetElementPtrInst
>(Val
);
271 GetElementPtrInst
*ShadowStackGCLowering::CreateGEP(LLVMContext
&Context
,
272 IRBuilder
<> &B
, Type
*Ty
, Value
*BasePtr
,
273 int Idx
, const char *Name
) {
274 Value
*Indices
[] = {ConstantInt::get(Type::getInt32Ty(Context
), 0),
275 ConstantInt::get(Type::getInt32Ty(Context
), Idx
)};
276 Value
*Val
= B
.CreateGEP(Ty
, BasePtr
, Indices
, Name
);
278 assert(isa
<GetElementPtrInst
>(Val
) && "Unexpected folded constant");
280 return dyn_cast
<GetElementPtrInst
>(Val
);
283 /// runOnFunction - Insert code to maintain the shadow stack.
284 bool ShadowStackGCLowering::runOnFunction(Function
&F
) {
285 // Quick exit for functions that do not use the shadow stack GC.
287 F
.getGC() != std::string("shadow-stack"))
290 LLVMContext
&Context
= F
.getContext();
292 // Find calls to llvm.gcroot.
295 // If there are no roots in this function, then there is no need to add a
296 // stack map entry for it.
300 // Build the constant map and figure the type of the shadow stack entry.
301 Value
*FrameMap
= GetFrameMap(F
);
302 Type
*ConcreteStackEntryTy
= GetConcreteStackEntryType(F
);
304 // Build the shadow stack entry at the very start of the function.
305 BasicBlock::iterator IP
= F
.getEntryBlock().begin();
306 IRBuilder
<> AtEntry(IP
->getParent(), IP
);
308 Instruction
*StackEntry
=
309 AtEntry
.CreateAlloca(ConcreteStackEntryTy
, nullptr, "gc_frame");
311 while (isa
<AllocaInst
>(IP
))
313 AtEntry
.SetInsertPoint(IP
->getParent(), IP
);
315 // Initialize the map pointer and load the current head of the shadow stack.
316 Instruction
*CurrentHead
= AtEntry
.CreateLoad(Head
, "gc_currhead");
317 Instruction
*EntryMapPtr
= CreateGEP(Context
, AtEntry
, ConcreteStackEntryTy
,
318 StackEntry
, 0, 1, "gc_frame.map");
319 AtEntry
.CreateStore(FrameMap
, EntryMapPtr
);
321 // After all the allocas...
322 for (unsigned I
= 0, E
= Roots
.size(); I
!= E
; ++I
) {
323 // For each root, find the corresponding slot in the aggregate...
324 Value
*SlotPtr
= CreateGEP(Context
, AtEntry
, ConcreteStackEntryTy
,
325 StackEntry
, 1 + I
, "gc_root");
327 // And use it in lieu of the alloca.
328 AllocaInst
*OriginalAlloca
= Roots
[I
].second
;
329 SlotPtr
->takeName(OriginalAlloca
);
330 OriginalAlloca
->replaceAllUsesWith(SlotPtr
);
333 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
334 // really necessary (the collector would never see the intermediate state at
335 // runtime), but it's nicer not to push the half-initialized entry onto the
337 while (isa
<StoreInst
>(IP
))
339 AtEntry
.SetInsertPoint(IP
->getParent(), IP
);
341 // Push the entry onto the shadow stack.
342 Instruction
*EntryNextPtr
= CreateGEP(Context
, AtEntry
, ConcreteStackEntryTy
,
343 StackEntry
, 0, 0, "gc_frame.next");
344 Instruction
*NewHeadVal
= CreateGEP(Context
, AtEntry
, ConcreteStackEntryTy
,
345 StackEntry
, 0, "gc_newhead");
346 AtEntry
.CreateStore(CurrentHead
, EntryNextPtr
);
347 AtEntry
.CreateStore(NewHeadVal
, Head
);
349 // For each instruction that escapes...
350 EscapeEnumerator
EE(F
, "gc_cleanup");
351 while (IRBuilder
<> *AtExit
= EE
.Next()) {
352 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
353 // AtEntry, since that would make the value live for the entire function.
354 Instruction
*EntryNextPtr2
=
355 CreateGEP(Context
, *AtExit
, ConcreteStackEntryTy
, StackEntry
, 0, 0,
357 Value
*SavedHead
= AtExit
->CreateLoad(EntryNextPtr2
, "gc_savedhead");
358 AtExit
->CreateStore(SavedHead
, Head
);
361 // Delete the original allocas (which are no longer used) and the intrinsic
362 // calls (which are no longer valid). Doing this last avoids invalidating
364 for (unsigned I
= 0, E
= Roots
.size(); I
!= E
; ++I
) {
365 Roots
[I
].first
->eraseFromParent();
366 Roots
[I
].second
->eraseFromParent();