blob: 10f64c709c7a325130c9e3efb34619bdfca29bb6 [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000029#include "llvm/CodeGen/GCs.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/CodeGen/GCStrategy.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000032#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Module.h"
Gabor Greif89c4cea2010-06-25 08:48:19 +000035#include "llvm/Support/CallSite.h"
Gordon Henriksen8fa89292008-01-07 01:30:53 +000036
37using namespace llvm;
38
39namespace {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000040
Nick Lewycky6726b6d2009-10-25 06:33:48 +000041 class 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 ///
Chris Lattner1afcace2011-07-09 17:41:24 +000048 StructType *StackEntryTy;
49 StructType *FrameMapTy;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000050
Gordon Henriksen8fa89292008-01-07 01:30:53 +000051 /// 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;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000054
Gordon Henriksen8fa89292008-01-07 01:30:53 +000055 public:
Gordon Henriksen5eca0752008-08-17 18:44:35 +000056 ShadowStackGC();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000057
Gordon Henriksen8fa89292008-01-07 01:30:53 +000058 bool initializeCustomLowering(Module &M);
59 bool performCustomLowering(Function &F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000060
Gordon Henriksen8fa89292008-01-07 01:30:53 +000061 private:
62 bool IsNullValue(Value *V);
63 Constant *GetFrameMap(Function &F);
Chris Lattnerdb125cf2011-07-18 04:54:35 +000064 Type* GetConcreteStackEntryType(Function &F);
Gordon Henriksen8fa89292008-01-07 01:30:53 +000065 void CollectRoots(Function &F);
Owen Andersone922c022009-07-22 00:24:57 +000066 static GetElementPtrInst *CreateGEP(LLVMContext &Context,
Owen Anderson9adc0ab2009-07-14 23:09:55 +000067 IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000068 int Idx1, const char *Name);
Owen Andersone922c022009-07-22 00:24:57 +000069 static GetElementPtrInst *CreateGEP(LLVMContext &Context,
Owen Anderson9adc0ab2009-07-14 23:09:55 +000070 IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000071 int Idx1, int Idx2, const char *Name);
72 };
Dan Gohman844731a2008-05-13 00:00:25 +000073
74}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000075
Gordon Henriksen5eca0752008-08-17 18:44:35 +000076static GCRegistry::Add<ShadowStackGC>
77X("shadow-stack", "Very portable GC for uncooperative code generators");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000078
Dan Gohman844731a2008-05-13 00:00:25 +000079namespace {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000080 /// 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
84 /// a landing pad.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000085 ///
Gordon Henriksen8fa89292008-01-07 01:30:53 +000086 /// 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.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000088 class EscapeEnumerator {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000089 Function &F;
90 const char *CleanupBBName;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000091
Gordon Henriksen8fa89292008-01-07 01:30:53 +000092 // State.
93 int State;
94 Function::iterator StateBB, StateE;
Eric Christopher7a61d702008-08-08 19:39:37 +000095 IRBuilder<> Builder;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000096
Gordon Henriksen8fa89292008-01-07 01:30:53 +000097 public:
98 EscapeEnumerator(Function &F, const char *N = "cleanup")
Owen Andersone922c022009-07-22 00:24:57 +000099 : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000100
Eric Christopher7a61d702008-08-08 19:39:37 +0000101 IRBuilder<> *Next() {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000102 switch (State) {
103 default:
104 return 0;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000105
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000106 case 0:
107 StateBB = F.begin();
108 StateE = F.end();
109 State = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000110
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000111 case 1:
Bill Wendling3ca2ad12011-09-21 22:14:28 +0000112 // Find all 'return', 'resume', and 'unwind' instructions.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000113 while (StateBB != StateE) {
114 BasicBlock *CurBB = StateBB++;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000115
Bill Wendlingdccc03b2011-07-31 06:30:59 +0000116 // Branches and invokes do not escape, only unwind, resume, and return
117 // do.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000118 TerminatorInst *TI = CurBB->getTerminator();
Bill Wendlingaa5abe82012-02-06 21:16:41 +0000119 if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI))
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000120 continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000121
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000122 Builder.SetInsertPoint(TI->getParent(), TI);
123 return &Builder;
124 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000125
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000126 State = 2;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000127
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000128 // Find all 'call' instructions.
129 SmallVector<Instruction*,16> Calls;
130 for (Function::iterator BB = F.begin(),
131 E = F.end(); BB != E; ++BB)
132 for (BasicBlock::iterator II = BB->begin(),
133 EE = BB->end(); II != EE; ++II)
134 if (CallInst *CI = dyn_cast<CallInst>(II))
135 if (!CI->getCalledFunction() ||
136 !CI->getCalledFunction()->getIntrinsicID())
137 Calls.push_back(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000138
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000139 if (Calls.empty())
140 return 0;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000141
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000142 // Create a cleanup block.
Bill Wendling3ca2ad12011-09-21 22:14:28 +0000143 LLVMContext &C = F.getContext();
144 BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F);
145 Type *ExnTy = StructType::get(Type::getInt8PtrTy(C),
146 Type::getInt32Ty(C), NULL);
Bill Wendling3ca2ad12011-09-21 22:14:28 +0000147 Constant *PersFn =
148 F.getParent()->
Bill Wendling71139552011-09-22 17:56:40 +0000149 getOrInsertFunction("__gcc_personality_v0",
Bill Wendling3ca2ad12011-09-21 22:14:28 +0000150 FunctionType::get(Type::getInt32Ty(C), true));
151 LandingPadInst *LPad = LandingPadInst::Create(ExnTy, PersFn, 1,
152 "cleanup.lpad",
153 CleanupBB);
154 LPad->setCleanup(true);
155 ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000156
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000157 // Transform the 'call' instructions into 'invoke's branching to the
158 // cleanup block. Go in reverse order to make prettier BB names.
159 SmallVector<Value*,16> Args;
160 for (unsigned I = Calls.size(); I != 0; ) {
161 CallInst *CI = cast<CallInst>(Calls[--I]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000162
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000163 // Split the basic block containing the function call.
164 BasicBlock *CallBB = CI->getParent();
165 BasicBlock *NewBB =
166 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000167
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000168 // Remove the unconditional branch inserted at the end of CallBB.
169 CallBB->getInstList().pop_back();
170 NewBB->getInstList().remove(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000171
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000172 // Create a new invoke instruction.
173 Args.clear();
Gabor Greif89c4cea2010-06-25 08:48:19 +0000174 CallSite CS(CI);
175 Args.append(CS.arg_begin(), CS.arg_end());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000176
Gabor Greifa9b23132010-04-20 13:13:04 +0000177 InvokeInst *II = InvokeInst::Create(CI->getCalledValue(),
Gabor Greif051a9502008-04-06 20:25:17 +0000178 NewBB, CleanupBB,
Jay Foada3efbb12011-07-15 08:37:34 +0000179 Args, CI->getName(), CallBB);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000180 II->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000181 II->setAttributes(CI->getAttributes());
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000182 CI->replaceAllUsesWith(II);
183 delete CI;
184 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000185
Bill Wendling3ca2ad12011-09-21 22:14:28 +0000186 Builder.SetInsertPoint(RI->getParent(), RI);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000187 return &Builder;
188 }
189 }
190 };
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000191}
192
193// -----------------------------------------------------------------------------
194
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000195void llvm::linkShadowStackGC() { }
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000196
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000197ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000198 InitRoots = true;
199 CustomRoots = true;
200}
201
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000202Constant *ShadowStackGC::GetFrameMap(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000203 // doInitialization creates the abstract type of this value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000204 Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000205
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000206 // Truncate the ShadowStackDescriptor if some metadata is null.
207 unsigned NumMeta = 0;
Chris Lattnerb065b062011-06-20 04:01:31 +0000208 SmallVector<Constant*, 16> Metadata;
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000209 for (unsigned I = 0; I != Roots.size(); ++I) {
Gabor Greif89c4cea2010-06-25 08:48:19 +0000210 Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000211 if (!C->isNullValue())
212 NumMeta = I + 1;
213 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
214 }
Jay Foad26701082011-06-22 09:24:39 +0000215 Metadata.resize(NumMeta);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000216
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000217 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Chris Lattnerb065b062011-06-20 04:01:31 +0000218
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000219 Constant *BaseElts[] = {
Chris Lattnerb065b062011-06-20 04:01:31 +0000220 ConstantInt::get(Int32Ty, Roots.size(), false),
221 ConstantInt::get(Int32Ty, NumMeta, false),
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000222 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000223
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000224 Constant *DescriptorElts[] = {
Chris Lattner1afcace2011-07-09 17:41:24 +0000225 ConstantStruct::get(FrameMapTy, BaseElts),
Jay Foad26701082011-06-22 09:24:39 +0000226 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000227 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000228
Chris Lattner1afcace2011-07-09 17:41:24 +0000229 Type *EltTys[] = { DescriptorElts[0]->getType(),DescriptorElts[1]->getType()};
Chris Lattner3ebb6492011-08-12 18:06:37 +0000230 StructType *STy = StructType::create(EltTys, "gc_map."+utostr(NumMeta));
Chris Lattner1afcace2011-07-09 17:41:24 +0000231
232 Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000233
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000234 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
235 // that, short of multithreaded LLVM, it should be safe; all that is
236 // necessary is that a simple Module::iterator loop not be invalidated.
237 // Appending to the GlobalVariable list is safe in that sense.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000238 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000239 // All of the output passes emit globals last. The ExecutionEngine
240 // explicitly supports adding globals to the module after
241 // initialization.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000242 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000243 // Still, if it isn't deemed acceptable, then this transformation needs
244 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
245 // (which uses a FunctionPassManager (which segfaults (not asserts) if
246 // provided a ModulePass))).
Owen Andersone9b11b42009-07-08 19:03:57 +0000247 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000248 GlobalVariable::InternalLinkage,
Owen Andersone9b11b42009-07-08 19:03:57 +0000249 FrameMap, "__gc_" + F.getName());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000250
Owen Anderson1d0be152009-08-13 21:58:54 +0000251 Constant *GEPIndices[2] = {
252 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
253 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)
254 };
Jay Foadb4263a62011-07-22 08:52:50 +0000255 return ConstantExpr::getGetElementPtr(GV, GEPIndices);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000256}
257
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000258Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000259 // doInitialization creates the generic version of this type.
Chris Lattner1afcace2011-07-09 17:41:24 +0000260 std::vector<Type*> EltTys;
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000261 EltTys.push_back(StackEntryTy);
262 for (size_t I = 0; I != Roots.size(); I++)
263 EltTys.push_back(Roots[I].second->getAllocatedType());
Chris Lattner1afcace2011-07-09 17:41:24 +0000264
Chris Lattner3ebb6492011-08-12 18:06:37 +0000265 return StructType::create(EltTys, "gc_stackentry."+F.getName().str());
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000266}
267
268/// doInitialization - If this module uses the GC intrinsics, find them now. If
269/// not, exit fast.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000270bool ShadowStackGC::initializeCustomLowering(Module &M) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000271 // struct FrameMap {
272 // int32_t NumRoots; // Number of roots in stack frame.
273 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
274 // void *Meta[]; // May be absent for roots without metadata.
275 // };
Chris Lattner1afcace2011-07-09 17:41:24 +0000276 std::vector<Type*> EltTys;
Owen Anderson1d0be152009-08-13 21:58:54 +0000277 // 32 bits is ok up to a 32GB stack frame. :)
278 EltTys.push_back(Type::getInt32Ty(M.getContext()));
279 // Specifies length of variable length array.
280 EltTys.push_back(Type::getInt32Ty(M.getContext()));
Chris Lattner3ebb6492011-08-12 18:06:37 +0000281 FrameMapTy = StructType::create(EltTys, "gc_map");
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000282 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000283
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000284 // struct StackEntry {
285 // ShadowStackEntry *Next; // Caller's stack entry.
286 // FrameMap *Map; // Pointer to constant FrameMap.
287 // void *Roots[]; // Stack roots (in-place array, so we pretend).
288 // };
Chris Lattner1afcace2011-07-09 17:41:24 +0000289
Chris Lattner3ebb6492011-08-12 18:06:37 +0000290 StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
Chris Lattner1afcace2011-07-09 17:41:24 +0000291
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000292 EltTys.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000293 EltTys.push_back(PointerType::getUnqual(StackEntryTy));
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000294 EltTys.push_back(FrameMapPtrTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000295 StackEntryTy->setBody(EltTys);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000296 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000297
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000298 // Get the root chain if it already exists.
299 Head = M.getGlobalVariable("llvm_gc_root_chain");
300 if (!Head) {
301 // If the root chain does not exist, insert a new one with linkonce
302 // linkage!
Owen Andersone9b11b42009-07-08 19:03:57 +0000303 Head = new GlobalVariable(M, StackEntryPtrTy, false,
Duncan Sands667d4b82009-03-07 15:45:40 +0000304 GlobalValue::LinkOnceAnyLinkage,
Owen Andersona7235ea2009-07-31 20:28:14 +0000305 Constant::getNullValue(StackEntryPtrTy),
Owen Andersone9b11b42009-07-08 19:03:57 +0000306 "llvm_gc_root_chain");
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000307 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000308 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
Duncan Sands667d4b82009-03-07 15:45:40 +0000309 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000310 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000311
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000312 return true;
313}
314
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000315bool ShadowStackGC::IsNullValue(Value *V) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000316 if (Constant *C = dyn_cast<Constant>(V))
317 return C->isNullValue();
318 return false;
319}
320
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000321void ShadowStackGC::CollectRoots(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000322 // FIXME: Account for original alignment. Could fragment the root array.
323 // Approach 1: Null initialize empty slots at runtime. Yuck.
324 // Approach 2: Emit a map of the array instead of just a count.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000325
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000326 assert(Roots.empty() && "Not cleaned up?");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000327
Gabor Greif89c4cea2010-06-25 08:48:19 +0000328 SmallVector<std::pair<CallInst*, AllocaInst*>, 16> MetaRoots;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000329
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000330 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
331 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
332 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
333 if (Function *F = CI->getCalledFunction())
334 if (F->getIntrinsicID() == Intrinsic::gcroot) {
Gabor Greif89c4cea2010-06-25 08:48:19 +0000335 std::pair<CallInst*, AllocaInst*> Pair = std::make_pair(
336 CI, cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
337 if (IsNullValue(CI->getArgOperand(1)))
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000338 Roots.push_back(Pair);
339 else
340 MetaRoots.push_back(Pair);
341 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000342
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000343 // Number roots with metadata (usually empty) at the beginning, so that the
344 // FrameMap::Meta array can be elided.
345 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
346}
347
348GetElementPtrInst *
Owen Andersone922c022009-07-22 00:24:57 +0000349ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000350 int Idx, int Idx2, const char *Name) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000351 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
352 ConstantInt::get(Type::getInt32Ty(Context), Idx),
353 ConstantInt::get(Type::getInt32Ty(Context), Idx2) };
Jay Foad0a2a60a2011-07-22 08:16:57 +0000354 Value* Val = B.CreateGEP(BasePtr, Indices, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000355
Duncan Sands89f6d882008-04-13 06:22:09 +0000356 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000357
Duncan Sands89f6d882008-04-13 06:22:09 +0000358 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000359}
360
361GetElementPtrInst *
Owen Andersone922c022009-07-22 00:24:57 +0000362ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000363 int Idx, const char *Name) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000364 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
365 ConstantInt::get(Type::getInt32Ty(Context), Idx) };
Jay Foad0a2a60a2011-07-22 08:16:57 +0000366 Value *Val = B.CreateGEP(BasePtr, Indices, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000367
Duncan Sands89f6d882008-04-13 06:22:09 +0000368 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
369
370 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000371}
372
373/// runOnFunction - Insert code to maintain the shadow stack.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000374bool ShadowStackGC::performCustomLowering(Function &F) {
Owen Andersone922c022009-07-22 00:24:57 +0000375 LLVMContext &Context = F.getContext();
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000376
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000377 // Find calls to llvm.gcroot.
378 CollectRoots(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000379
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000380 // If there are no roots in this function, then there is no need to add a
381 // stack map entry for it.
382 if (Roots.empty())
383 return false;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000384
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000385 // Build the constant map and figure the type of the shadow stack entry.
386 Value *FrameMap = GetFrameMap(F);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000387 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000388
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000389 // Build the shadow stack entry at the very start of the function.
390 BasicBlock::iterator IP = F.getEntryBlock().begin();
Eric Christopher7a61d702008-08-08 19:39:37 +0000391 IRBuilder<> AtEntry(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000392
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000393 Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
394 "gc_frame");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000395
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000396 while (isa<AllocaInst>(IP)) ++IP;
397 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000398
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000399 // Initialize the map pointer and load the current head of the shadow stack.
400 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000401 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, StackEntry,
402 0,1,"gc_frame.map");
Chris Lattner1afcace2011-07-09 17:41:24 +0000403 AtEntry.CreateStore(FrameMap, EntryMapPtr);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000404
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000405 // After all the allocas...
406 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
407 // For each root, find the corresponding slot in the aggregate...
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000408 Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000409
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000410 // And use it in lieu of the alloca.
411 AllocaInst *OriginalAlloca = Roots[I].second;
412 SlotPtr->takeName(OriginalAlloca);
413 OriginalAlloca->replaceAllUsesWith(SlotPtr);
414 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000415
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000416 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
417 // really necessary (the collector would never see the intermediate state at
418 // runtime), but it's nicer not to push the half-initialized entry onto the
419 // shadow stack.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000420 while (isa<StoreInst>(IP)) ++IP;
421 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000422
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000423 // Push the entry onto the shadow stack.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000424 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry,
425 StackEntry,0,0,"gc_frame.next");
426 Instruction *NewHeadVal = CreateGEP(Context, AtEntry,
427 StackEntry, 0, "gc_newhead");
428 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
429 AtEntry.CreateStore(NewHeadVal, Head);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000430
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000431 // For each instruction that escapes...
432 EscapeEnumerator EE(F, "gc_cleanup");
Eric Christopher7a61d702008-08-08 19:39:37 +0000433 while (IRBuilder<> *AtExit = EE.Next()) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000434 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
435 // AtEntry, since that would make the value live for the entire function.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000436 Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0,
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000437 "gc_frame.next");
438 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
439 AtExit->CreateStore(SavedHead, Head);
440 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000441
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000442 // Delete the original allocas (which are no longer used) and the intrinsic
443 // calls (which are no longer valid). Doing this last avoids invalidating
444 // iterators.
445 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
446 Roots[I].first->eraseFromParent();
447 Roots[I].second->eraseFromParent();
448 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000449
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000450 Roots.clear();
451 return true;
452}