10b57cec5SDimitry Andric //===- SafeStack.cpp - Safe Stack Insertion -------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass splits the stack into the safe stack (kept as-is for LLVM backend)
100b57cec5SDimitry Andric // and the unsafe stack (explicitly allocated and managed through the runtime
110b57cec5SDimitry Andric // support library).
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric // http://clang.llvm.org/docs/SafeStack.html
140b57cec5SDimitry Andric //
150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
160b57cec5SDimitry Andric 
170b57cec5SDimitry Andric #include "SafeStackLayout.h"
180b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
190b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
205ffd83dbSDimitry Andric #include "llvm/ADT/BitVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
230b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
26*5f7ddb14SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/InlineCost.h"
280b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
290b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
300b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
315ffd83dbSDimitry Andric #include "llvm/Analysis/StackLifetime.h"
320b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
360b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
370b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
380b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
390b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
400b57cec5SDimitry Andric #include "llvm/IR/DIBuilder.h"
410b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
420b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
430b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
440b57cec5SDimitry Andric #include "llvm/IR/Function.h"
450b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
460b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
470b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
480b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
490b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
500b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
510b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
520b57cec5SDimitry Andric #include "llvm/IR/Module.h"
530b57cec5SDimitry Andric #include "llvm/IR/Type.h"
540b57cec5SDimitry Andric #include "llvm/IR/Use.h"
550b57cec5SDimitry Andric #include "llvm/IR/User.h"
560b57cec5SDimitry Andric #include "llvm/IR/Value.h"
57480093f4SDimitry Andric #include "llvm/InitializePasses.h"
580b57cec5SDimitry Andric #include "llvm/Pass.h"
590b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
600b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
610b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
620b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
630b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
640b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
650b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
660b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
67480093f4SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
680b57cec5SDimitry Andric #include <algorithm>
690b57cec5SDimitry Andric #include <cassert>
700b57cec5SDimitry Andric #include <cstdint>
710b57cec5SDimitry Andric #include <string>
720b57cec5SDimitry Andric #include <utility>
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric using namespace llvm;
750b57cec5SDimitry Andric using namespace llvm::safestack;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric #define DEBUG_TYPE "safe-stack"
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric namespace llvm {
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric STATISTIC(NumFunctions, "Total number of functions");
820b57cec5SDimitry Andric STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
830b57cec5SDimitry Andric STATISTIC(NumUnsafeStackRestorePointsFunctions,
840b57cec5SDimitry Andric           "Number of functions that use setjmp or exceptions");
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric STATISTIC(NumAllocas, "Total number of allocas");
870b57cec5SDimitry Andric STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
880b57cec5SDimitry Andric STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
890b57cec5SDimitry Andric STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
900b57cec5SDimitry Andric STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric } // namespace llvm
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric /// Use __safestack_pointer_address even if the platform has a faster way of
950b57cec5SDimitry Andric /// access safe stack pointer.
960b57cec5SDimitry Andric static cl::opt<bool>
970b57cec5SDimitry Andric     SafeStackUsePointerAddress("safestack-use-pointer-address",
980b57cec5SDimitry Andric                                   cl::init(false), cl::Hidden);
990b57cec5SDimitry Andric 
1005ffd83dbSDimitry Andric // Disabled by default due to PR32143.
1015ffd83dbSDimitry Andric static cl::opt<bool> ClColoring("safe-stack-coloring",
1025ffd83dbSDimitry Andric                                 cl::desc("enable safe stack coloring"),
1035ffd83dbSDimitry Andric                                 cl::Hidden, cl::init(false));
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric namespace {
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric /// Rewrite an SCEV expression for a memory access address to an expression that
1080b57cec5SDimitry Andric /// represents offset from the given alloca.
1090b57cec5SDimitry Andric ///
1100b57cec5SDimitry Andric /// The implementation simply replaces all mentions of the alloca with zero.
1110b57cec5SDimitry Andric class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
1120b57cec5SDimitry Andric   const Value *AllocaPtr;
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric public:
AllocaOffsetRewriter(ScalarEvolution & SE,const Value * AllocaPtr)1150b57cec5SDimitry Andric   AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
1160b57cec5SDimitry Andric       : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
1170b57cec5SDimitry Andric 
visitUnknown(const SCEVUnknown * Expr)1180b57cec5SDimitry Andric   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1190b57cec5SDimitry Andric     if (Expr->getValue() == AllocaPtr)
1200b57cec5SDimitry Andric       return SE.getZero(Expr->getType());
1210b57cec5SDimitry Andric     return Expr;
1220b57cec5SDimitry Andric   }
1230b57cec5SDimitry Andric };
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric /// The SafeStack pass splits the stack of each function into the safe
1260b57cec5SDimitry Andric /// stack, which is only accessed through memory safe dereferences (as
1270b57cec5SDimitry Andric /// determined statically), and the unsafe stack, which contains all
1280b57cec5SDimitry Andric /// local variables that are accessed in ways that we can't prove to
1290b57cec5SDimitry Andric /// be safe.
1300b57cec5SDimitry Andric class SafeStack {
1310b57cec5SDimitry Andric   Function &F;
1320b57cec5SDimitry Andric   const TargetLoweringBase &TL;
1330b57cec5SDimitry Andric   const DataLayout &DL;
134*5f7ddb14SDimitry Andric   DomTreeUpdater *DTU;
1350b57cec5SDimitry Andric   ScalarEvolution &SE;
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   Type *StackPtrTy;
1380b57cec5SDimitry Andric   Type *IntPtrTy;
1390b57cec5SDimitry Andric   Type *Int32Ty;
1400b57cec5SDimitry Andric   Type *Int8Ty;
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   Value *UnsafeStackPtr = nullptr;
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric   /// Unsafe stack alignment. Each stack frame must ensure that the stack is
1450b57cec5SDimitry Andric   /// aligned to this value. We need to re-align the unsafe stack if the
1460b57cec5SDimitry Andric   /// alignment of any object on the stack exceeds this value.
1470b57cec5SDimitry Andric   ///
1480b57cec5SDimitry Andric   /// 16 seems like a reasonable upper bound on the alignment of objects that we
1490b57cec5SDimitry Andric   /// might expect to appear on the stack on most common targets.
1500b57cec5SDimitry Andric   enum { StackAlignment = 16 };
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   /// Return the value of the stack canary.
1530b57cec5SDimitry Andric   Value *getStackGuard(IRBuilder<> &IRB, Function &F);
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric   /// Load stack guard from the frame and check if it has changed.
156af732203SDimitry Andric   void checkStackGuard(IRBuilder<> &IRB, Function &F, Instruction &RI,
1570b57cec5SDimitry Andric                        AllocaInst *StackGuardSlot, Value *StackGuard);
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   /// Find all static allocas, dynamic allocas, return instructions and
1600b57cec5SDimitry Andric   /// stack restore points (exception unwind blocks and setjmp calls) in the
1610b57cec5SDimitry Andric   /// given function and append them to the respective vectors.
1620b57cec5SDimitry Andric   void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
1630b57cec5SDimitry Andric                  SmallVectorImpl<AllocaInst *> &DynamicAllocas,
1640b57cec5SDimitry Andric                  SmallVectorImpl<Argument *> &ByValArguments,
165af732203SDimitry Andric                  SmallVectorImpl<Instruction *> &Returns,
1660b57cec5SDimitry Andric                  SmallVectorImpl<Instruction *> &StackRestorePoints);
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   /// Calculate the allocation size of a given alloca. Returns 0 if the
1690b57cec5SDimitry Andric   /// size can not be statically determined.
1700b57cec5SDimitry Andric   uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   /// Allocate space for all static allocas in \p StaticAllocas,
173af732203SDimitry Andric   /// replace allocas with pointers into the unsafe stack.
1740b57cec5SDimitry Andric   ///
1750b57cec5SDimitry Andric   /// \returns A pointer to the top of the unsafe stack after all unsafe static
1760b57cec5SDimitry Andric   /// allocas are allocated.
1770b57cec5SDimitry Andric   Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
1780b57cec5SDimitry Andric                                         ArrayRef<AllocaInst *> StaticAllocas,
1790b57cec5SDimitry Andric                                         ArrayRef<Argument *> ByValArguments,
1800b57cec5SDimitry Andric                                         Instruction *BasePointer,
1810b57cec5SDimitry Andric                                         AllocaInst *StackGuardSlot);
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric   /// Generate code to restore the stack after all stack restore points
1840b57cec5SDimitry Andric   /// in \p StackRestorePoints.
1850b57cec5SDimitry Andric   ///
1860b57cec5SDimitry Andric   /// \returns A local variable in which to maintain the dynamic top of the
1870b57cec5SDimitry Andric   /// unsafe stack if needed.
1880b57cec5SDimitry Andric   AllocaInst *
1890b57cec5SDimitry Andric   createStackRestorePoints(IRBuilder<> &IRB, Function &F,
1900b57cec5SDimitry Andric                            ArrayRef<Instruction *> StackRestorePoints,
1910b57cec5SDimitry Andric                            Value *StaticTop, bool NeedDynamicTop);
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   /// Replace all allocas in \p DynamicAllocas with code to allocate
1940b57cec5SDimitry Andric   /// space dynamically on the unsafe stack and store the dynamic unsafe stack
1950b57cec5SDimitry Andric   /// top to \p DynamicTop if non-null.
1960b57cec5SDimitry Andric   void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
1970b57cec5SDimitry Andric                                        AllocaInst *DynamicTop,
1980b57cec5SDimitry Andric                                        ArrayRef<AllocaInst *> DynamicAllocas);
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
2030b57cec5SDimitry Andric                           const Value *AllocaPtr, uint64_t AllocaSize);
2040b57cec5SDimitry Andric   bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
2050b57cec5SDimitry Andric                     uint64_t AllocaSize);
2060b57cec5SDimitry Andric 
2075ffd83dbSDimitry Andric   bool ShouldInlinePointerAddress(CallInst &CI);
2080b57cec5SDimitry Andric   void TryInlinePointerAddress();
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric public:
SafeStack(Function & F,const TargetLoweringBase & TL,const DataLayout & DL,DomTreeUpdater * DTU,ScalarEvolution & SE)2110b57cec5SDimitry Andric   SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL,
212*5f7ddb14SDimitry Andric             DomTreeUpdater *DTU, ScalarEvolution &SE)
213*5f7ddb14SDimitry Andric       : F(F), TL(TL), DL(DL), DTU(DTU), SE(SE),
2140b57cec5SDimitry Andric         StackPtrTy(Type::getInt8PtrTy(F.getContext())),
2150b57cec5SDimitry Andric         IntPtrTy(DL.getIntPtrType(F.getContext())),
2160b57cec5SDimitry Andric         Int32Ty(Type::getInt32Ty(F.getContext())),
2170b57cec5SDimitry Andric         Int8Ty(Type::getInt8Ty(F.getContext())) {}
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric   // Run the transformation on the associated function.
2200b57cec5SDimitry Andric   // Returns whether the function was changed.
2210b57cec5SDimitry Andric   bool run();
2220b57cec5SDimitry Andric };
2230b57cec5SDimitry Andric 
getStaticAllocaAllocationSize(const AllocaInst * AI)2240b57cec5SDimitry Andric uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
2250b57cec5SDimitry Andric   uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType());
2260b57cec5SDimitry Andric   if (AI->isArrayAllocation()) {
2270b57cec5SDimitry Andric     auto C = dyn_cast<ConstantInt>(AI->getArraySize());
2280b57cec5SDimitry Andric     if (!C)
2290b57cec5SDimitry Andric       return 0;
2300b57cec5SDimitry Andric     Size *= C->getZExtValue();
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric   return Size;
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric 
IsAccessSafe(Value * Addr,uint64_t AccessSize,const Value * AllocaPtr,uint64_t AllocaSize)2350b57cec5SDimitry Andric bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
2360b57cec5SDimitry Andric                              const Value *AllocaPtr, uint64_t AllocaSize) {
2370b57cec5SDimitry Andric   AllocaOffsetRewriter Rewriter(SE, AllocaPtr);
2380b57cec5SDimitry Andric   const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   uint64_t BitWidth = SE.getTypeSizeInBits(Expr->getType());
2410b57cec5SDimitry Andric   ConstantRange AccessStartRange = SE.getUnsignedRange(Expr);
2420b57cec5SDimitry Andric   ConstantRange SizeRange =
2430b57cec5SDimitry Andric       ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
2440b57cec5SDimitry Andric   ConstantRange AccessRange = AccessStartRange.add(SizeRange);
2450b57cec5SDimitry Andric   ConstantRange AllocaRange =
2460b57cec5SDimitry Andric       ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
2470b57cec5SDimitry Andric   bool Safe = AllocaRange.contains(AccessRange);
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   LLVM_DEBUG(
2500b57cec5SDimitry Andric       dbgs() << "[SafeStack] "
2510b57cec5SDimitry Andric              << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
2520b57cec5SDimitry Andric              << *AllocaPtr << "\n"
2530b57cec5SDimitry Andric              << "            Access " << *Addr << "\n"
2540b57cec5SDimitry Andric              << "            SCEV " << *Expr
2550b57cec5SDimitry Andric              << " U: " << SE.getUnsignedRange(Expr)
2560b57cec5SDimitry Andric              << ", S: " << SE.getSignedRange(Expr) << "\n"
2570b57cec5SDimitry Andric              << "            Range " << AccessRange << "\n"
2580b57cec5SDimitry Andric              << "            AllocaRange " << AllocaRange << "\n"
2590b57cec5SDimitry Andric              << "            " << (Safe ? "safe" : "unsafe") << "\n");
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   return Safe;
2620b57cec5SDimitry Andric }
2630b57cec5SDimitry Andric 
IsMemIntrinsicSafe(const MemIntrinsic * MI,const Use & U,const Value * AllocaPtr,uint64_t AllocaSize)2640b57cec5SDimitry Andric bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
2650b57cec5SDimitry Andric                                    const Value *AllocaPtr,
2660b57cec5SDimitry Andric                                    uint64_t AllocaSize) {
2670b57cec5SDimitry Andric   if (auto MTI = dyn_cast<MemTransferInst>(MI)) {
2680b57cec5SDimitry Andric     if (MTI->getRawSource() != U && MTI->getRawDest() != U)
2690b57cec5SDimitry Andric       return true;
2700b57cec5SDimitry Andric   } else {
2710b57cec5SDimitry Andric     if (MI->getRawDest() != U)
2720b57cec5SDimitry Andric       return true;
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
2760b57cec5SDimitry Andric   // Non-constant size => unsafe. FIXME: try SCEV getRange.
2770b57cec5SDimitry Andric   if (!Len) return false;
2780b57cec5SDimitry Andric   return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
2790b57cec5SDimitry Andric }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric /// Check whether a given allocation must be put on the safe
2820b57cec5SDimitry Andric /// stack or not. The function analyzes all uses of AI and checks whether it is
2830b57cec5SDimitry Andric /// only accessed in a memory safe way (as decided statically).
IsSafeStackAlloca(const Value * AllocaPtr,uint64_t AllocaSize)2840b57cec5SDimitry Andric bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
2850b57cec5SDimitry Andric   // Go through all uses of this alloca and check whether all accesses to the
2860b57cec5SDimitry Andric   // allocated object are statically known to be memory safe and, hence, the
2870b57cec5SDimitry Andric   // object can be placed on the safe stack.
2880b57cec5SDimitry Andric   SmallPtrSet<const Value *, 16> Visited;
2890b57cec5SDimitry Andric   SmallVector<const Value *, 8> WorkList;
2900b57cec5SDimitry Andric   WorkList.push_back(AllocaPtr);
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric   // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
2930b57cec5SDimitry Andric   while (!WorkList.empty()) {
2940b57cec5SDimitry Andric     const Value *V = WorkList.pop_back_val();
2950b57cec5SDimitry Andric     for (const Use &UI : V->uses()) {
2960b57cec5SDimitry Andric       auto I = cast<const Instruction>(UI.getUser());
2970b57cec5SDimitry Andric       assert(V == UI.get());
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric       switch (I->getOpcode()) {
3000b57cec5SDimitry Andric       case Instruction::Load:
3010b57cec5SDimitry Andric         if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr,
3020b57cec5SDimitry Andric                           AllocaSize))
3030b57cec5SDimitry Andric           return false;
3040b57cec5SDimitry Andric         break;
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric       case Instruction::VAArg:
3070b57cec5SDimitry Andric         // "va-arg" from a pointer is safe.
3080b57cec5SDimitry Andric         break;
3090b57cec5SDimitry Andric       case Instruction::Store:
3100b57cec5SDimitry Andric         if (V == I->getOperand(0)) {
3110b57cec5SDimitry Andric           // Stored the pointer - conservatively assume it may be unsafe.
3120b57cec5SDimitry Andric           LLVM_DEBUG(dbgs()
3130b57cec5SDimitry Andric                      << "[SafeStack] Unsafe alloca: " << *AllocaPtr
3140b57cec5SDimitry Andric                      << "\n            store of address: " << *I << "\n");
3150b57cec5SDimitry Andric           return false;
3160b57cec5SDimitry Andric         }
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric         if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()),
3190b57cec5SDimitry Andric                           AllocaPtr, AllocaSize))
3200b57cec5SDimitry Andric           return false;
3210b57cec5SDimitry Andric         break;
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric       case Instruction::Ret:
3240b57cec5SDimitry Andric         // Information leak.
3250b57cec5SDimitry Andric         return false;
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric       case Instruction::Call:
3280b57cec5SDimitry Andric       case Instruction::Invoke: {
3295ffd83dbSDimitry Andric         const CallBase &CS = *cast<CallBase>(I);
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric         if (I->isLifetimeStartOrEnd())
3320b57cec5SDimitry Andric           continue;
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric         if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
3350b57cec5SDimitry Andric           if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
3360b57cec5SDimitry Andric             LLVM_DEBUG(dbgs()
3370b57cec5SDimitry Andric                        << "[SafeStack] Unsafe alloca: " << *AllocaPtr
3380b57cec5SDimitry Andric                        << "\n            unsafe memintrinsic: " << *I << "\n");
3390b57cec5SDimitry Andric             return false;
3400b57cec5SDimitry Andric           }
3410b57cec5SDimitry Andric           continue;
3420b57cec5SDimitry Andric         }
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric         // LLVM 'nocapture' attribute is only set for arguments whose address
3450b57cec5SDimitry Andric         // is not stored, passed around, or used in any other non-trivial way.
3460b57cec5SDimitry Andric         // We assume that passing a pointer to an object as a 'nocapture
3470b57cec5SDimitry Andric         // readnone' argument is safe.
3480b57cec5SDimitry Andric         // FIXME: a more precise solution would require an interprocedural
3490b57cec5SDimitry Andric         // analysis here, which would look at all uses of an argument inside
3500b57cec5SDimitry Andric         // the function being called.
3515ffd83dbSDimitry Andric         auto B = CS.arg_begin(), E = CS.arg_end();
3525ffd83dbSDimitry Andric         for (auto A = B; A != E; ++A)
3530b57cec5SDimitry Andric           if (A->get() == V)
3540b57cec5SDimitry Andric             if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
3550b57cec5SDimitry Andric                                                CS.doesNotAccessMemory()))) {
3560b57cec5SDimitry Andric               LLVM_DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
3570b57cec5SDimitry Andric                                 << "\n            unsafe call: " << *I << "\n");
3580b57cec5SDimitry Andric               return false;
3590b57cec5SDimitry Andric             }
3600b57cec5SDimitry Andric         continue;
3610b57cec5SDimitry Andric       }
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric       default:
3640b57cec5SDimitry Andric         if (Visited.insert(I).second)
3650b57cec5SDimitry Andric           WorkList.push_back(cast<const Instruction>(I));
3660b57cec5SDimitry Andric       }
3670b57cec5SDimitry Andric     }
3680b57cec5SDimitry Andric   }
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric   // All uses of the alloca are safe, we can place it on the safe stack.
3710b57cec5SDimitry Andric   return true;
3720b57cec5SDimitry Andric }
3730b57cec5SDimitry Andric 
getStackGuard(IRBuilder<> & IRB,Function & F)3740b57cec5SDimitry Andric Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
3750b57cec5SDimitry Andric   Value *StackGuardVar = TL.getIRStackGuard(IRB);
376*5f7ddb14SDimitry Andric   Module *M = F.getParent();
377*5f7ddb14SDimitry Andric 
378*5f7ddb14SDimitry Andric   if (!StackGuardVar) {
379*5f7ddb14SDimitry Andric     TL.insertSSPDeclarations(*M);
380*5f7ddb14SDimitry Andric     return IRB.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
381*5f7ddb14SDimitry Andric   }
382*5f7ddb14SDimitry Andric 
3830b57cec5SDimitry Andric   return IRB.CreateLoad(StackPtrTy, StackGuardVar, "StackGuard");
3840b57cec5SDimitry Andric }
3850b57cec5SDimitry Andric 
findInsts(Function & F,SmallVectorImpl<AllocaInst * > & StaticAllocas,SmallVectorImpl<AllocaInst * > & DynamicAllocas,SmallVectorImpl<Argument * > & ByValArguments,SmallVectorImpl<Instruction * > & Returns,SmallVectorImpl<Instruction * > & StackRestorePoints)3860b57cec5SDimitry Andric void SafeStack::findInsts(Function &F,
3870b57cec5SDimitry Andric                           SmallVectorImpl<AllocaInst *> &StaticAllocas,
3880b57cec5SDimitry Andric                           SmallVectorImpl<AllocaInst *> &DynamicAllocas,
3890b57cec5SDimitry Andric                           SmallVectorImpl<Argument *> &ByValArguments,
390af732203SDimitry Andric                           SmallVectorImpl<Instruction *> &Returns,
3910b57cec5SDimitry Andric                           SmallVectorImpl<Instruction *> &StackRestorePoints) {
3920b57cec5SDimitry Andric   for (Instruction &I : instructions(&F)) {
3930b57cec5SDimitry Andric     if (auto AI = dyn_cast<AllocaInst>(&I)) {
3940b57cec5SDimitry Andric       ++NumAllocas;
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric       uint64_t Size = getStaticAllocaAllocationSize(AI);
3970b57cec5SDimitry Andric       if (IsSafeStackAlloca(AI, Size))
3980b57cec5SDimitry Andric         continue;
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric       if (AI->isStaticAlloca()) {
4010b57cec5SDimitry Andric         ++NumUnsafeStaticAllocas;
4020b57cec5SDimitry Andric         StaticAllocas.push_back(AI);
4030b57cec5SDimitry Andric       } else {
4040b57cec5SDimitry Andric         ++NumUnsafeDynamicAllocas;
4050b57cec5SDimitry Andric         DynamicAllocas.push_back(AI);
4060b57cec5SDimitry Andric       }
4070b57cec5SDimitry Andric     } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
408af732203SDimitry Andric       if (CallInst *CI = I.getParent()->getTerminatingMustTailCall())
409af732203SDimitry Andric         Returns.push_back(CI);
410af732203SDimitry Andric       else
4110b57cec5SDimitry Andric         Returns.push_back(RI);
4120b57cec5SDimitry Andric     } else if (auto CI = dyn_cast<CallInst>(&I)) {
4130b57cec5SDimitry Andric       // setjmps require stack restore.
4140b57cec5SDimitry Andric       if (CI->getCalledFunction() && CI->canReturnTwice())
4150b57cec5SDimitry Andric         StackRestorePoints.push_back(CI);
4160b57cec5SDimitry Andric     } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
4170b57cec5SDimitry Andric       // Exception landing pads require stack restore.
4180b57cec5SDimitry Andric       StackRestorePoints.push_back(LP);
4190b57cec5SDimitry Andric     } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
4200b57cec5SDimitry Andric       if (II->getIntrinsicID() == Intrinsic::gcroot)
4210b57cec5SDimitry Andric         report_fatal_error(
4220b57cec5SDimitry Andric             "gcroot intrinsic not compatible with safestack attribute");
4230b57cec5SDimitry Andric     }
4240b57cec5SDimitry Andric   }
4250b57cec5SDimitry Andric   for (Argument &Arg : F.args()) {
4260b57cec5SDimitry Andric     if (!Arg.hasByValAttr())
4270b57cec5SDimitry Andric       continue;
428*5f7ddb14SDimitry Andric     uint64_t Size = DL.getTypeStoreSize(Arg.getParamByValType());
4290b57cec5SDimitry Andric     if (IsSafeStackAlloca(&Arg, Size))
4300b57cec5SDimitry Andric       continue;
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric     ++NumUnsafeByValArguments;
4330b57cec5SDimitry Andric     ByValArguments.push_back(&Arg);
4340b57cec5SDimitry Andric   }
4350b57cec5SDimitry Andric }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric AllocaInst *
createStackRestorePoints(IRBuilder<> & IRB,Function & F,ArrayRef<Instruction * > StackRestorePoints,Value * StaticTop,bool NeedDynamicTop)4380b57cec5SDimitry Andric SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
4390b57cec5SDimitry Andric                                     ArrayRef<Instruction *> StackRestorePoints,
4400b57cec5SDimitry Andric                                     Value *StaticTop, bool NeedDynamicTop) {
4410b57cec5SDimitry Andric   assert(StaticTop && "The stack top isn't set.");
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   if (StackRestorePoints.empty())
4440b57cec5SDimitry Andric     return nullptr;
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   // We need the current value of the shadow stack pointer to restore
4470b57cec5SDimitry Andric   // after longjmp or exception catching.
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric   // FIXME: On some platforms this could be handled by the longjmp/exception
4500b57cec5SDimitry Andric   // runtime itself.
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   AllocaInst *DynamicTop = nullptr;
4530b57cec5SDimitry Andric   if (NeedDynamicTop) {
4540b57cec5SDimitry Andric     // If we also have dynamic alloca's, the stack pointer value changes
4550b57cec5SDimitry Andric     // throughout the function. For now we store it in an alloca.
4560b57cec5SDimitry Andric     DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
4570b57cec5SDimitry Andric                                   "unsafe_stack_dynamic_ptr");
4580b57cec5SDimitry Andric     IRB.CreateStore(StaticTop, DynamicTop);
4590b57cec5SDimitry Andric   }
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric   // Restore current stack pointer after longjmp/exception catch.
4620b57cec5SDimitry Andric   for (Instruction *I : StackRestorePoints) {
4630b57cec5SDimitry Andric     ++NumUnsafeStackRestorePoints;
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric     IRB.SetInsertPoint(I->getNextNode());
4660b57cec5SDimitry Andric     Value *CurrentTop =
4670b57cec5SDimitry Andric         DynamicTop ? IRB.CreateLoad(StackPtrTy, DynamicTop) : StaticTop;
4680b57cec5SDimitry Andric     IRB.CreateStore(CurrentTop, UnsafeStackPtr);
4690b57cec5SDimitry Andric   }
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric   return DynamicTop;
4720b57cec5SDimitry Andric }
4730b57cec5SDimitry Andric 
checkStackGuard(IRBuilder<> & IRB,Function & F,Instruction & RI,AllocaInst * StackGuardSlot,Value * StackGuard)474af732203SDimitry Andric void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, Instruction &RI,
4750b57cec5SDimitry Andric                                 AllocaInst *StackGuardSlot, Value *StackGuard) {
4760b57cec5SDimitry Andric   Value *V = IRB.CreateLoad(StackPtrTy, StackGuardSlot);
4770b57cec5SDimitry Andric   Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
4800b57cec5SDimitry Andric   auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
4810b57cec5SDimitry Andric   MDNode *Weights = MDBuilder(F.getContext())
4820b57cec5SDimitry Andric                         .createBranchWeights(SuccessProb.getNumerator(),
4830b57cec5SDimitry Andric                                              FailureProb.getNumerator());
4840b57cec5SDimitry Andric   Instruction *CheckTerm =
485*5f7ddb14SDimitry Andric       SplitBlockAndInsertIfThen(Cmp, &RI, /* Unreachable */ true, Weights, DTU);
4860b57cec5SDimitry Andric   IRBuilder<> IRBFail(CheckTerm);
4870b57cec5SDimitry Andric   // FIXME: respect -fsanitize-trap / -ftrap-function here?
4880b57cec5SDimitry Andric   FunctionCallee StackChkFail =
4890b57cec5SDimitry Andric       F.getParent()->getOrInsertFunction("__stack_chk_fail", IRB.getVoidTy());
4900b57cec5SDimitry Andric   IRBFail.CreateCall(StackChkFail, {});
4910b57cec5SDimitry Andric }
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric /// We explicitly compute and set the unsafe stack layout for all unsafe
4940b57cec5SDimitry Andric /// static alloca instructions. We save the unsafe "base pointer" in the
4950b57cec5SDimitry Andric /// prologue into a local variable and restore it in the epilogue.
moveStaticAllocasToUnsafeStack(IRBuilder<> & IRB,Function & F,ArrayRef<AllocaInst * > StaticAllocas,ArrayRef<Argument * > ByValArguments,Instruction * BasePointer,AllocaInst * StackGuardSlot)4960b57cec5SDimitry Andric Value *SafeStack::moveStaticAllocasToUnsafeStack(
4970b57cec5SDimitry Andric     IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
498af732203SDimitry Andric     ArrayRef<Argument *> ByValArguments, Instruction *BasePointer,
499af732203SDimitry Andric     AllocaInst *StackGuardSlot) {
5000b57cec5SDimitry Andric   if (StaticAllocas.empty() && ByValArguments.empty())
5010b57cec5SDimitry Andric     return BasePointer;
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric   DIBuilder DIB(*F.getParent());
5040b57cec5SDimitry Andric 
5055ffd83dbSDimitry Andric   StackLifetime SSC(F, StaticAllocas, StackLifetime::LivenessType::May);
5065ffd83dbSDimitry Andric   static const StackLifetime::LiveRange NoColoringRange(1, true);
5075ffd83dbSDimitry Andric   if (ClColoring)
5080b57cec5SDimitry Andric     SSC.run();
5095ffd83dbSDimitry Andric 
5105ffd83dbSDimitry Andric   for (auto *I : SSC.getMarkers()) {
5115ffd83dbSDimitry Andric     auto *Op = dyn_cast<Instruction>(I->getOperand(1));
5125ffd83dbSDimitry Andric     const_cast<IntrinsicInst *>(I)->eraseFromParent();
5135ffd83dbSDimitry Andric     // Remove the operand bitcast, too, if it has no more uses left.
5145ffd83dbSDimitry Andric     if (Op && Op->use_empty())
5155ffd83dbSDimitry Andric       Op->eraseFromParent();
5165ffd83dbSDimitry Andric   }
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   // Unsafe stack always grows down.
5190b57cec5SDimitry Andric   StackLayout SSL(StackAlignment);
5200b57cec5SDimitry Andric   if (StackGuardSlot) {
5210b57cec5SDimitry Andric     Type *Ty = StackGuardSlot->getAllocatedType();
5220b57cec5SDimitry Andric     unsigned Align =
5230b57cec5SDimitry Andric         std::max(DL.getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
5240b57cec5SDimitry Andric     SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
5250b57cec5SDimitry Andric                   Align, SSC.getFullLiveRange());
5260b57cec5SDimitry Andric   }
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   for (Argument *Arg : ByValArguments) {
529*5f7ddb14SDimitry Andric     Type *Ty = Arg->getParamByValType();
5300b57cec5SDimitry Andric     uint64_t Size = DL.getTypeStoreSize(Ty);
5310b57cec5SDimitry Andric     if (Size == 0)
5320b57cec5SDimitry Andric       Size = 1; // Don't create zero-sized stack objects.
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric     // Ensure the object is properly aligned.
5350b57cec5SDimitry Andric     unsigned Align = std::max((unsigned)DL.getPrefTypeAlignment(Ty),
5360b57cec5SDimitry Andric                               Arg->getParamAlignment());
5370b57cec5SDimitry Andric     SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
5380b57cec5SDimitry Andric   }
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric   for (AllocaInst *AI : StaticAllocas) {
5410b57cec5SDimitry Andric     Type *Ty = AI->getAllocatedType();
5420b57cec5SDimitry Andric     uint64_t Size = getStaticAllocaAllocationSize(AI);
5430b57cec5SDimitry Andric     if (Size == 0)
5440b57cec5SDimitry Andric       Size = 1; // Don't create zero-sized stack objects.
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric     // Ensure the object is properly aligned.
5470b57cec5SDimitry Andric     unsigned Align =
5480b57cec5SDimitry Andric         std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment());
5490b57cec5SDimitry Andric 
5505ffd83dbSDimitry Andric     SSL.addObject(AI, Size, Align,
5515ffd83dbSDimitry Andric                   ClColoring ? SSC.getLiveRange(AI) : NoColoringRange);
5520b57cec5SDimitry Andric   }
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric   SSL.computeLayout();
5550b57cec5SDimitry Andric   unsigned FrameAlignment = SSL.getFrameAlignment();
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric   // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
5580b57cec5SDimitry Andric   // (AlignmentSkew).
5590b57cec5SDimitry Andric   if (FrameAlignment > StackAlignment) {
5600b57cec5SDimitry Andric     // Re-align the base pointer according to the max requested alignment.
5610b57cec5SDimitry Andric     assert(isPowerOf2_32(FrameAlignment));
5620b57cec5SDimitry Andric     IRB.SetInsertPoint(BasePointer->getNextNode());
5630b57cec5SDimitry Andric     BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
5640b57cec5SDimitry Andric         IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
5650b57cec5SDimitry Andric                       ConstantInt::get(IntPtrTy, ~uint64_t(FrameAlignment - 1))),
5660b57cec5SDimitry Andric         StackPtrTy));
5670b57cec5SDimitry Andric   }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   IRB.SetInsertPoint(BasePointer->getNextNode());
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric   if (StackGuardSlot) {
5720b57cec5SDimitry Andric     unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
5730b57cec5SDimitry Andric     Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
5740b57cec5SDimitry Andric                                ConstantInt::get(Int32Ty, -Offset));
5750b57cec5SDimitry Andric     Value *NewAI =
5760b57cec5SDimitry Andric         IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric     // Replace alloc with the new location.
5790b57cec5SDimitry Andric     StackGuardSlot->replaceAllUsesWith(NewAI);
5800b57cec5SDimitry Andric     StackGuardSlot->eraseFromParent();
5810b57cec5SDimitry Andric   }
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric   for (Argument *Arg : ByValArguments) {
5840b57cec5SDimitry Andric     unsigned Offset = SSL.getObjectOffset(Arg);
585480093f4SDimitry Andric     MaybeAlign Align(SSL.getObjectAlignment(Arg));
586*5f7ddb14SDimitry Andric     Type *Ty = Arg->getParamByValType();
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric     uint64_t Size = DL.getTypeStoreSize(Ty);
5890b57cec5SDimitry Andric     if (Size == 0)
5900b57cec5SDimitry Andric       Size = 1; // Don't create zero-sized stack objects.
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric     Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
5930b57cec5SDimitry Andric                                ConstantInt::get(Int32Ty, -Offset));
5940b57cec5SDimitry Andric     Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
5950b57cec5SDimitry Andric                                      Arg->getName() + ".unsafe-byval");
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric     // Replace alloc with the new location.
5985ffd83dbSDimitry Andric     replaceDbgDeclare(Arg, BasePointer, DIB, DIExpression::ApplyOffset,
5995ffd83dbSDimitry Andric                       -Offset);
6000b57cec5SDimitry Andric     Arg->replaceAllUsesWith(NewArg);
6010b57cec5SDimitry Andric     IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
602480093f4SDimitry Andric     IRB.CreateMemCpy(Off, Align, Arg, Arg->getParamAlign(), Size);
6030b57cec5SDimitry Andric   }
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric   // Allocate space for every unsafe static AllocaInst on the unsafe stack.
6060b57cec5SDimitry Andric   for (AllocaInst *AI : StaticAllocas) {
6070b57cec5SDimitry Andric     IRB.SetInsertPoint(AI);
6080b57cec5SDimitry Andric     unsigned Offset = SSL.getObjectOffset(AI);
6090b57cec5SDimitry Andric 
6105ffd83dbSDimitry Andric     replaceDbgDeclare(AI, BasePointer, DIB, DIExpression::ApplyOffset, -Offset);
6110b57cec5SDimitry Andric     replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric     // Replace uses of the alloca with the new location.
6140b57cec5SDimitry Andric     // Insert address calculation close to each use to work around PR27844.
6150b57cec5SDimitry Andric     std::string Name = std::string(AI->getName()) + ".unsafe";
6160b57cec5SDimitry Andric     while (!AI->use_empty()) {
6170b57cec5SDimitry Andric       Use &U = *AI->use_begin();
6180b57cec5SDimitry Andric       Instruction *User = cast<Instruction>(U.getUser());
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric       Instruction *InsertBefore;
6210b57cec5SDimitry Andric       if (auto *PHI = dyn_cast<PHINode>(User))
6220b57cec5SDimitry Andric         InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
6230b57cec5SDimitry Andric       else
6240b57cec5SDimitry Andric         InsertBefore = User;
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric       IRBuilder<> IRBUser(InsertBefore);
6270b57cec5SDimitry Andric       Value *Off = IRBUser.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
6280b57cec5SDimitry Andric                                      ConstantInt::get(Int32Ty, -Offset));
6290b57cec5SDimitry Andric       Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric       if (auto *PHI = dyn_cast<PHINode>(User))
6320b57cec5SDimitry Andric         // PHI nodes may have multiple incoming edges from the same BB (why??),
6330b57cec5SDimitry Andric         // all must be updated at once with the same incoming value.
6340b57cec5SDimitry Andric         PHI->setIncomingValueForBlock(PHI->getIncomingBlock(U), Replacement);
6350b57cec5SDimitry Andric       else
6360b57cec5SDimitry Andric         U.set(Replacement);
6370b57cec5SDimitry Andric     }
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric     AI->eraseFromParent();
6400b57cec5SDimitry Andric   }
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   // Re-align BasePointer so that our callees would see it aligned as
6430b57cec5SDimitry Andric   // expected.
6440b57cec5SDimitry Andric   // FIXME: no need to update BasePointer in leaf functions.
6450b57cec5SDimitry Andric   unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric   // Update shadow stack pointer in the function epilogue.
6480b57cec5SDimitry Andric   IRB.SetInsertPoint(BasePointer->getNextNode());
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   Value *StaticTop =
6510b57cec5SDimitry Andric       IRB.CreateGEP(Int8Ty, BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
6520b57cec5SDimitry Andric                     "unsafe_stack_static_top");
6530b57cec5SDimitry Andric   IRB.CreateStore(StaticTop, UnsafeStackPtr);
6540b57cec5SDimitry Andric   return StaticTop;
6550b57cec5SDimitry Andric }
6560b57cec5SDimitry Andric 
moveDynamicAllocasToUnsafeStack(Function & F,Value * UnsafeStackPtr,AllocaInst * DynamicTop,ArrayRef<AllocaInst * > DynamicAllocas)6570b57cec5SDimitry Andric void SafeStack::moveDynamicAllocasToUnsafeStack(
6580b57cec5SDimitry Andric     Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
6590b57cec5SDimitry Andric     ArrayRef<AllocaInst *> DynamicAllocas) {
6600b57cec5SDimitry Andric   DIBuilder DIB(*F.getParent());
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric   for (AllocaInst *AI : DynamicAllocas) {
6630b57cec5SDimitry Andric     IRBuilder<> IRB(AI);
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric     // Compute the new SP value (after AI).
6660b57cec5SDimitry Andric     Value *ArraySize = AI->getArraySize();
6670b57cec5SDimitry Andric     if (ArraySize->getType() != IntPtrTy)
6680b57cec5SDimitry Andric       ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric     Type *Ty = AI->getAllocatedType();
6710b57cec5SDimitry Andric     uint64_t TySize = DL.getTypeAllocSize(Ty);
6720b57cec5SDimitry Andric     Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric     Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(StackPtrTy, UnsafeStackPtr),
6750b57cec5SDimitry Andric                                    IntPtrTy);
6760b57cec5SDimitry Andric     SP = IRB.CreateSub(SP, Size);
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric     // Align the SP value to satisfy the AllocaInst, type and stack alignments.
6790b57cec5SDimitry Andric     unsigned Align = std::max(
6800b57cec5SDimitry Andric         std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()),
6810b57cec5SDimitry Andric         (unsigned)StackAlignment);
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric     assert(isPowerOf2_32(Align));
6840b57cec5SDimitry Andric     Value *NewTop = IRB.CreateIntToPtr(
6850b57cec5SDimitry Andric         IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
6860b57cec5SDimitry Andric         StackPtrTy);
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric     // Save the stack pointer.
6890b57cec5SDimitry Andric     IRB.CreateStore(NewTop, UnsafeStackPtr);
6900b57cec5SDimitry Andric     if (DynamicTop)
6910b57cec5SDimitry Andric       IRB.CreateStore(NewTop, DynamicTop);
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric     Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
6940b57cec5SDimitry Andric     if (AI->hasName() && isa<Instruction>(NewAI))
6950b57cec5SDimitry Andric       NewAI->takeName(AI);
6960b57cec5SDimitry Andric 
6975ffd83dbSDimitry Andric     replaceDbgDeclare(AI, NewAI, DIB, DIExpression::ApplyOffset, 0);
6980b57cec5SDimitry Andric     AI->replaceAllUsesWith(NewAI);
6990b57cec5SDimitry Andric     AI->eraseFromParent();
7000b57cec5SDimitry Andric   }
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric   if (!DynamicAllocas.empty()) {
7030b57cec5SDimitry Andric     // Now go through the instructions again, replacing stacksave/stackrestore.
7040b57cec5SDimitry Andric     for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
7050b57cec5SDimitry Andric       Instruction *I = &*(It++);
7060b57cec5SDimitry Andric       auto II = dyn_cast<IntrinsicInst>(I);
7070b57cec5SDimitry Andric       if (!II)
7080b57cec5SDimitry Andric         continue;
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric       if (II->getIntrinsicID() == Intrinsic::stacksave) {
7110b57cec5SDimitry Andric         IRBuilder<> IRB(II);
7120b57cec5SDimitry Andric         Instruction *LI = IRB.CreateLoad(StackPtrTy, UnsafeStackPtr);
7130b57cec5SDimitry Andric         LI->takeName(II);
7140b57cec5SDimitry Andric         II->replaceAllUsesWith(LI);
7150b57cec5SDimitry Andric         II->eraseFromParent();
7160b57cec5SDimitry Andric       } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
7170b57cec5SDimitry Andric         IRBuilder<> IRB(II);
7180b57cec5SDimitry Andric         Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
7190b57cec5SDimitry Andric         SI->takeName(II);
7200b57cec5SDimitry Andric         assert(II->use_empty());
7210b57cec5SDimitry Andric         II->eraseFromParent();
7220b57cec5SDimitry Andric       }
7230b57cec5SDimitry Andric     }
7240b57cec5SDimitry Andric   }
7250b57cec5SDimitry Andric }
7260b57cec5SDimitry Andric 
ShouldInlinePointerAddress(CallInst & CI)7275ffd83dbSDimitry Andric bool SafeStack::ShouldInlinePointerAddress(CallInst &CI) {
7285ffd83dbSDimitry Andric   Function *Callee = CI.getCalledFunction();
7295ffd83dbSDimitry Andric   if (CI.hasFnAttr(Attribute::AlwaysInline) &&
7305ffd83dbSDimitry Andric       isInlineViable(*Callee).isSuccess())
7310b57cec5SDimitry Andric     return true;
7320b57cec5SDimitry Andric   if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
7335ffd83dbSDimitry Andric       CI.isNoInline())
7340b57cec5SDimitry Andric     return false;
7350b57cec5SDimitry Andric   return true;
7360b57cec5SDimitry Andric }
7370b57cec5SDimitry Andric 
TryInlinePointerAddress()7380b57cec5SDimitry Andric void SafeStack::TryInlinePointerAddress() {
7395ffd83dbSDimitry Andric   auto *CI = dyn_cast<CallInst>(UnsafeStackPtr);
7405ffd83dbSDimitry Andric   if (!CI)
7410b57cec5SDimitry Andric     return;
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric   if(F.hasOptNone())
7440b57cec5SDimitry Andric     return;
7450b57cec5SDimitry Andric 
7465ffd83dbSDimitry Andric   Function *Callee = CI->getCalledFunction();
7470b57cec5SDimitry Andric   if (!Callee || Callee->isDeclaration())
7480b57cec5SDimitry Andric     return;
7490b57cec5SDimitry Andric 
7505ffd83dbSDimitry Andric   if (!ShouldInlinePointerAddress(*CI))
7510b57cec5SDimitry Andric     return;
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   InlineFunctionInfo IFI;
7545ffd83dbSDimitry Andric   InlineFunction(*CI, IFI);
7550b57cec5SDimitry Andric }
7560b57cec5SDimitry Andric 
run()7570b57cec5SDimitry Andric bool SafeStack::run() {
7580b57cec5SDimitry Andric   assert(F.hasFnAttribute(Attribute::SafeStack) &&
7590b57cec5SDimitry Andric          "Can't run SafeStack on a function without the attribute");
7600b57cec5SDimitry Andric   assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   ++NumFunctions;
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   SmallVector<AllocaInst *, 16> StaticAllocas;
7650b57cec5SDimitry Andric   SmallVector<AllocaInst *, 4> DynamicAllocas;
7660b57cec5SDimitry Andric   SmallVector<Argument *, 4> ByValArguments;
767af732203SDimitry Andric   SmallVector<Instruction *, 4> Returns;
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric   // Collect all points where stack gets unwound and needs to be restored
7700b57cec5SDimitry Andric   // This is only necessary because the runtime (setjmp and unwind code) is
7710b57cec5SDimitry Andric   // not aware of the unsafe stack and won't unwind/restore it properly.
7720b57cec5SDimitry Andric   // To work around this problem without changing the runtime, we insert
7730b57cec5SDimitry Andric   // instrumentation to restore the unsafe stack pointer when necessary.
7740b57cec5SDimitry Andric   SmallVector<Instruction *, 4> StackRestorePoints;
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   // Find all static and dynamic alloca instructions that must be moved to the
7770b57cec5SDimitry Andric   // unsafe stack, all return instructions and stack restore points.
7780b57cec5SDimitry Andric   findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
7790b57cec5SDimitry Andric             StackRestorePoints);
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   if (StaticAllocas.empty() && DynamicAllocas.empty() &&
7820b57cec5SDimitry Andric       ByValArguments.empty() && StackRestorePoints.empty())
7830b57cec5SDimitry Andric     return false; // Nothing to do in this function.
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric   if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
7860b57cec5SDimitry Andric       !ByValArguments.empty())
7870b57cec5SDimitry Andric     ++NumUnsafeStackFunctions; // This function has the unsafe stack.
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric   if (!StackRestorePoints.empty())
7900b57cec5SDimitry Andric     ++NumUnsafeStackRestorePointsFunctions;
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
7930b57cec5SDimitry Andric   // Calls must always have a debug location, or else inlining breaks. So
7940b57cec5SDimitry Andric   // we explicitly set a artificial debug location here.
7950b57cec5SDimitry Andric   if (DISubprogram *SP = F.getSubprogram())
796af732203SDimitry Andric     IRB.SetCurrentDebugLocation(
797af732203SDimitry Andric         DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP));
7980b57cec5SDimitry Andric   if (SafeStackUsePointerAddress) {
7990b57cec5SDimitry Andric     FunctionCallee Fn = F.getParent()->getOrInsertFunction(
8000b57cec5SDimitry Andric         "__safestack_pointer_address", StackPtrTy->getPointerTo(0));
8010b57cec5SDimitry Andric     UnsafeStackPtr = IRB.CreateCall(Fn);
8020b57cec5SDimitry Andric   } else {
8030b57cec5SDimitry Andric     UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
8040b57cec5SDimitry Andric   }
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   // Load the current stack pointer (we'll also use it as a base pointer).
8070b57cec5SDimitry Andric   // FIXME: use a dedicated register for it ?
8080b57cec5SDimitry Andric   Instruction *BasePointer =
8090b57cec5SDimitry Andric       IRB.CreateLoad(StackPtrTy, UnsafeStackPtr, false, "unsafe_stack_ptr");
8100b57cec5SDimitry Andric   assert(BasePointer->getType() == StackPtrTy);
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric   AllocaInst *StackGuardSlot = nullptr;
8130b57cec5SDimitry Andric   // FIXME: implement weaker forms of stack protector.
8140b57cec5SDimitry Andric   if (F.hasFnAttribute(Attribute::StackProtect) ||
8150b57cec5SDimitry Andric       F.hasFnAttribute(Attribute::StackProtectStrong) ||
8160b57cec5SDimitry Andric       F.hasFnAttribute(Attribute::StackProtectReq)) {
8170b57cec5SDimitry Andric     Value *StackGuard = getStackGuard(IRB, F);
8180b57cec5SDimitry Andric     StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
8190b57cec5SDimitry Andric     IRB.CreateStore(StackGuard, StackGuardSlot);
8200b57cec5SDimitry Andric 
821af732203SDimitry Andric     for (Instruction *RI : Returns) {
8220b57cec5SDimitry Andric       IRBuilder<> IRBRet(RI);
8230b57cec5SDimitry Andric       checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
8240b57cec5SDimitry Andric     }
8250b57cec5SDimitry Andric   }
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   // The top of the unsafe stack after all unsafe static allocas are
8280b57cec5SDimitry Andric   // allocated.
829af732203SDimitry Andric   Value *StaticTop = moveStaticAllocasToUnsafeStack(
830af732203SDimitry Andric       IRB, F, StaticAllocas, ByValArguments, BasePointer, StackGuardSlot);
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   // Safe stack object that stores the current unsafe stack top. It is updated
8330b57cec5SDimitry Andric   // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
8340b57cec5SDimitry Andric   // This is only needed if we need to restore stack pointer after longjmp
8350b57cec5SDimitry Andric   // or exceptions, and we have dynamic allocations.
8360b57cec5SDimitry Andric   // FIXME: a better alternative might be to store the unsafe stack pointer
8370b57cec5SDimitry Andric   // before setjmp / invoke instructions.
8380b57cec5SDimitry Andric   AllocaInst *DynamicTop = createStackRestorePoints(
8390b57cec5SDimitry Andric       IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   // Handle dynamic allocas.
8420b57cec5SDimitry Andric   moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
8430b57cec5SDimitry Andric                                   DynamicAllocas);
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric   // Restore the unsafe stack pointer before each return.
846af732203SDimitry Andric   for (Instruction *RI : Returns) {
8470b57cec5SDimitry Andric     IRB.SetInsertPoint(RI);
8480b57cec5SDimitry Andric     IRB.CreateStore(BasePointer, UnsafeStackPtr);
8490b57cec5SDimitry Andric   }
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   TryInlinePointerAddress();
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "[SafeStack]     safestack applied\n");
8540b57cec5SDimitry Andric   return true;
8550b57cec5SDimitry Andric }
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric class SafeStackLegacyPass : public FunctionPass {
8580b57cec5SDimitry Andric   const TargetMachine *TM = nullptr;
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric public:
8610b57cec5SDimitry Andric   static char ID; // Pass identification, replacement for typeid..
8620b57cec5SDimitry Andric 
SafeStackLegacyPass()8630b57cec5SDimitry Andric   SafeStackLegacyPass() : FunctionPass(ID) {
8640b57cec5SDimitry Andric     initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
8650b57cec5SDimitry Andric   }
8660b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const8670b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
8680b57cec5SDimitry Andric     AU.addRequired<TargetPassConfig>();
8690b57cec5SDimitry Andric     AU.addRequired<TargetLibraryInfoWrapperPass>();
8700b57cec5SDimitry Andric     AU.addRequired<AssumptionCacheTracker>();
871*5f7ddb14SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
8720b57cec5SDimitry Andric   }
8730b57cec5SDimitry Andric 
runOnFunction(Function & F)8740b57cec5SDimitry Andric   bool runOnFunction(Function &F) override {
8750b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric     if (!F.hasFnAttribute(Attribute::SafeStack)) {
8780b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "[SafeStack]     safestack is not requested"
8790b57cec5SDimitry Andric                            " for this function\n");
8800b57cec5SDimitry Andric       return false;
8810b57cec5SDimitry Andric     }
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric     if (F.isDeclaration()) {
8840b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "[SafeStack]     function definition"
8850b57cec5SDimitry Andric                            " is not available\n");
8860b57cec5SDimitry Andric       return false;
8870b57cec5SDimitry Andric     }
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric     TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
8900b57cec5SDimitry Andric     auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
8910b57cec5SDimitry Andric     if (!TL)
8920b57cec5SDimitry Andric       report_fatal_error("TargetLowering instance is required");
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric     auto *DL = &F.getParent()->getDataLayout();
8958bcb0991SDimitry Andric     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
8960b57cec5SDimitry Andric     auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric     // Compute DT and LI only for functions that have the attribute.
8990b57cec5SDimitry Andric     // This is only useful because the legacy pass manager doesn't let us
9000b57cec5SDimitry Andric     // compute analyzes lazily.
9010b57cec5SDimitry Andric 
902*5f7ddb14SDimitry Andric     DominatorTree *DT;
903*5f7ddb14SDimitry Andric     bool ShouldPreserveDominatorTree;
904*5f7ddb14SDimitry Andric     Optional<DominatorTree> LazilyComputedDomTree;
9050b57cec5SDimitry Andric 
906*5f7ddb14SDimitry Andric     // Do we already have a DominatorTree avaliable from the previous pass?
907*5f7ddb14SDimitry Andric     // Note that we should *NOT* require it, to avoid the case where we end up
908*5f7ddb14SDimitry Andric     // not needing it, but the legacy PM would have computed it for us anyways.
909*5f7ddb14SDimitry Andric     if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
910*5f7ddb14SDimitry Andric       DT = &DTWP->getDomTree();
911*5f7ddb14SDimitry Andric       ShouldPreserveDominatorTree = true;
912*5f7ddb14SDimitry Andric     } else {
913*5f7ddb14SDimitry Andric       // Otherwise, we need to compute it.
914*5f7ddb14SDimitry Andric       LazilyComputedDomTree.emplace(F);
915*5f7ddb14SDimitry Andric       DT = LazilyComputedDomTree.getPointer();
916*5f7ddb14SDimitry Andric       ShouldPreserveDominatorTree = false;
917*5f7ddb14SDimitry Andric     }
918*5f7ddb14SDimitry Andric 
919*5f7ddb14SDimitry Andric     // Likewise, lazily compute loop info.
920*5f7ddb14SDimitry Andric     LoopInfo LI(*DT);
921*5f7ddb14SDimitry Andric 
922*5f7ddb14SDimitry Andric     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
923*5f7ddb14SDimitry Andric 
924*5f7ddb14SDimitry Andric     ScalarEvolution SE(F, TLI, ACT, *DT, LI);
925*5f7ddb14SDimitry Andric 
926*5f7ddb14SDimitry Andric     return SafeStack(F, *TL, *DL, ShouldPreserveDominatorTree ? &DTU : nullptr,
927*5f7ddb14SDimitry Andric                      SE)
928*5f7ddb14SDimitry Andric         .run();
9290b57cec5SDimitry Andric   }
9300b57cec5SDimitry Andric };
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric } // end anonymous namespace
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric char SafeStackLegacyPass::ID = 0;
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE,
9370b57cec5SDimitry Andric                       "Safe Stack instrumentation pass", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)9380b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
939*5f7ddb14SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
9400b57cec5SDimitry Andric INITIALIZE_PASS_END(SafeStackLegacyPass, DEBUG_TYPE,
9410b57cec5SDimitry Andric                     "Safe Stack instrumentation pass", false, false)
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }
944