52#define DEBUG_TYPE "shadow-stack-gc-lowering"
56class ShadowStackGCLoweringImpl {
65 std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
69 std::vector<std::pair<uint64_t, uint64_t>> RootOffsets;
72 ShadowStackGCLoweringImpl() =
default;
74 bool doInitialization(
Module &M);
78 bool IsNullValue(
Value *V);
80 std::pair<uint64_t, Align> ComputeFrameLayout(
Function &
F);
85 ShadowStackGCLoweringImpl Impl;
90 ShadowStackGCLowering();
92 bool doInitialization(
Module &M)
override {
return Impl.doInitialization(M); }
97 std::optional<DomTreeUpdater> DTU;
98 if (
auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
99 DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
100 return Impl.runOnFunction(
F, DTU ? &*DTU :
nullptr);
109 if (!Map.contains(
"shadow-stack"))
112 ShadowStackGCLoweringImpl Impl;
113 bool Changed = Impl.doInitialization(M);
119 Changed |= Impl.runOnFunction(
F, DT ? &DTU :
nullptr);
129char ShadowStackGCLowering::ID = 0;
133 "Shadow Stack GC Lowering",
false,
false)
141ShadowStackGCLowering::ShadowStackGCLowering() :
FunctionPass(ID) {}
146 Type *VoidPtr = PointerType::getUnqual(
F.getContext());
149 unsigned NumMeta = 0;
151 for (
unsigned I = 0;
I != Roots.size(); ++
I) {
153 if (!
C->isNullValue())
159 Type *Int32Ty = Type::getInt32Ty(
F.getContext());
162 ConstantInt::get(Int32Ty, FrameSizeInPtrs,
false),
163 ConstantInt::get(Int32Ty, NumMeta,
false),
188 return new GlobalVariable(*
F.getParent(), FrameMap->
getType(),
true,
189 GlobalVariable::InternalLinkage, FrameMap,
190 "__gc_" +
F.getName());
193std::pair<uint64_t, Align>
194ShadowStackGCLoweringImpl::ComputeFrameLayout(
Function &
F) {
200 Align PtrAlign =
DL.getPointerABIAlignment(0);
203 Align MaxAlign = PtrAlign;
210 for (
const std::pair<CallInst *, AllocaInst *> &Root : Roots) {
211 AllocaInst *AI = Root.second;
213 if (!RootSize || !RootSize->isFixed())
215 "Intrinsic::gcroot requires a fixed size stack object");
218 MaxAlign = std::max(MaxAlign, RootAlign);
224 RootOffsets.push_back({AlignedOffset,
Size});
230 return {FrameSize, MaxAlign};
235bool ShadowStackGCLoweringImpl::doInitialization(
Module &M) {
238 if (
F.hasGC() &&
F.getGC() ==
"shadow-stack") {
251 std::vector<Type *> EltTys;
253 EltTys.push_back(Type::getInt32Ty(
M.getContext()));
255 EltTys.push_back(Type::getInt32Ty(
M.getContext()));
260 PointerType *StackEntryPtrTy = PointerType::getUnqual(
M.getContext());
263 Head =
M.getGlobalVariable(
"llvm_gc_root_chain");
267 Head =
new GlobalVariable(
278bool ShadowStackGCLoweringImpl::IsNullValue(
Value *V) {
280 return C->isNullValue();
284void ShadowStackGCLoweringImpl::CollectRoots(
Function &
F) {
285 assert(Roots.empty() &&
"Not cleaned up?");
289 for (BasicBlock &BB :
F)
290 for (Instruction &
I : BB)
292 if (
Function *
F = CI->getCalledFunction())
293 if (
F->getIntrinsicID() == Intrinsic::gcroot) {
294 std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
297 if (IsNullValue(CI->getArgOperand(1)))
298 Roots.push_back(Pair);
305 Roots.insert(Roots.begin(), MetaRoots.
begin(), MetaRoots.
end());
309bool ShadowStackGCLoweringImpl::runOnFunction(
Function &
F,
310 DomTreeUpdater *DTU) {
312 if (!
F.hasGC() ||
F.getGC() !=
"shadow-stack")
315 LLVMContext &
Context =
F.getContext();
327 auto [FrameSize, FrameAlign] = ComputeFrameLayout(
F);
331 Value *FrameMap = GetFrameMap(
F, FrameSize / PtrSize - 2);
337 AllocaInst *StackEntry = AtEntry.CreateAlloca(
338 ArrayType::get(Int8Ty, FrameSize),
nullptr,
"gc_frame");
341 AtEntry.SetInsertPointPastAllocas(&
F);
342 IP = AtEntry.GetInsertPoint();
346 AtEntry.CreateLoad(AtEntry.getPtrTy(), Head,
"gc_currhead");
349 Value *EntryMapPtr = AtEntry.CreatePtrAdd(
350 StackEntry, AtEntry.getInt64(PtrSize),
"gc_frame.map");
351 AtEntry.CreateStore(FrameMap, EntryMapPtr);
356 assert(RootOffsets.size() == Roots.size());
357 for (
unsigned I = 0,
E = Roots.size();
I !=
E; ++
I) {
358 auto [RootOffset, RootSize] = RootOffsets[
I];
361 if (RootOffset > LastEnd) {
363 AtEntry.CreatePtrAdd(StackEntry, AtEntry.getInt64(LastEnd));
364 AtEntry.CreateMemSet(PaddingPtr, AtEntry.getInt8(0), RootOffset - LastEnd,
369 Value *SlotPtr = AtEntry.CreatePtrAdd(
370 StackEntry, AtEntry.getInt64(RootOffset),
"gc_root");
373 AllocaInst *OriginalAlloca = Roots[
I].second;
377 LastEnd = RootOffset + RootSize;
381 if (FrameSize > LastEnd) {
383 AtEntry.CreatePtrAdd(StackEntry, AtEntry.getInt64(LastEnd));
384 AtEntry.CreateMemSet(PaddingPtr, AtEntry.getInt8(0), FrameSize - LastEnd,
394 AtEntry.SetInsertPoint(IP->getParent(), IP);
398 AtEntry.CreateStore(CurrentHead, StackEntry);
401 AtEntry.CreateStore(StackEntry, Head);
404 EscapeEnumerator EE(
F,
"gc_cleanup",
true, DTU);
410 AtExit->CreateLoad(AtExit->getPtrTy(), StackEntry,
"gc_savedhead");
411 AtExit->CreateStore(SavedHead, Head);
417 for (std::pair<CallInst *, AllocaInst *> &Root : Roots) {
418 Root.first->eraseFromParent();
419 Root.second->eraseFromParent();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool runOnFunction(Function &F, bool PostInlining)
Module.h This file contains the declarations for the Module class.
Machine Check Debug Module
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the SmallVector class.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
InstListType::iterator iterator
Instruction iterators...
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Analysis pass which computes a DominatorTree.
Legacy analysis pass which computes a DominatorTree.
FunctionPass class - This class is used to implement most global optimizations.
An analysis pass which caches information about the entire Module.
bool hasExternalLinkage() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
void setLinkage(LinkageTypes LT)
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
A Module instance is used to store all the information related to an LLVM module.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
void push_back(const T &Elt)
Class to represent struct types.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
std::string utostr(uint64_t X, bool isNeg=false)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI char & ShadowStackGCLoweringID
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI FunctionPass * createShadowStackGCLoweringPass()
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.