xref: /minix3/external/bsd/llvm/dist/llvm/lib/CodeGen/ShadowStackGC.cpp (revision f4a2713ac843a11c696ec80c0a5e3e5d80b4d338)
1*f4a2713aSLionel Sambuc //===-- ShadowStackGC.cpp - GC support for uncooperative targets ----------===//
2*f4a2713aSLionel Sambuc //
3*f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4*f4a2713aSLionel Sambuc //
5*f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6*f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7*f4a2713aSLionel Sambuc //
8*f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9*f4a2713aSLionel Sambuc //
10*f4a2713aSLionel Sambuc // This file implements lowering for the llvm.gc* intrinsics for targets that do
11*f4a2713aSLionel Sambuc // not natively support them (which includes the C backend). Note that the code
12*f4a2713aSLionel Sambuc // generated is not quite as efficient as algorithms which generate stack maps
13*f4a2713aSLionel Sambuc // to identify roots.
14*f4a2713aSLionel Sambuc //
15*f4a2713aSLionel Sambuc // This pass implements the code transformation described in this paper:
16*f4a2713aSLionel Sambuc //   "Accurate Garbage Collection in an Uncooperative Environment"
17*f4a2713aSLionel Sambuc //   Fergus Henderson, ISMM, 2002
18*f4a2713aSLionel Sambuc //
19*f4a2713aSLionel Sambuc // In runtime/GC/SemiSpace.cpp is a prototype runtime which is compatible with
20*f4a2713aSLionel Sambuc // ShadowStackGC.
21*f4a2713aSLionel Sambuc //
22*f4a2713aSLionel Sambuc // In order to support this particular transformation, all stack roots are
23*f4a2713aSLionel Sambuc // coallocated in the stack. This allows a fully target-independent stack map
24*f4a2713aSLionel Sambuc // while introducing only minor runtime overhead.
25*f4a2713aSLionel Sambuc //
26*f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
27*f4a2713aSLionel Sambuc 
28*f4a2713aSLionel Sambuc #define DEBUG_TYPE "shadowstackgc"
29*f4a2713aSLionel Sambuc #include "llvm/CodeGen/GCs.h"
30*f4a2713aSLionel Sambuc #include "llvm/ADT/StringExtras.h"
31*f4a2713aSLionel Sambuc #include "llvm/CodeGen/GCStrategy.h"
32*f4a2713aSLionel Sambuc #include "llvm/IR/IRBuilder.h"
33*f4a2713aSLionel Sambuc #include "llvm/IR/IntrinsicInst.h"
34*f4a2713aSLionel Sambuc #include "llvm/IR/Module.h"
35*f4a2713aSLionel Sambuc #include "llvm/Support/CallSite.h"
36*f4a2713aSLionel Sambuc 
37*f4a2713aSLionel Sambuc using namespace llvm;
38*f4a2713aSLionel Sambuc 
39*f4a2713aSLionel Sambuc namespace {
40*f4a2713aSLionel Sambuc 
41*f4a2713aSLionel Sambuc   class ShadowStackGC : public GCStrategy {
42*f4a2713aSLionel Sambuc     /// RootChain - This is the global linked-list that contains the chain of GC
43*f4a2713aSLionel Sambuc     /// roots.
44*f4a2713aSLionel Sambuc     GlobalVariable *Head;
45*f4a2713aSLionel Sambuc 
46*f4a2713aSLionel Sambuc     /// StackEntryTy - Abstract type of a link in the shadow stack.
47*f4a2713aSLionel Sambuc     ///
48*f4a2713aSLionel Sambuc     StructType *StackEntryTy;
49*f4a2713aSLionel Sambuc     StructType *FrameMapTy;
50*f4a2713aSLionel Sambuc 
51*f4a2713aSLionel Sambuc     /// Roots - GC roots in the current function. Each is a pair of the
52*f4a2713aSLionel Sambuc     /// intrinsic call and its corresponding alloca.
53*f4a2713aSLionel Sambuc     std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
54*f4a2713aSLionel Sambuc 
55*f4a2713aSLionel Sambuc   public:
56*f4a2713aSLionel Sambuc     ShadowStackGC();
57*f4a2713aSLionel Sambuc 
58*f4a2713aSLionel Sambuc     bool initializeCustomLowering(Module &M);
59*f4a2713aSLionel Sambuc     bool performCustomLowering(Function &F);
60*f4a2713aSLionel Sambuc 
61*f4a2713aSLionel Sambuc   private:
62*f4a2713aSLionel Sambuc     bool IsNullValue(Value *V);
63*f4a2713aSLionel Sambuc     Constant *GetFrameMap(Function &F);
64*f4a2713aSLionel Sambuc     Type* GetConcreteStackEntryType(Function &F);
65*f4a2713aSLionel Sambuc     void CollectRoots(Function &F);
66*f4a2713aSLionel Sambuc     static GetElementPtrInst *CreateGEP(LLVMContext &Context,
67*f4a2713aSLionel Sambuc                                         IRBuilder<> &B, Value *BasePtr,
68*f4a2713aSLionel Sambuc                                         int Idx1, const char *Name);
69*f4a2713aSLionel Sambuc     static GetElementPtrInst *CreateGEP(LLVMContext &Context,
70*f4a2713aSLionel Sambuc                                         IRBuilder<> &B, Value *BasePtr,
71*f4a2713aSLionel Sambuc                                         int Idx1, int Idx2, const char *Name);
72*f4a2713aSLionel Sambuc   };
73*f4a2713aSLionel Sambuc 
74*f4a2713aSLionel Sambuc }
75*f4a2713aSLionel Sambuc 
76*f4a2713aSLionel Sambuc static GCRegistry::Add<ShadowStackGC>
77*f4a2713aSLionel Sambuc X("shadow-stack", "Very portable GC for uncooperative code generators");
78*f4a2713aSLionel Sambuc 
79*f4a2713aSLionel Sambuc namespace {
80*f4a2713aSLionel Sambuc   /// EscapeEnumerator - This is a little algorithm to find all escape points
81*f4a2713aSLionel Sambuc   /// from a function so that "finally"-style code can be inserted. In addition
82*f4a2713aSLionel Sambuc   /// to finding the existing return and unwind instructions, it also (if
83*f4a2713aSLionel Sambuc   /// necessary) transforms any call instructions into invokes and sends them to
84*f4a2713aSLionel Sambuc   /// a landing pad.
85*f4a2713aSLionel Sambuc   ///
86*f4a2713aSLionel Sambuc   /// It's wrapped up in a state machine using the same transform C# uses for
87*f4a2713aSLionel Sambuc   /// 'yield return' enumerators, This transform allows it to be non-allocating.
88*f4a2713aSLionel Sambuc   class EscapeEnumerator {
89*f4a2713aSLionel Sambuc     Function &F;
90*f4a2713aSLionel Sambuc     const char *CleanupBBName;
91*f4a2713aSLionel Sambuc 
92*f4a2713aSLionel Sambuc     // State.
93*f4a2713aSLionel Sambuc     int State;
94*f4a2713aSLionel Sambuc     Function::iterator StateBB, StateE;
95*f4a2713aSLionel Sambuc     IRBuilder<> Builder;
96*f4a2713aSLionel Sambuc 
97*f4a2713aSLionel Sambuc   public:
98*f4a2713aSLionel Sambuc     EscapeEnumerator(Function &F, const char *N = "cleanup")
99*f4a2713aSLionel Sambuc       : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
100*f4a2713aSLionel Sambuc 
101*f4a2713aSLionel Sambuc     IRBuilder<> *Next() {
102*f4a2713aSLionel Sambuc       switch (State) {
103*f4a2713aSLionel Sambuc       default:
104*f4a2713aSLionel Sambuc         return 0;
105*f4a2713aSLionel Sambuc 
106*f4a2713aSLionel Sambuc       case 0:
107*f4a2713aSLionel Sambuc         StateBB = F.begin();
108*f4a2713aSLionel Sambuc         StateE = F.end();
109*f4a2713aSLionel Sambuc         State = 1;
110*f4a2713aSLionel Sambuc 
111*f4a2713aSLionel Sambuc       case 1:
112*f4a2713aSLionel Sambuc         // Find all 'return', 'resume', and 'unwind' instructions.
113*f4a2713aSLionel Sambuc         while (StateBB != StateE) {
114*f4a2713aSLionel Sambuc           BasicBlock *CurBB = StateBB++;
115*f4a2713aSLionel Sambuc 
116*f4a2713aSLionel Sambuc           // Branches and invokes do not escape, only unwind, resume, and return
117*f4a2713aSLionel Sambuc           // do.
118*f4a2713aSLionel Sambuc           TerminatorInst *TI = CurBB->getTerminator();
119*f4a2713aSLionel Sambuc           if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI))
120*f4a2713aSLionel Sambuc             continue;
121*f4a2713aSLionel Sambuc 
122*f4a2713aSLionel Sambuc           Builder.SetInsertPoint(TI->getParent(), TI);
123*f4a2713aSLionel Sambuc           return &Builder;
124*f4a2713aSLionel Sambuc         }
125*f4a2713aSLionel Sambuc 
126*f4a2713aSLionel Sambuc         State = 2;
127*f4a2713aSLionel Sambuc 
128*f4a2713aSLionel Sambuc         // Find all 'call' instructions.
129*f4a2713aSLionel Sambuc         SmallVector<Instruction*,16> Calls;
130*f4a2713aSLionel Sambuc         for (Function::iterator BB = F.begin(),
131*f4a2713aSLionel Sambuc                                 E = F.end(); BB != E; ++BB)
132*f4a2713aSLionel Sambuc           for (BasicBlock::iterator II = BB->begin(),
133*f4a2713aSLionel Sambuc                                     EE = BB->end(); II != EE; ++II)
134*f4a2713aSLionel Sambuc             if (CallInst *CI = dyn_cast<CallInst>(II))
135*f4a2713aSLionel Sambuc               if (!CI->getCalledFunction() ||
136*f4a2713aSLionel Sambuc                   !CI->getCalledFunction()->getIntrinsicID())
137*f4a2713aSLionel Sambuc                 Calls.push_back(CI);
138*f4a2713aSLionel Sambuc 
139*f4a2713aSLionel Sambuc         if (Calls.empty())
140*f4a2713aSLionel Sambuc           return 0;
141*f4a2713aSLionel Sambuc 
142*f4a2713aSLionel Sambuc         // Create a cleanup block.
143*f4a2713aSLionel Sambuc         LLVMContext &C = F.getContext();
144*f4a2713aSLionel Sambuc         BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F);
145*f4a2713aSLionel Sambuc         Type *ExnTy = StructType::get(Type::getInt8PtrTy(C),
146*f4a2713aSLionel Sambuc                                       Type::getInt32Ty(C), NULL);
147*f4a2713aSLionel Sambuc         Constant *PersFn =
148*f4a2713aSLionel Sambuc           F.getParent()->
149*f4a2713aSLionel Sambuc           getOrInsertFunction("__gcc_personality_v0",
150*f4a2713aSLionel Sambuc                               FunctionType::get(Type::getInt32Ty(C), true));
151*f4a2713aSLionel Sambuc         LandingPadInst *LPad = LandingPadInst::Create(ExnTy, PersFn, 1,
152*f4a2713aSLionel Sambuc                                                       "cleanup.lpad",
153*f4a2713aSLionel Sambuc                                                       CleanupBB);
154*f4a2713aSLionel Sambuc         LPad->setCleanup(true);
155*f4a2713aSLionel Sambuc         ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB);
156*f4a2713aSLionel Sambuc 
157*f4a2713aSLionel Sambuc         // Transform the 'call' instructions into 'invoke's branching to the
158*f4a2713aSLionel Sambuc         // cleanup block. Go in reverse order to make prettier BB names.
159*f4a2713aSLionel Sambuc         SmallVector<Value*,16> Args;
160*f4a2713aSLionel Sambuc         for (unsigned I = Calls.size(); I != 0; ) {
161*f4a2713aSLionel Sambuc           CallInst *CI = cast<CallInst>(Calls[--I]);
162*f4a2713aSLionel Sambuc 
163*f4a2713aSLionel Sambuc           // Split the basic block containing the function call.
164*f4a2713aSLionel Sambuc           BasicBlock *CallBB = CI->getParent();
165*f4a2713aSLionel Sambuc           BasicBlock *NewBB =
166*f4a2713aSLionel Sambuc             CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
167*f4a2713aSLionel Sambuc 
168*f4a2713aSLionel Sambuc           // Remove the unconditional branch inserted at the end of CallBB.
169*f4a2713aSLionel Sambuc           CallBB->getInstList().pop_back();
170*f4a2713aSLionel Sambuc           NewBB->getInstList().remove(CI);
171*f4a2713aSLionel Sambuc 
172*f4a2713aSLionel Sambuc           // Create a new invoke instruction.
173*f4a2713aSLionel Sambuc           Args.clear();
174*f4a2713aSLionel Sambuc           CallSite CS(CI);
175*f4a2713aSLionel Sambuc           Args.append(CS.arg_begin(), CS.arg_end());
176*f4a2713aSLionel Sambuc 
177*f4a2713aSLionel Sambuc           InvokeInst *II = InvokeInst::Create(CI->getCalledValue(),
178*f4a2713aSLionel Sambuc                                               NewBB, CleanupBB,
179*f4a2713aSLionel Sambuc                                               Args, CI->getName(), CallBB);
180*f4a2713aSLionel Sambuc           II->setCallingConv(CI->getCallingConv());
181*f4a2713aSLionel Sambuc           II->setAttributes(CI->getAttributes());
182*f4a2713aSLionel Sambuc           CI->replaceAllUsesWith(II);
183*f4a2713aSLionel Sambuc           delete CI;
184*f4a2713aSLionel Sambuc         }
185*f4a2713aSLionel Sambuc 
186*f4a2713aSLionel Sambuc         Builder.SetInsertPoint(RI->getParent(), RI);
187*f4a2713aSLionel Sambuc         return &Builder;
188*f4a2713aSLionel Sambuc       }
189*f4a2713aSLionel Sambuc     }
190*f4a2713aSLionel Sambuc   };
191*f4a2713aSLionel Sambuc }
192*f4a2713aSLionel Sambuc 
193*f4a2713aSLionel Sambuc // -----------------------------------------------------------------------------
194*f4a2713aSLionel Sambuc 
195*f4a2713aSLionel Sambuc void llvm::linkShadowStackGC() { }
196*f4a2713aSLionel Sambuc 
197*f4a2713aSLionel Sambuc ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
198*f4a2713aSLionel Sambuc   InitRoots = true;
199*f4a2713aSLionel Sambuc   CustomRoots = true;
200*f4a2713aSLionel Sambuc }
201*f4a2713aSLionel Sambuc 
202*f4a2713aSLionel Sambuc Constant *ShadowStackGC::GetFrameMap(Function &F) {
203*f4a2713aSLionel Sambuc   // doInitialization creates the abstract type of this value.
204*f4a2713aSLionel Sambuc   Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
205*f4a2713aSLionel Sambuc 
206*f4a2713aSLionel Sambuc   // Truncate the ShadowStackDescriptor if some metadata is null.
207*f4a2713aSLionel Sambuc   unsigned NumMeta = 0;
208*f4a2713aSLionel Sambuc   SmallVector<Constant*, 16> Metadata;
209*f4a2713aSLionel Sambuc   for (unsigned I = 0; I != Roots.size(); ++I) {
210*f4a2713aSLionel Sambuc     Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
211*f4a2713aSLionel Sambuc     if (!C->isNullValue())
212*f4a2713aSLionel Sambuc       NumMeta = I + 1;
213*f4a2713aSLionel Sambuc     Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
214*f4a2713aSLionel Sambuc   }
215*f4a2713aSLionel Sambuc   Metadata.resize(NumMeta);
216*f4a2713aSLionel Sambuc 
217*f4a2713aSLionel Sambuc   Type *Int32Ty = Type::getInt32Ty(F.getContext());
218*f4a2713aSLionel Sambuc 
219*f4a2713aSLionel Sambuc   Constant *BaseElts[] = {
220*f4a2713aSLionel Sambuc     ConstantInt::get(Int32Ty, Roots.size(), false),
221*f4a2713aSLionel Sambuc     ConstantInt::get(Int32Ty, NumMeta, false),
222*f4a2713aSLionel Sambuc   };
223*f4a2713aSLionel Sambuc 
224*f4a2713aSLionel Sambuc   Constant *DescriptorElts[] = {
225*f4a2713aSLionel Sambuc     ConstantStruct::get(FrameMapTy, BaseElts),
226*f4a2713aSLionel Sambuc     ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)
227*f4a2713aSLionel Sambuc   };
228*f4a2713aSLionel Sambuc 
229*f4a2713aSLionel Sambuc   Type *EltTys[] = { DescriptorElts[0]->getType(),DescriptorElts[1]->getType()};
230*f4a2713aSLionel Sambuc   StructType *STy = StructType::create(EltTys, "gc_map."+utostr(NumMeta));
231*f4a2713aSLionel Sambuc 
232*f4a2713aSLionel Sambuc   Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
233*f4a2713aSLionel Sambuc 
234*f4a2713aSLionel Sambuc   // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
235*f4a2713aSLionel Sambuc   //        that, short of multithreaded LLVM, it should be safe; all that is
236*f4a2713aSLionel Sambuc   //        necessary is that a simple Module::iterator loop not be invalidated.
237*f4a2713aSLionel Sambuc   //        Appending to the GlobalVariable list is safe in that sense.
238*f4a2713aSLionel Sambuc   //
239*f4a2713aSLionel Sambuc   //        All of the output passes emit globals last. The ExecutionEngine
240*f4a2713aSLionel Sambuc   //        explicitly supports adding globals to the module after
241*f4a2713aSLionel Sambuc   //        initialization.
242*f4a2713aSLionel Sambuc   //
243*f4a2713aSLionel Sambuc   //        Still, if it isn't deemed acceptable, then this transformation needs
244*f4a2713aSLionel Sambuc   //        to be a ModulePass (which means it cannot be in the 'llc' pipeline
245*f4a2713aSLionel Sambuc   //        (which uses a FunctionPassManager (which segfaults (not asserts) if
246*f4a2713aSLionel Sambuc   //        provided a ModulePass))).
247*f4a2713aSLionel Sambuc   Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
248*f4a2713aSLionel Sambuc                                     GlobalVariable::InternalLinkage,
249*f4a2713aSLionel Sambuc                                     FrameMap, "__gc_" + F.getName());
250*f4a2713aSLionel Sambuc 
251*f4a2713aSLionel Sambuc   Constant *GEPIndices[2] = {
252*f4a2713aSLionel Sambuc                           ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
253*f4a2713aSLionel Sambuc                           ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)
254*f4a2713aSLionel Sambuc                           };
255*f4a2713aSLionel Sambuc   return ConstantExpr::getGetElementPtr(GV, GEPIndices);
256*f4a2713aSLionel Sambuc }
257*f4a2713aSLionel Sambuc 
258*f4a2713aSLionel Sambuc Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
259*f4a2713aSLionel Sambuc   // doInitialization creates the generic version of this type.
260*f4a2713aSLionel Sambuc   std::vector<Type*> EltTys;
261*f4a2713aSLionel Sambuc   EltTys.push_back(StackEntryTy);
262*f4a2713aSLionel Sambuc   for (size_t I = 0; I != Roots.size(); I++)
263*f4a2713aSLionel Sambuc     EltTys.push_back(Roots[I].second->getAllocatedType());
264*f4a2713aSLionel Sambuc 
265*f4a2713aSLionel Sambuc   return StructType::create(EltTys, "gc_stackentry."+F.getName().str());
266*f4a2713aSLionel Sambuc }
267*f4a2713aSLionel Sambuc 
268*f4a2713aSLionel Sambuc /// doInitialization - If this module uses the GC intrinsics, find them now. If
269*f4a2713aSLionel Sambuc /// not, exit fast.
270*f4a2713aSLionel Sambuc bool ShadowStackGC::initializeCustomLowering(Module &M) {
271*f4a2713aSLionel Sambuc   // struct FrameMap {
272*f4a2713aSLionel Sambuc   //   int32_t NumRoots; // Number of roots in stack frame.
273*f4a2713aSLionel Sambuc   //   int32_t NumMeta;  // Number of metadata descriptors. May be < NumRoots.
274*f4a2713aSLionel Sambuc   //   void *Meta[];     // May be absent for roots without metadata.
275*f4a2713aSLionel Sambuc   // };
276*f4a2713aSLionel Sambuc   std::vector<Type*> EltTys;
277*f4a2713aSLionel Sambuc   // 32 bits is ok up to a 32GB stack frame. :)
278*f4a2713aSLionel Sambuc   EltTys.push_back(Type::getInt32Ty(M.getContext()));
279*f4a2713aSLionel Sambuc   // Specifies length of variable length array.
280*f4a2713aSLionel Sambuc   EltTys.push_back(Type::getInt32Ty(M.getContext()));
281*f4a2713aSLionel Sambuc   FrameMapTy = StructType::create(EltTys, "gc_map");
282*f4a2713aSLionel Sambuc   PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
283*f4a2713aSLionel Sambuc 
284*f4a2713aSLionel Sambuc   // struct StackEntry {
285*f4a2713aSLionel Sambuc   //   ShadowStackEntry *Next; // Caller's stack entry.
286*f4a2713aSLionel Sambuc   //   FrameMap *Map;          // Pointer to constant FrameMap.
287*f4a2713aSLionel Sambuc   //   void *Roots[];          // Stack roots (in-place array, so we pretend).
288*f4a2713aSLionel Sambuc   // };
289*f4a2713aSLionel Sambuc 
290*f4a2713aSLionel Sambuc   StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
291*f4a2713aSLionel Sambuc 
292*f4a2713aSLionel Sambuc   EltTys.clear();
293*f4a2713aSLionel Sambuc   EltTys.push_back(PointerType::getUnqual(StackEntryTy));
294*f4a2713aSLionel Sambuc   EltTys.push_back(FrameMapPtrTy);
295*f4a2713aSLionel Sambuc   StackEntryTy->setBody(EltTys);
296*f4a2713aSLionel Sambuc   PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
297*f4a2713aSLionel Sambuc 
298*f4a2713aSLionel Sambuc   // Get the root chain if it already exists.
299*f4a2713aSLionel Sambuc   Head = M.getGlobalVariable("llvm_gc_root_chain");
300*f4a2713aSLionel Sambuc   if (!Head) {
301*f4a2713aSLionel Sambuc     // If the root chain does not exist, insert a new one with linkonce
302*f4a2713aSLionel Sambuc     // linkage!
303*f4a2713aSLionel Sambuc     Head = new GlobalVariable(M, StackEntryPtrTy, false,
304*f4a2713aSLionel Sambuc                               GlobalValue::LinkOnceAnyLinkage,
305*f4a2713aSLionel Sambuc                               Constant::getNullValue(StackEntryPtrTy),
306*f4a2713aSLionel Sambuc                               "llvm_gc_root_chain");
307*f4a2713aSLionel Sambuc   } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
308*f4a2713aSLionel Sambuc     Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
309*f4a2713aSLionel Sambuc     Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
310*f4a2713aSLionel Sambuc   }
311*f4a2713aSLionel Sambuc 
312*f4a2713aSLionel Sambuc   return true;
313*f4a2713aSLionel Sambuc }
314*f4a2713aSLionel Sambuc 
315*f4a2713aSLionel Sambuc bool ShadowStackGC::IsNullValue(Value *V) {
316*f4a2713aSLionel Sambuc   if (Constant *C = dyn_cast<Constant>(V))
317*f4a2713aSLionel Sambuc     return C->isNullValue();
318*f4a2713aSLionel Sambuc   return false;
319*f4a2713aSLionel Sambuc }
320*f4a2713aSLionel Sambuc 
321*f4a2713aSLionel Sambuc void ShadowStackGC::CollectRoots(Function &F) {
322*f4a2713aSLionel Sambuc   // FIXME: Account for original alignment. Could fragment the root array.
323*f4a2713aSLionel Sambuc   //   Approach 1: Null initialize empty slots at runtime. Yuck.
324*f4a2713aSLionel Sambuc   //   Approach 2: Emit a map of the array instead of just a count.
325*f4a2713aSLionel Sambuc 
326*f4a2713aSLionel Sambuc   assert(Roots.empty() && "Not cleaned up?");
327*f4a2713aSLionel Sambuc 
328*f4a2713aSLionel Sambuc   SmallVector<std::pair<CallInst*, AllocaInst*>, 16> MetaRoots;
329*f4a2713aSLionel Sambuc 
330*f4a2713aSLionel Sambuc   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
331*f4a2713aSLionel Sambuc     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
332*f4a2713aSLionel Sambuc       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
333*f4a2713aSLionel Sambuc         if (Function *F = CI->getCalledFunction())
334*f4a2713aSLionel Sambuc           if (F->getIntrinsicID() == Intrinsic::gcroot) {
335*f4a2713aSLionel Sambuc             std::pair<CallInst*, AllocaInst*> Pair = std::make_pair(
336*f4a2713aSLionel Sambuc               CI, cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
337*f4a2713aSLionel Sambuc             if (IsNullValue(CI->getArgOperand(1)))
338*f4a2713aSLionel Sambuc               Roots.push_back(Pair);
339*f4a2713aSLionel Sambuc             else
340*f4a2713aSLionel Sambuc               MetaRoots.push_back(Pair);
341*f4a2713aSLionel Sambuc           }
342*f4a2713aSLionel Sambuc 
343*f4a2713aSLionel Sambuc   // Number roots with metadata (usually empty) at the beginning, so that the
344*f4a2713aSLionel Sambuc   // FrameMap::Meta array can be elided.
345*f4a2713aSLionel Sambuc   Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
346*f4a2713aSLionel Sambuc }
347*f4a2713aSLionel Sambuc 
348*f4a2713aSLionel Sambuc GetElementPtrInst *
349*f4a2713aSLionel Sambuc ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
350*f4a2713aSLionel Sambuc                          int Idx, int Idx2, const char *Name) {
351*f4a2713aSLionel Sambuc   Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
352*f4a2713aSLionel Sambuc                        ConstantInt::get(Type::getInt32Ty(Context), Idx),
353*f4a2713aSLionel Sambuc                        ConstantInt::get(Type::getInt32Ty(Context), Idx2) };
354*f4a2713aSLionel Sambuc   Value* Val = B.CreateGEP(BasePtr, Indices, Name);
355*f4a2713aSLionel Sambuc 
356*f4a2713aSLionel Sambuc   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
357*f4a2713aSLionel Sambuc 
358*f4a2713aSLionel Sambuc   return dyn_cast<GetElementPtrInst>(Val);
359*f4a2713aSLionel Sambuc }
360*f4a2713aSLionel Sambuc 
361*f4a2713aSLionel Sambuc GetElementPtrInst *
362*f4a2713aSLionel Sambuc ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
363*f4a2713aSLionel Sambuc                          int Idx, const char *Name) {
364*f4a2713aSLionel Sambuc   Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
365*f4a2713aSLionel Sambuc                        ConstantInt::get(Type::getInt32Ty(Context), Idx) };
366*f4a2713aSLionel Sambuc   Value *Val = B.CreateGEP(BasePtr, Indices, Name);
367*f4a2713aSLionel Sambuc 
368*f4a2713aSLionel Sambuc   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
369*f4a2713aSLionel Sambuc 
370*f4a2713aSLionel Sambuc   return dyn_cast<GetElementPtrInst>(Val);
371*f4a2713aSLionel Sambuc }
372*f4a2713aSLionel Sambuc 
373*f4a2713aSLionel Sambuc /// runOnFunction - Insert code to maintain the shadow stack.
374*f4a2713aSLionel Sambuc bool ShadowStackGC::performCustomLowering(Function &F) {
375*f4a2713aSLionel Sambuc   LLVMContext &Context = F.getContext();
376*f4a2713aSLionel Sambuc 
377*f4a2713aSLionel Sambuc   // Find calls to llvm.gcroot.
378*f4a2713aSLionel Sambuc   CollectRoots(F);
379*f4a2713aSLionel Sambuc 
380*f4a2713aSLionel Sambuc   // If there are no roots in this function, then there is no need to add a
381*f4a2713aSLionel Sambuc   // stack map entry for it.
382*f4a2713aSLionel Sambuc   if (Roots.empty())
383*f4a2713aSLionel Sambuc     return false;
384*f4a2713aSLionel Sambuc 
385*f4a2713aSLionel Sambuc   // Build the constant map and figure the type of the shadow stack entry.
386*f4a2713aSLionel Sambuc   Value *FrameMap = GetFrameMap(F);
387*f4a2713aSLionel Sambuc   Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
388*f4a2713aSLionel Sambuc 
389*f4a2713aSLionel Sambuc   // Build the shadow stack entry at the very start of the function.
390*f4a2713aSLionel Sambuc   BasicBlock::iterator IP = F.getEntryBlock().begin();
391*f4a2713aSLionel Sambuc   IRBuilder<> AtEntry(IP->getParent(), IP);
392*f4a2713aSLionel Sambuc 
393*f4a2713aSLionel Sambuc   Instruction *StackEntry   = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
394*f4a2713aSLionel Sambuc                                                    "gc_frame");
395*f4a2713aSLionel Sambuc 
396*f4a2713aSLionel Sambuc   while (isa<AllocaInst>(IP)) ++IP;
397*f4a2713aSLionel Sambuc   AtEntry.SetInsertPoint(IP->getParent(), IP);
398*f4a2713aSLionel Sambuc 
399*f4a2713aSLionel Sambuc   // Initialize the map pointer and load the current head of the shadow stack.
400*f4a2713aSLionel Sambuc   Instruction *CurrentHead  = AtEntry.CreateLoad(Head, "gc_currhead");
401*f4a2713aSLionel Sambuc   Instruction *EntryMapPtr  = CreateGEP(Context, AtEntry, StackEntry,
402*f4a2713aSLionel Sambuc                                         0,1,"gc_frame.map");
403*f4a2713aSLionel Sambuc   AtEntry.CreateStore(FrameMap, EntryMapPtr);
404*f4a2713aSLionel Sambuc 
405*f4a2713aSLionel Sambuc   // After all the allocas...
406*f4a2713aSLionel Sambuc   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
407*f4a2713aSLionel Sambuc     // For each root, find the corresponding slot in the aggregate...
408*f4a2713aSLionel Sambuc     Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root");
409*f4a2713aSLionel Sambuc 
410*f4a2713aSLionel Sambuc     // And use it in lieu of the alloca.
411*f4a2713aSLionel Sambuc     AllocaInst *OriginalAlloca = Roots[I].second;
412*f4a2713aSLionel Sambuc     SlotPtr->takeName(OriginalAlloca);
413*f4a2713aSLionel Sambuc     OriginalAlloca->replaceAllUsesWith(SlotPtr);
414*f4a2713aSLionel Sambuc   }
415*f4a2713aSLionel Sambuc 
416*f4a2713aSLionel Sambuc   // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
417*f4a2713aSLionel Sambuc   // really necessary (the collector would never see the intermediate state at
418*f4a2713aSLionel Sambuc   // runtime), but it's nicer not to push the half-initialized entry onto the
419*f4a2713aSLionel Sambuc   // shadow stack.
420*f4a2713aSLionel Sambuc   while (isa<StoreInst>(IP)) ++IP;
421*f4a2713aSLionel Sambuc   AtEntry.SetInsertPoint(IP->getParent(), IP);
422*f4a2713aSLionel Sambuc 
423*f4a2713aSLionel Sambuc   // Push the entry onto the shadow stack.
424*f4a2713aSLionel Sambuc   Instruction *EntryNextPtr = CreateGEP(Context, AtEntry,
425*f4a2713aSLionel Sambuc                                         StackEntry,0,0,"gc_frame.next");
426*f4a2713aSLionel Sambuc   Instruction *NewHeadVal   = CreateGEP(Context, AtEntry,
427*f4a2713aSLionel Sambuc                                         StackEntry, 0, "gc_newhead");
428*f4a2713aSLionel Sambuc   AtEntry.CreateStore(CurrentHead, EntryNextPtr);
429*f4a2713aSLionel Sambuc   AtEntry.CreateStore(NewHeadVal, Head);
430*f4a2713aSLionel Sambuc 
431*f4a2713aSLionel Sambuc   // For each instruction that escapes...
432*f4a2713aSLionel Sambuc   EscapeEnumerator EE(F, "gc_cleanup");
433*f4a2713aSLionel Sambuc   while (IRBuilder<> *AtExit = EE.Next()) {
434*f4a2713aSLionel Sambuc     // Pop the entry from the shadow stack. Don't reuse CurrentHead from
435*f4a2713aSLionel Sambuc     // AtEntry, since that would make the value live for the entire function.
436*f4a2713aSLionel Sambuc     Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0,
437*f4a2713aSLionel Sambuc                                            "gc_frame.next");
438*f4a2713aSLionel Sambuc     Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
439*f4a2713aSLionel Sambuc                        AtExit->CreateStore(SavedHead, Head);
440*f4a2713aSLionel Sambuc   }
441*f4a2713aSLionel Sambuc 
442*f4a2713aSLionel Sambuc   // Delete the original allocas (which are no longer used) and the intrinsic
443*f4a2713aSLionel Sambuc   // calls (which are no longer valid). Doing this last avoids invalidating
444*f4a2713aSLionel Sambuc   // iterators.
445*f4a2713aSLionel Sambuc   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
446*f4a2713aSLionel Sambuc     Roots[I].first->eraseFromParent();
447*f4a2713aSLionel Sambuc     Roots[I].second->eraseFromParent();
448*f4a2713aSLionel Sambuc   }
449*f4a2713aSLionel Sambuc 
450*f4a2713aSLionel Sambuc   Roots.clear();
451*f4a2713aSLionel Sambuc   return true;
452*f4a2713aSLionel Sambuc }
453