blob: 25a499b88968dc62075467d7bdc85a931dd8ba25 [file] [log] [blame]
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001//===-- ShadowStackGC.cpp - GC support for uncooperative targets ----------===//
Gordon Henriksen8fa89292008-01-07 01:30:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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
Gordon Henriksen5eca0752008-08-17 18:44:35 +000012// generated is not quite as efficient as algorithms which generate stack maps
Gordon Henriksen8fa89292008-01-07 01:30:53 +000013// to identify roots.
14//
15// This pass implements the code transformation described in this paper:
16// "Accurate Garbage Collection in an Uncooperative Environment"
17// Fergus Henderson, ISMM, 2002
18//
19// In runtime/GC/SemiSpace.cpp is a prototype runtime which is compatible with
Gordon Henriksen5eca0752008-08-17 18:44:35 +000020// ShadowStackGC.
Gordon Henriksen8fa89292008-01-07 01:30:53 +000021//
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.
25//
26//===----------------------------------------------------------------------===//
27
28#define DEBUG_TYPE "shadowstackgc"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000029#include "llvm/CodeGen/GCs.h"
Gordon Henriksen8fa89292008-01-07 01:30:53 +000030#include "llvm/ADT/StringExtras.h"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000031#include "llvm/CodeGen/GCStrategy.h"
Gordon Henriksen8fa89292008-01-07 01:30:53 +000032#include "llvm/IntrinsicInst.h"
33#include "llvm/Module.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000034#include "llvm/Support/Compiler.h"
Duncan Sands89f6d882008-04-13 06:22:09 +000035#include "llvm/Support/IRBuilder.h"
Gordon Henriksen8fa89292008-01-07 01:30:53 +000036
37using namespace llvm;
38
39namespace {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000040
Gordon Henriksen5eca0752008-08-17 18:44:35 +000041 class VISIBILITY_HIDDEN ShadowStackGC : public GCStrategy {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000042 /// RootChain - This is the global linked-list that contains the chain of GC
43 /// roots.
44 GlobalVariable *Head;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000045
Gordon Henriksen8fa89292008-01-07 01:30:53 +000046 /// StackEntryTy - Abstract type of a link in the shadow stack.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000047 ///
Gordon Henriksen8fa89292008-01-07 01:30:53 +000048 const StructType *StackEntryTy;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000049
Gordon Henriksen8fa89292008-01-07 01:30:53 +000050 /// Roots - GC roots in the current function. Each is a pair of the
51 /// intrinsic call and its corresponding alloca.
52 std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000053
Gordon Henriksen8fa89292008-01-07 01:30:53 +000054 public:
Gordon Henriksen5eca0752008-08-17 18:44:35 +000055 ShadowStackGC();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000056
Gordon Henriksen8fa89292008-01-07 01:30:53 +000057 bool initializeCustomLowering(Module &M);
58 bool performCustomLowering(Function &F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000059
Gordon Henriksen8fa89292008-01-07 01:30:53 +000060 private:
61 bool IsNullValue(Value *V);
62 Constant *GetFrameMap(Function &F);
63 const Type* GetConcreteStackEntryType(Function &F);
64 void CollectRoots(Function &F);
Owen Andersone922c022009-07-22 00:24:57 +000065 static GetElementPtrInst *CreateGEP(LLVMContext &Context,
Owen Anderson9adc0ab2009-07-14 23:09:55 +000066 IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000067 int Idx1, const char *Name);
Owen Andersone922c022009-07-22 00:24:57 +000068 static GetElementPtrInst *CreateGEP(LLVMContext &Context,
Owen Anderson9adc0ab2009-07-14 23:09:55 +000069 IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000070 int Idx1, int Idx2, const char *Name);
71 };
Dan Gohman844731a2008-05-13 00:00:25 +000072
73}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000074
Gordon Henriksen5eca0752008-08-17 18:44:35 +000075static GCRegistry::Add<ShadowStackGC>
76X("shadow-stack", "Very portable GC for uncooperative code generators");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000077
Dan Gohman844731a2008-05-13 00:00:25 +000078namespace {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000079 /// EscapeEnumerator - This is a little algorithm to find all escape points
80 /// from a function so that "finally"-style code can be inserted. In addition
81 /// to finding the existing return and unwind instructions, it also (if
82 /// necessary) transforms any call instructions into invokes and sends them to
83 /// a landing pad.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000084 ///
Gordon Henriksen8fa89292008-01-07 01:30:53 +000085 /// It's wrapped up in a state machine using the same transform C# uses for
86 /// 'yield return' enumerators, This transform allows it to be non-allocating.
87 class VISIBILITY_HIDDEN EscapeEnumerator {
88 Function &F;
89 const char *CleanupBBName;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000090
Gordon Henriksen8fa89292008-01-07 01:30:53 +000091 // State.
92 int State;
93 Function::iterator StateBB, StateE;
Eric Christopher7a61d702008-08-08 19:39:37 +000094 IRBuilder<> Builder;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000095
Gordon Henriksen8fa89292008-01-07 01:30:53 +000096 public:
97 EscapeEnumerator(Function &F, const char *N = "cleanup")
Owen Andersone922c022009-07-22 00:24:57 +000098 : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000099
Eric Christopher7a61d702008-08-08 19:39:37 +0000100 IRBuilder<> *Next() {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000101 switch (State) {
102 default:
103 return 0;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000104
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000105 case 0:
106 StateBB = F.begin();
107 StateE = F.end();
108 State = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000109
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000110 case 1:
111 // Find all 'return' and 'unwind' instructions.
112 while (StateBB != StateE) {
113 BasicBlock *CurBB = StateBB++;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000114
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000115 // Branches and invokes do not escape, only unwind and return do.
116 TerminatorInst *TI = CurBB->getTerminator();
117 if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI))
118 continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000119
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000120 Builder.SetInsertPoint(TI->getParent(), TI);
121 return &Builder;
122 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000123
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000124 State = 2;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000125
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000126 // Find all 'call' instructions.
127 SmallVector<Instruction*,16> Calls;
128 for (Function::iterator BB = F.begin(),
129 E = F.end(); BB != E; ++BB)
130 for (BasicBlock::iterator II = BB->begin(),
131 EE = BB->end(); II != EE; ++II)
132 if (CallInst *CI = dyn_cast<CallInst>(II))
133 if (!CI->getCalledFunction() ||
134 !CI->getCalledFunction()->getIntrinsicID())
135 Calls.push_back(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000136
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000137 if (Calls.empty())
138 return 0;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000139
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000140 // Create a cleanup block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000141 BasicBlock *CleanupBB = BasicBlock::Create(F.getContext(),
142 CleanupBBName, &F);
143 UnwindInst *UI = new UnwindInst(F.getContext(), CleanupBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000144
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000145 // Transform the 'call' instructions into 'invoke's branching to the
146 // cleanup block. Go in reverse order to make prettier BB names.
147 SmallVector<Value*,16> Args;
148 for (unsigned I = Calls.size(); I != 0; ) {
149 CallInst *CI = cast<CallInst>(Calls[--I]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000150
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000151 // Split the basic block containing the function call.
152 BasicBlock *CallBB = CI->getParent();
153 BasicBlock *NewBB =
154 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000155
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000156 // Remove the unconditional branch inserted at the end of CallBB.
157 CallBB->getInstList().pop_back();
158 NewBB->getInstList().remove(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000159
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000160 // Create a new invoke instruction.
161 Args.clear();
162 Args.append(CI->op_begin() + 1, CI->op_end());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000163
Gabor Greif051a9502008-04-06 20:25:17 +0000164 InvokeInst *II = InvokeInst::Create(CI->getOperand(0),
165 NewBB, CleanupBB,
166 Args.begin(), Args.end(),
167 CI->getName(), CallBB);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000168 II->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000169 II->setAttributes(CI->getAttributes());
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000170 CI->replaceAllUsesWith(II);
171 delete CI;
172 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000173
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000174 Builder.SetInsertPoint(UI->getParent(), UI);
175 return &Builder;
176 }
177 }
178 };
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000179}
180
181// -----------------------------------------------------------------------------
182
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000183void llvm::linkShadowStackGC() { }
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000184
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000185ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000186 InitRoots = true;
187 CustomRoots = true;
188}
189
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000190Constant *ShadowStackGC::GetFrameMap(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000191 // doInitialization creates the abstract type of this value.
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000192 const Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000193
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000194 // Truncate the ShadowStackDescriptor if some metadata is null.
195 unsigned NumMeta = 0;
196 SmallVector<Constant*,16> Metadata;
197 for (unsigned I = 0; I != Roots.size(); ++I) {
198 Constant *C = cast<Constant>(Roots[I].first->getOperand(2));
199 if (!C->isNullValue())
200 NumMeta = I + 1;
201 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
202 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000203
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000204 Constant *BaseElts[] = {
Owen Anderson1d0be152009-08-13 21:58:54 +0000205 ConstantInt::get(Type::getInt32Ty(F.getContext()), Roots.size(), false),
206 ConstantInt::get(Type::getInt32Ty(F.getContext()), NumMeta, false),
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000207 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000208
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000209 Constant *DescriptorElts[] = {
Nick Lewyckyc332fba2009-09-19 20:30:26 +0000210 ConstantStruct::get(F.getContext(), BaseElts, 2, false),
Owen Andersondebcb012009-07-29 22:17:13 +0000211 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta),
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000212 Metadata.begin(), NumMeta)
213 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000214
Nick Lewyckyc332fba2009-09-19 20:30:26 +0000215 Constant *FrameMap = ConstantStruct::get(F.getContext(), DescriptorElts, 2,
216 false);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000217
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000218 std::string TypeName("gc_map.");
219 TypeName += utostr(NumMeta);
220 F.getParent()->addTypeName(TypeName, FrameMap->getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000221
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000222 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
223 // that, short of multithreaded LLVM, it should be safe; all that is
224 // necessary is that a simple Module::iterator loop not be invalidated.
225 // Appending to the GlobalVariable list is safe in that sense.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000226 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000227 // All of the output passes emit globals last. The ExecutionEngine
228 // explicitly supports adding globals to the module after
229 // initialization.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000230 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000231 // Still, if it isn't deemed acceptable, then this transformation needs
232 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
233 // (which uses a FunctionPassManager (which segfaults (not asserts) if
234 // provided a ModulePass))).
Owen Andersone9b11b42009-07-08 19:03:57 +0000235 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000236 GlobalVariable::InternalLinkage,
Owen Andersone9b11b42009-07-08 19:03:57 +0000237 FrameMap, "__gc_" + F.getName());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000238
Owen Anderson1d0be152009-08-13 21:58:54 +0000239 Constant *GEPIndices[2] = {
240 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
241 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)
242 };
Owen Andersonbaf3c402009-07-29 18:55:55 +0000243 return ConstantExpr::getGetElementPtr(GV, GEPIndices, 2);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000244}
245
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000246const Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000247 // doInitialization creates the generic version of this type.
248 std::vector<const Type*> EltTys;
249 EltTys.push_back(StackEntryTy);
250 for (size_t I = 0; I != Roots.size(); I++)
251 EltTys.push_back(Roots[I].second->getAllocatedType());
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000252 Type *Ty = StructType::get(F.getContext(), EltTys);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000253
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000254 std::string TypeName("gc_stackentry.");
255 TypeName += F.getName();
256 F.getParent()->addTypeName(TypeName, Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000257
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000258 return Ty;
259}
260
261/// doInitialization - If this module uses the GC intrinsics, find them now. If
262/// not, exit fast.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000263bool ShadowStackGC::initializeCustomLowering(Module &M) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000264 // struct FrameMap {
265 // int32_t NumRoots; // Number of roots in stack frame.
266 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
267 // void *Meta[]; // May be absent for roots without metadata.
268 // };
269 std::vector<const Type*> EltTys;
Owen Anderson1d0be152009-08-13 21:58:54 +0000270 // 32 bits is ok up to a 32GB stack frame. :)
271 EltTys.push_back(Type::getInt32Ty(M.getContext()));
272 // Specifies length of variable length array.
273 EltTys.push_back(Type::getInt32Ty(M.getContext()));
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000274 StructType *FrameMapTy = StructType::get(M.getContext(), EltTys);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000275 M.addTypeName("gc_map", FrameMapTy);
276 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000277
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000278 // 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).
282 // };
Owen Anderson0e275dc2009-08-13 23:27:32 +0000283 OpaqueType *RecursiveTy = OpaqueType::get(M.getContext());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000284
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000285 EltTys.clear();
286 EltTys.push_back(PointerType::getUnqual(RecursiveTy));
287 EltTys.push_back(FrameMapPtrTy);
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000288 PATypeHolder LinkTyH = StructType::get(M.getContext(), EltTys);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000289
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000290 RecursiveTy->refineAbstractTypeTo(LinkTyH.get());
291 StackEntryTy = cast<StructType>(LinkTyH.get());
292 const PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
293 M.addTypeName("gc_stackentry", LinkTyH.get()); // FIXME: Is this safe from
294 // a FunctionPass?
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000295
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000296 // Get the root chain if it already exists.
297 Head = M.getGlobalVariable("llvm_gc_root_chain");
298 if (!Head) {
299 // If the root chain does not exist, insert a new one with linkonce
300 // linkage!
Owen Andersone9b11b42009-07-08 19:03:57 +0000301 Head = new GlobalVariable(M, StackEntryPtrTy, false,
Duncan Sands667d4b82009-03-07 15:45:40 +0000302 GlobalValue::LinkOnceAnyLinkage,
Owen Andersona7235ea2009-07-31 20:28:14 +0000303 Constant::getNullValue(StackEntryPtrTy),
Owen Andersone9b11b42009-07-08 19:03:57 +0000304 "llvm_gc_root_chain");
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000305 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000306 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
Duncan Sands667d4b82009-03-07 15:45:40 +0000307 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000308 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000309
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000310 return true;
311}
312
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000313bool ShadowStackGC::IsNullValue(Value *V) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000314 if (Constant *C = dyn_cast<Constant>(V))
315 return C->isNullValue();
316 return false;
317}
318
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000319void ShadowStackGC::CollectRoots(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000320 // FIXME: Account for original alignment. Could fragment the root array.
321 // Approach 1: Null initialize empty slots at runtime. Yuck.
322 // Approach 2: Emit a map of the array instead of just a count.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000323
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000324 assert(Roots.empty() && "Not cleaned up?");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000325
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000326 SmallVector<std::pair<CallInst*,AllocaInst*>,16> MetaRoots;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000327
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000328 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
329 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
330 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
331 if (Function *F = CI->getCalledFunction())
332 if (F->getIntrinsicID() == Intrinsic::gcroot) {
333 std::pair<CallInst*,AllocaInst*> Pair = std::make_pair(
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000334 CI, cast<AllocaInst>(CI->getOperand(1)->stripPointerCasts()));
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000335 if (IsNullValue(CI->getOperand(2)))
336 Roots.push_back(Pair);
337 else
338 MetaRoots.push_back(Pair);
339 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000340
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000341 // Number roots with metadata (usually empty) at the beginning, so that the
342 // FrameMap::Meta array can be elided.
343 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
344}
345
346GetElementPtrInst *
Owen Andersone922c022009-07-22 00:24:57 +0000347ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000348 int Idx, int Idx2, const char *Name) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000349 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
350 ConstantInt::get(Type::getInt32Ty(Context), Idx),
351 ConstantInt::get(Type::getInt32Ty(Context), Idx2) };
Duncan Sands89f6d882008-04-13 06:22:09 +0000352 Value* Val = B.CreateGEP(BasePtr, Indices, Indices + 3, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000353
Duncan Sands89f6d882008-04-13 06:22:09 +0000354 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000355
Duncan Sands89f6d882008-04-13 06:22:09 +0000356 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000357}
358
359GetElementPtrInst *
Owen Andersone922c022009-07-22 00:24:57 +0000360ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000361 int Idx, const char *Name) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000362 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
363 ConstantInt::get(Type::getInt32Ty(Context), Idx) };
Duncan Sands89f6d882008-04-13 06:22:09 +0000364 Value *Val = B.CreateGEP(BasePtr, Indices, Indices + 2, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000365
Duncan Sands89f6d882008-04-13 06:22:09 +0000366 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
367
368 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000369}
370
371/// runOnFunction - Insert code to maintain the shadow stack.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000372bool ShadowStackGC::performCustomLowering(Function &F) {
Owen Andersone922c022009-07-22 00:24:57 +0000373 LLVMContext &Context = F.getContext();
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000374
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000375 // Find calls to llvm.gcroot.
376 CollectRoots(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000377
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000378 // If there are no roots in this function, then there is no need to add a
379 // stack map entry for it.
380 if (Roots.empty())
381 return false;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000382
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000383 // Build the constant map and figure the type of the shadow stack entry.
384 Value *FrameMap = GetFrameMap(F);
385 const Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000386
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000387 // Build the shadow stack entry at the very start of the function.
388 BasicBlock::iterator IP = F.getEntryBlock().begin();
Eric Christopher7a61d702008-08-08 19:39:37 +0000389 IRBuilder<> AtEntry(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000390
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000391 Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
392 "gc_frame");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000393
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000394 while (isa<AllocaInst>(IP)) ++IP;
395 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000396
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000397 // Initialize the map pointer and load the current head of the shadow stack.
398 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000399 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, StackEntry,
400 0,1,"gc_frame.map");
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000401 AtEntry.CreateStore(FrameMap, EntryMapPtr);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000402
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000403 // After all the allocas...
404 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
405 // For each root, find the corresponding slot in the aggregate...
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000406 Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000407
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000408 // And use it in lieu of the alloca.
409 AllocaInst *OriginalAlloca = Roots[I].second;
410 SlotPtr->takeName(OriginalAlloca);
411 OriginalAlloca->replaceAllUsesWith(SlotPtr);
412 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000413
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000414 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
415 // really necessary (the collector would never see the intermediate state at
416 // runtime), but it's nicer not to push the half-initialized entry onto the
417 // shadow stack.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000418 while (isa<StoreInst>(IP)) ++IP;
419 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000420
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000421 // Push the entry onto the shadow stack.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000422 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry,
423 StackEntry,0,0,"gc_frame.next");
424 Instruction *NewHeadVal = CreateGEP(Context, AtEntry,
425 StackEntry, 0, "gc_newhead");
426 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
427 AtEntry.CreateStore(NewHeadVal, Head);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000428
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000429 // For each instruction that escapes...
430 EscapeEnumerator EE(F, "gc_cleanup");
Eric Christopher7a61d702008-08-08 19:39:37 +0000431 while (IRBuilder<> *AtExit = EE.Next()) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000432 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
433 // AtEntry, since that would make the value live for the entire function.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000434 Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0,
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000435 "gc_frame.next");
436 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
437 AtExit->CreateStore(SavedHead, Head);
438 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000439
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000440 // Delete the original allocas (which are no longer used) and the intrinsic
441 // calls (which are no longer valid). Doing this last avoids invalidating
442 // iterators.
443 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
444 Roots[I].first->eraseFromParent();
445 Roots[I].second->eraseFromParent();
446 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000447
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000448 Roots.clear();
449 return true;
450}