49#define DEBUG_TYPE "shadow-stack-gc-lowering"
64 std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
69 ShadowStackGCLowering();
76 bool IsNullValue(
Value *V);
85 Type *Ty,
Value *BasePtr,
int Idx1,
int Idx2,
91char ShadowStackGCLowering::ID = 0;
95 "Shadow Stack GC Lowering",
false,
false)
103ShadowStackGCLowering::ShadowStackGCLowering() :
FunctionPass(
ID) {
112 unsigned NumMeta = 0;
114 for (
unsigned I = 0;
I != Roots.size(); ++
I) {
115 Constant *
C = cast<Constant>(Roots[
I].first->getArgOperand(1));
116 if (!
C->isNullValue())
152 GlobalVariable::InternalLinkage, FrameMap,
153 "__gc_" +
F.getName());
161Type *ShadowStackGCLowering::GetConcreteStackEntryType(
Function &
F) {
163 std::vector<Type *> EltTys;
164 EltTys.push_back(StackEntryTy);
165 for (
const std::pair<CallInst *, AllocaInst *> &Root : Roots)
166 EltTys.push_back(Root.second->getAllocatedType());
173bool ShadowStackGCLowering::doInitialization(
Module &M) {
176 if (
F.hasGC() &&
F.getGC() == std::string(
"shadow-stack")) {
189 std::vector<Type *> EltTys;
195 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
206 EltTys.push_back(PointerType::getUnqual(StackEntryTy));
207 EltTys.push_back(FrameMapPtrTy);
208 StackEntryTy->setBody(EltTys);
209 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
212 Head =
M.getGlobalVariable(
"llvm_gc_root_chain");
219 }
else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
227bool ShadowStackGCLowering::IsNullValue(
Value *V) {
229 return C->isNullValue();
233void ShadowStackGCLowering::CollectRoots(
Function &
F) {
238 assert(Roots.empty() &&
"Not cleaned up?");
245 if (
Function *
F = CI->getCalledFunction())
246 if (
F->getIntrinsicID() == Intrinsic::gcroot) {
247 std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
249 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
250 if (IsNullValue(CI->getArgOperand(1)))
251 Roots.push_back(Pair);
258 Roots.insert(Roots.begin(), MetaRoots.
begin(), MetaRoots.
end());
269 Value *Val =
B.CreateGEP(Ty, BasePtr, Indices,
Name);
271 assert(isa<GetElementPtrInst>(Val) &&
"Unexpected folded constant");
273 return dyn_cast<GetElementPtrInst>(Val);
281 Value *Val =
B.CreateGEP(Ty, BasePtr, Indices,
Name);
283 assert(isa<GetElementPtrInst>(Val) &&
"Unexpected folded constant");
285 return dyn_cast<GetElementPtrInst>(Val);
288void ShadowStackGCLowering::getAnalysisUsage(
AnalysisUsage &AU)
const {
293bool ShadowStackGCLowering::runOnFunction(
Function &
F) {
296 F.getGC() != std::string(
"shadow-stack"))
309 std::optional<DomTreeUpdater> DTU;
310 if (
auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
311 DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
314 Value *FrameMap = GetFrameMap(
F);
315 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(
F);
322 AtEntry.CreateAlloca(ConcreteStackEntryTy,
nullptr,
"gc_frame");
324 AtEntry.SetInsertPointPastAllocas(&
F);
325 IP = AtEntry.GetInsertPoint();
329 AtEntry.CreateLoad(StackEntryTy->getPointerTo(), Head,
"gc_currhead");
330 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
331 StackEntry, 0, 1,
"gc_frame.map");
332 AtEntry.CreateStore(FrameMap, EntryMapPtr);
335 for (
unsigned I = 0,
E = Roots.size();
I !=
E; ++
I) {
337 Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
338 StackEntry, 1 +
I,
"gc_root");
350 while (isa<StoreInst>(IP))
352 AtEntry.SetInsertPoint(IP->getParent(), IP);
355 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
356 StackEntry, 0, 0,
"gc_frame.next");
357 Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
358 StackEntry, 0,
"gc_newhead");
359 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
360 AtEntry.CreateStore(NewHeadVal, Head);
364 DTU ? &*DTU :
nullptr);
369 CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
371 Value *SavedHead = AtExit->CreateLoad(StackEntryTy->getPointerTo(),
372 EntryNextPtr2,
"gc_savedhead");
373 AtExit->CreateStore(SavedHead, Head);
379 for (std::pair<CallInst *, AllocaInst *> &Root : Roots) {
380 Root.first->eraseFromParent();
381 Root.second->eraseFromParent();
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Module.h This file contains the declarations for the Module class.
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
an instruction to allocate memory on the stack
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
InstListType::iterator iterator
Instruction iterators...
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< unsigned > InRangeIndex=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Legacy analysis pass which computes a DominatorTree.
EscapeEnumerator - This is a little algorithm to find all escape points from a function so that "fina...
FunctionPass class - This class is used to implement most global optimizations.
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
An analysis pass which caches information about the entire Module.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
A Module instance is used to store all the information related to an LLVM module.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent struct types.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
The instances of the Type class are immutable: once they are created, they are never changed.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
static IntegerType * getInt32Ty(LLVMContext &C)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
This is an optimization pass for GlobalISel generic memory operations.
char & ShadowStackGCLoweringID
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.
void initializeShadowStackGCLoweringPass(PassRegistry &)
FunctionPass * createShadowStackGCLoweringPass()
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.