#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Transforms/Utils/EscapeEnumerator.h"
#include <cassert>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "shadow-stack-gc-lowering"
namespace {
class ShadowStackGCLowering : public FunctionPass {
GlobalVariable *Head = nullptr;
StructType *StackEntryTy = nullptr;
StructType *FrameMapTy = nullptr;
std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
public:
static char ID;
ShadowStackGCLowering();
bool doInitialization(Module &M) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
private:
bool IsNullValue(Value *V);
Constant *GetFrameMap(Function &F);
Type *GetConcreteStackEntryType(Function &F);
void CollectRoots(Function &F);
static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
Type *Ty, Value *BasePtr, int Idx1,
const char *Name);
static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
Type *Ty, Value *BasePtr, int Idx1, int Idx2,
const char *Name);
};
}
char ShadowStackGCLowering::ID = 0;
char &llvm::ShadowStackGCLoweringID = ShadowStackGCLowering::ID;
INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, DEBUG_TYPE,
"Shadow Stack GC Lowering", false, false)
INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(ShadowStackGCLowering, DEBUG_TYPE,
"Shadow Stack GC Lowering", false, false)
FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
ShadowStackGCLowering::ShadowStackGCLowering() : FunctionPass(ID) {
initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
}
Constant *ShadowStackGCLowering::GetFrameMap(Function &F) {
Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
unsigned NumMeta = 0;
SmallVector<Constant *, 16> Metadata;
for (unsigned I = 0; I != Roots.size(); ++I) {
Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
if (!C->isNullValue())
NumMeta = I + 1;
Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
}
Metadata.resize(NumMeta);
Type *Int32Ty = Type::getInt32Ty(F.getContext());
Constant *BaseElts[] = {
ConstantInt::get(Int32Ty, Roots.size(), false),
ConstantInt::get(Int32Ty, NumMeta, false),
};
Constant *DescriptorElts[] = {
ConstantStruct::get(FrameMapTy, BaseElts),
ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
GlobalVariable::InternalLinkage, FrameMap,
"__gc_" + F.getName());
Constant *GEPIndices[2] = {
ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices);
}
Type *ShadowStackGCLowering::GetConcreteStackEntryType(Function &F) {
std::vector<Type *> EltTys;
EltTys.push_back(StackEntryTy);
for (const std::pair<CallInst *, AllocaInst *> &Root : Roots)
EltTys.push_back(Root.second->getAllocatedType());
return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str());
}
bool ShadowStackGCLowering::doInitialization(Module &M) {
bool Active = false;
for (Function &F : M) {
if (F.hasGC() && F.getGC() == std::string("shadow-stack")) {
Active = true;
break;
}
}
if (!Active)
return false;
std::vector<Type *> EltTys;
EltTys.push_back(Type::getInt32Ty(M.getContext()));
EltTys.push_back(Type::getInt32Ty(M.getContext()));
FrameMapTy = StructType::create(EltTys, "gc_map");
PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
EltTys.clear();
EltTys.push_back(PointerType::getUnqual(StackEntryTy));
EltTys.push_back(FrameMapPtrTy);
StackEntryTy->setBody(EltTys);
PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
Head = M.getGlobalVariable("llvm_gc_root_chain");
if (!Head) {
Head = new GlobalVariable(
M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
} else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
}
return true;
}
bool ShadowStackGCLowering::IsNullValue(Value *V) {
if (Constant *C = dyn_cast<Constant>(V))
return C->isNullValue();
return false;
}
void ShadowStackGCLowering::CollectRoots(Function &F) {
assert(Roots.empty() && "Not cleaned up?");
SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
for (BasicBlock &BB : F)
for (Instruction &I : BB)
if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(&I))
if (Function *F = CI->getCalledFunction())
if (F->getIntrinsicID() == Intrinsic::gcroot) {
std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
CI,
cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
if (IsNullValue(CI->getArgOperand(1)))
Roots.push_back(Pair);
else
MetaRoots.push_back(Pair);
}
Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
}
GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
IRBuilder<> &B, Type *Ty,
Value *BasePtr, int Idx,
int Idx2,
const char *Name) {
Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
ConstantInt::get(Type::getInt32Ty(Context), Idx),
ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
return dyn_cast<GetElementPtrInst>(Val);
}
GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
IRBuilder<> &B, Type *Ty, Value *BasePtr,
int Idx, const char *Name) {
Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
ConstantInt::get(Type::getInt32Ty(Context), Idx)};
Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
return dyn_cast<GetElementPtrInst>(Val);
}
void ShadowStackGCLowering::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<DominatorTreeWrapperPass>();
}
bool ShadowStackGCLowering::runOnFunction(Function &F) {
if (!F.hasGC() ||
F.getGC() != std::string("shadow-stack"))
return false;
LLVMContext &Context = F.getContext();
CollectRoots(F);
if (Roots.empty())
return false;
Optional<DomTreeUpdater> DTU;
if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
Value *FrameMap = GetFrameMap(F);
Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
BasicBlock::iterator IP = F.getEntryBlock().begin();
IRBuilder<> AtEntry(IP->getParent(), IP);
Instruction *StackEntry =
AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
while (isa<AllocaInst>(IP))
++IP;
AtEntry.SetInsertPoint(IP->getParent(), IP);
Instruction *CurrentHead =
AtEntry.CreateLoad(StackEntryTy->getPointerTo(), Head, "gc_currhead");
Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
StackEntry, 0, 1, "gc_frame.map");
AtEntry.CreateStore(FrameMap, EntryMapPtr);
for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
StackEntry, 1 + I, "gc_root");
AllocaInst *OriginalAlloca = Roots[I].second;
SlotPtr->takeName(OriginalAlloca);
OriginalAlloca->replaceAllUsesWith(SlotPtr);
}
while (isa<StoreInst>(IP))
++IP;
AtEntry.SetInsertPoint(IP->getParent(), IP);
Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
StackEntry, 0, 0, "gc_frame.next");
Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
StackEntry, 0, "gc_newhead");
AtEntry.CreateStore(CurrentHead, EntryNextPtr);
AtEntry.CreateStore(NewHeadVal, Head);
EscapeEnumerator EE(F, "gc_cleanup", true,
DTU ? DTU.getPointer() : nullptr);
while (IRBuilder<> *AtExit = EE.Next()) {
Instruction *EntryNextPtr2 =
CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
"gc_frame.next");
Value *SavedHead = AtExit->CreateLoad(StackEntryTy->getPointerTo(),
EntryNextPtr2, "gc_savedhead");
AtExit->CreateStore(SavedHead, Head);
}
for (std::pair<CallInst *, AllocaInst *> &Root : Roots) {
Root.first->eraseFromParent();
Root.second->eraseFromParent();
}
Roots.clear();
return true;
}