53#define DEBUG_TYPE "shadow-stack-gc-lowering"
57class ShadowStackGCLoweringImpl {
66 std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
70 std::vector<std::pair<uint64_t, uint64_t>> RootOffsets;
73 ShadowStackGCLoweringImpl() =
default;
75 bool doInitialization(
Module &M);
79 bool IsNullValue(
Value *V);
81 std::pair<uint64_t, Align> ComputeFrameLayout(
Function &
F);
86 ShadowStackGCLoweringImpl Impl;
91 ShadowStackGCLowering();
93 bool doInitialization(
Module &M)
override {
return Impl.doInitialization(M); }
98 std::optional<DomTreeUpdater> DTU;
99 if (
auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
100 DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
101 return Impl.runOnFunction(
F, DTU ? &*DTU :
nullptr);
110 if (!Map.contains(
"shadow-stack"))
113 ShadowStackGCLoweringImpl Impl;
114 bool Changed = Impl.doInitialization(M);
120 Changed |= Impl.runOnFunction(
F, DT ? &DTU :
nullptr);
130char ShadowStackGCLowering::ID = 0;
134 "Shadow Stack GC Lowering",
false,
false)
142ShadowStackGCLowering::ShadowStackGCLowering() :
FunctionPass(
ID) {}
147 Type *VoidPtr = PointerType::getUnqual(
F.getContext());
150 unsigned NumMeta = 0;
152 for (
unsigned I = 0;
I != Roots.size(); ++
I) {
154 if (!
C->isNullValue())
163 ConstantInt::get(
Int32Ty, FrameSizeInPtrs,
false),
164 ConstantInt::get(
Int32Ty, NumMeta,
false),
189 return new GlobalVariable(*
F.getParent(), FrameMap->
getType(),
true,
190 GlobalVariable::InternalLinkage, FrameMap,
191 "__gc_" +
F.getName());
194std::pair<uint64_t, Align>
195ShadowStackGCLoweringImpl::ComputeFrameLayout(Function &
F) {
200 uint64_t PtrSize =
DL.getPointerSize(0);
201 Align PtrAlign =
DL.getPointerABIAlignment(0);
204 Align MaxAlign = PtrAlign;
208 uint64_t
Offset = 2 * PtrSize;
211 for (
const std::pair<CallInst *, AllocaInst *> &Root : Roots) {
212 AllocaInst *AI = Root.second;
214 if (!RootSize || !RootSize->isFixed())
216 "Intrinsic::gcroot requires a fixed size stack object");
217 uint64_t
Size = RootSize->getFixedValue();
219 MaxAlign = std::max(MaxAlign, RootAlign);
225 RootOffsets.push_back({AlignedOffset,
Size});
231 return {FrameSize, MaxAlign};
236bool ShadowStackGCLoweringImpl::doInitialization(
Module &M) {
238 for (Function &
F : M) {
239 if (
F.hasGC() &&
F.getGC() ==
"shadow-stack") {
252 std::vector<Type *> EltTys;
254 EltTys.push_back(Type::getInt32Ty(
M.getContext()));
256 EltTys.push_back(Type::getInt32Ty(
M.getContext()));
261 PointerType *StackEntryPtrTy = PointerType::getUnqual(
M.getContext());
264 Head =
M.getGlobalVariable(
"llvm_gc_root_chain");
268 Head =
new GlobalVariable(
279bool ShadowStackGCLoweringImpl::IsNullValue(
Value *V) {
281 return C->isNullValue();
285void ShadowStackGCLoweringImpl::CollectRoots(Function &
F) {
286 assert(Roots.empty() &&
"Not cleaned up?");
290 for (BasicBlock &BB :
F)
291 for (Instruction &
I : BB)
293 if (Function *
F = CI->getCalledFunction())
294 if (
F->getIntrinsicID() == Intrinsic::gcroot) {
295 std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
298 if (IsNullValue(CI->getArgOperand(1)))
299 Roots.push_back(Pair);
306 Roots.insert(Roots.begin(), MetaRoots.
begin(), MetaRoots.
end());
310bool ShadowStackGCLoweringImpl::runOnFunction(Function &
F,
311 DomTreeUpdater *DTU) {
313 if (!
F.hasGC() ||
F.getGC() !=
"shadow-stack")
316 LLVMContext &
Context =
F.getContext();
328 auto [FrameSize, FrameAlign] = ComputeFrameLayout(
F);
331 uint64_t PtrSize =
DL.getPointerSize();
332 Value *FrameMap = GetFrameMap(
F, FrameSize / PtrSize - 2);
338 AllocaInst *StackEntry = AtEntry.CreateAlloca(
339 ArrayType::get(Int8Ty, FrameSize),
nullptr,
"gc_frame");
342 AtEntry.SetInsertPointPastAllocas(&
F);
343 IP = AtEntry.GetInsertPoint();
347 AtEntry.CreateLoad(AtEntry.getPtrTy(), Head,
"gc_currhead");
350 Value *EntryMapPtr = AtEntry.CreatePtrAdd(
351 StackEntry, AtEntry.getInt64(PtrSize),
"gc_frame.map");
352 AtEntry.CreateStore(FrameMap, EntryMapPtr);
356 uint64_t LastEnd = 2 * PtrSize;
357 assert(RootOffsets.size() == Roots.size());
358 for (
unsigned I = 0,
E = Roots.size();
I !=
E; ++
I) {
359 auto [RootOffset, RootSize] = RootOffsets[
I];
362 if (RootOffset > LastEnd) {
364 AtEntry.CreatePtrAdd(StackEntry, AtEntry.getInt64(LastEnd));
365 AtEntry.CreateMemSet(PaddingPtr, AtEntry.getInt8(0), RootOffset - LastEnd,
370 Value *SlotPtr = AtEntry.CreatePtrAdd(
371 StackEntry, AtEntry.getInt64(RootOffset),
"gc_root");
374 AllocaInst *OriginalAlloca = Roots[
I].second;
378 LastEnd = RootOffset + RootSize;
382 if (FrameSize > LastEnd) {
384 AtEntry.CreatePtrAdd(StackEntry, AtEntry.getInt64(LastEnd));
385 AtEntry.CreateMemSet(PaddingPtr, AtEntry.getInt8(0), FrameSize - LastEnd,
395 AtEntry.SetInsertPoint(IP->getParent(), IP);
399 AtEntry.CreateStore(CurrentHead, StackEntry);
402 AtEntry.CreateStore(StackEntry, Head);
405 EscapeEnumerator EE(
F,
"gc_cleanup",
true, DTU);
411 AtExit->CreateLoad(AtExit->getPtrTy(), StackEntry,
"gc_savedhead");
412 AtExit->CreateStore(SavedHead, Head);
418 for (std::pair<CallInst *, AllocaInst *> &Root : Roots) {
419 Root.first->eraseFromParent();
420 Root.second->eraseFromParent();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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.
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
std::string utostr(uint64_t X, bool isNeg=false)
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.