xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/StackProtector.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
10b57cec5SDimitry Andric //===- StackProtector.cpp - Stack Protector 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 inserts stack protectors into functions which need them. A variable
100b57cec5SDimitry Andric // with a random value in it is stored onto the stack before the local variables
110b57cec5SDimitry Andric // are allocated. Upon exiting the block, the stored value is checked. If it's
120b57cec5SDimitry Andric // changed, then there was some sort of violation and the program aborts.
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
150b57cec5SDimitry Andric 
160b57cec5SDimitry Andric #include "llvm/CodeGen/StackProtector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
1806c3fb27SDimitry Andric #include "llvm/ADT/SmallVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
215ffd83dbSDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
270b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
280b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
290b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
300b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
310b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
320b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
3306c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.h"
340b57cec5SDimitry Andric #include "llvm/IR/Function.h"
350b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
360b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
370b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
380b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
390b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
400b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
410b57cec5SDimitry Andric #include "llvm/IR/Module.h"
420b57cec5SDimitry Andric #include "llvm/IR/Type.h"
430b57cec5SDimitry Andric #include "llvm/IR/User.h"
44480093f4SDimitry Andric #include "llvm/InitializePasses.h"
450b57cec5SDimitry Andric #include "llvm/Pass.h"
460b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
470b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
480b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
490b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
50bdd1243dSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
51bdd1243dSDimitry Andric #include <optional>
520b57cec5SDimitry Andric #include <utility>
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric using namespace llvm;
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric #define DEBUG_TYPE "stack-protector"
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected");
590b57cec5SDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address"
600b57cec5SDimitry Andric                         " taken.");
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
630b57cec5SDimitry Andric                                           cl::init(true), cl::Hidden);
64bdd1243dSDimitry Andric static cl::opt<bool> DisableCheckNoReturn("disable-check-noreturn-call",
65bdd1243dSDimitry Andric                                           cl::init(false), cl::Hidden);
660b57cec5SDimitry Andric 
67*1db9f3b2SDimitry Andric /// InsertStackProtectors - Insert code into the prologue and epilogue of the
68*1db9f3b2SDimitry Andric /// function.
69*1db9f3b2SDimitry Andric ///
70*1db9f3b2SDimitry Andric ///  - The prologue code loads and stores the stack guard onto the stack.
71*1db9f3b2SDimitry Andric ///  - The epilogue checks the value stored in the prologue against the original
72*1db9f3b2SDimitry Andric ///    value. It calls __stack_chk_fail if they differ.
73*1db9f3b2SDimitry Andric static bool InsertStackProtectors(const TargetMachine *TM, Function *F,
74*1db9f3b2SDimitry Andric                                   DomTreeUpdater *DTU, bool &HasPrologue,
75*1db9f3b2SDimitry Andric                                   bool &HasIRCheck);
76*1db9f3b2SDimitry Andric 
77*1db9f3b2SDimitry Andric /// CreateFailBB - Create a basic block to jump to when the stack protector
78*1db9f3b2SDimitry Andric /// check fails.
79*1db9f3b2SDimitry Andric static BasicBlock *CreateFailBB(Function *F, const Triple &Trip);
80*1db9f3b2SDimitry Andric 
shouldEmitSDCheck(const BasicBlock & BB) const81*1db9f3b2SDimitry Andric bool SSPLayoutInfo::shouldEmitSDCheck(const BasicBlock &BB) const {
82*1db9f3b2SDimitry Andric   return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
83*1db9f3b2SDimitry Andric }
84*1db9f3b2SDimitry Andric 
copyToMachineFrameInfo(MachineFrameInfo & MFI) const85*1db9f3b2SDimitry Andric void SSPLayoutInfo::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
86*1db9f3b2SDimitry Andric   if (Layout.empty())
87*1db9f3b2SDimitry Andric     return;
88*1db9f3b2SDimitry Andric 
89*1db9f3b2SDimitry Andric   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
90*1db9f3b2SDimitry Andric     if (MFI.isDeadObjectIndex(I))
91*1db9f3b2SDimitry Andric       continue;
92*1db9f3b2SDimitry Andric 
93*1db9f3b2SDimitry Andric     const AllocaInst *AI = MFI.getObjectAllocation(I);
94*1db9f3b2SDimitry Andric     if (!AI)
95*1db9f3b2SDimitry Andric       continue;
96*1db9f3b2SDimitry Andric 
97*1db9f3b2SDimitry Andric     SSPLayoutMap::const_iterator LI = Layout.find(AI);
98*1db9f3b2SDimitry Andric     if (LI == Layout.end())
99*1db9f3b2SDimitry Andric       continue;
100*1db9f3b2SDimitry Andric 
101*1db9f3b2SDimitry Andric     MFI.setObjectSSPLayout(I, LI->second);
102*1db9f3b2SDimitry Andric   }
103*1db9f3b2SDimitry Andric }
104*1db9f3b2SDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)105*1db9f3b2SDimitry Andric SSPLayoutInfo SSPLayoutAnalysis::run(Function &F,
106*1db9f3b2SDimitry Andric                                      FunctionAnalysisManager &FAM) {
107*1db9f3b2SDimitry Andric 
108*1db9f3b2SDimitry Andric   SSPLayoutInfo Info;
109*1db9f3b2SDimitry Andric   Info.RequireStackProtector =
110*1db9f3b2SDimitry Andric       SSPLayoutAnalysis::requiresStackProtector(&F, &Info.Layout);
111*1db9f3b2SDimitry Andric   Info.SSPBufferSize = F.getFnAttributeAsParsedInteger(
112*1db9f3b2SDimitry Andric       "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
113*1db9f3b2SDimitry Andric   return Info;
114*1db9f3b2SDimitry Andric }
115*1db9f3b2SDimitry Andric 
116*1db9f3b2SDimitry Andric AnalysisKey SSPLayoutAnalysis::Key;
117*1db9f3b2SDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)118*1db9f3b2SDimitry Andric PreservedAnalyses StackProtectorPass::run(Function &F,
119*1db9f3b2SDimitry Andric                                           FunctionAnalysisManager &FAM) {
120*1db9f3b2SDimitry Andric   auto &Info = FAM.getResult<SSPLayoutAnalysis>(F);
121*1db9f3b2SDimitry Andric   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
122*1db9f3b2SDimitry Andric   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
123*1db9f3b2SDimitry Andric 
124*1db9f3b2SDimitry Andric   if (!Info.RequireStackProtector)
125*1db9f3b2SDimitry Andric     return PreservedAnalyses::all();
126*1db9f3b2SDimitry Andric 
127*1db9f3b2SDimitry Andric   // TODO(etienneb): Functions with funclets are not correctly supported now.
128*1db9f3b2SDimitry Andric   // Do nothing if this is funclet-based personality.
129*1db9f3b2SDimitry Andric   if (F.hasPersonalityFn()) {
130*1db9f3b2SDimitry Andric     EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
131*1db9f3b2SDimitry Andric     if (isFuncletEHPersonality(Personality))
132*1db9f3b2SDimitry Andric       return PreservedAnalyses::all();
133*1db9f3b2SDimitry Andric   }
134*1db9f3b2SDimitry Andric 
135*1db9f3b2SDimitry Andric   ++NumFunProtected;
136*1db9f3b2SDimitry Andric   bool Changed = InsertStackProtectors(TM, &F, DT ? &DTU : nullptr,
137*1db9f3b2SDimitry Andric                                        Info.HasPrologue, Info.HasIRCheck);
138*1db9f3b2SDimitry Andric #ifdef EXPENSIVE_CHECKS
139*1db9f3b2SDimitry Andric   assert((!DT || DT->verify(DominatorTree::VerificationLevel::Full)) &&
140*1db9f3b2SDimitry Andric          "Failed to maintain validity of domtree!");
141*1db9f3b2SDimitry Andric #endif
142*1db9f3b2SDimitry Andric 
143*1db9f3b2SDimitry Andric   if (!Changed)
144*1db9f3b2SDimitry Andric     return PreservedAnalyses::all();
145*1db9f3b2SDimitry Andric   PreservedAnalyses PA;
146*1db9f3b2SDimitry Andric   PA.preserve<SSPLayoutAnalysis>();
147*1db9f3b2SDimitry Andric   PA.preserve<DominatorTreeAnalysis>();
148*1db9f3b2SDimitry Andric   return PA;
149*1db9f3b2SDimitry Andric }
150*1db9f3b2SDimitry Andric 
1510b57cec5SDimitry Andric char StackProtector::ID = 0;
1520b57cec5SDimitry Andric 
StackProtector()153bdd1243dSDimitry Andric StackProtector::StackProtector() : FunctionPass(ID) {
154480093f4SDimitry Andric   initializeStackProtectorPass(*PassRegistry::getPassRegistry());
155480093f4SDimitry Andric }
156480093f4SDimitry Andric 
1570b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
1580b57cec5SDimitry Andric                       "Insert stack protectors", false, true)
INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)1590b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
160fe6060f1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1610b57cec5SDimitry Andric INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
1620b57cec5SDimitry Andric                     "Insert stack protectors", false, true)
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
1650b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1660b57cec5SDimitry Andric void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
1670b57cec5SDimitry Andric   AU.addRequired<TargetPassConfig>();
1680b57cec5SDimitry Andric   AU.addPreserved<DominatorTreeWrapperPass>();
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric 
runOnFunction(Function & Fn)1710b57cec5SDimitry Andric bool StackProtector::runOnFunction(Function &Fn) {
1720b57cec5SDimitry Andric   F = &Fn;
1730b57cec5SDimitry Andric   M = F->getParent();
174bdd1243dSDimitry Andric   if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
175bdd1243dSDimitry Andric     DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
1760b57cec5SDimitry Andric   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
177*1db9f3b2SDimitry Andric   LayoutInfo.HasPrologue = false;
178*1db9f3b2SDimitry Andric   LayoutInfo.HasIRCheck = false;
1790b57cec5SDimitry Andric 
180*1db9f3b2SDimitry Andric   LayoutInfo.SSPBufferSize = Fn.getFnAttributeAsParsedInteger(
181*1db9f3b2SDimitry Andric       "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
182*1db9f3b2SDimitry Andric   if (!requiresStackProtector(F, &LayoutInfo.Layout))
1830b57cec5SDimitry Andric     return false;
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   // TODO(etienneb): Functions with funclets are not correctly supported now.
1860b57cec5SDimitry Andric   // Do nothing if this is funclet-based personality.
1870b57cec5SDimitry Andric   if (Fn.hasPersonalityFn()) {
1880b57cec5SDimitry Andric     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
1890b57cec5SDimitry Andric     if (isFuncletEHPersonality(Personality))
1900b57cec5SDimitry Andric       return false;
1910b57cec5SDimitry Andric   }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   ++NumFunProtected;
194*1db9f3b2SDimitry Andric   bool Changed =
195*1db9f3b2SDimitry Andric       InsertStackProtectors(TM, F, DTU ? &*DTU : nullptr,
196*1db9f3b2SDimitry Andric                             LayoutInfo.HasPrologue, LayoutInfo.HasIRCheck);
197bdd1243dSDimitry Andric #ifdef EXPENSIVE_CHECKS
198bdd1243dSDimitry Andric   assert((!DTU ||
199bdd1243dSDimitry Andric           DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full)) &&
200bdd1243dSDimitry Andric          "Failed to maintain validity of domtree!");
201bdd1243dSDimitry Andric #endif
202bdd1243dSDimitry Andric   DTU.reset();
203bdd1243dSDimitry Andric   return Changed;
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and
2070b57cec5SDimitry Andric /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
2080b57cec5SDimitry Andric /// multiple arrays, this gets set if any of them is large.
ContainsProtectableArray(Type * Ty,Module * M,unsigned SSPBufferSize,bool & IsLarge,bool Strong,bool InStruct)20906c3fb27SDimitry Andric static bool ContainsProtectableArray(Type *Ty, Module *M, unsigned SSPBufferSize,
21006c3fb27SDimitry Andric                                      bool &IsLarge, bool Strong,
21106c3fb27SDimitry Andric                                      bool InStruct) {
2120b57cec5SDimitry Andric   if (!Ty)
2130b57cec5SDimitry Andric     return false;
2140b57cec5SDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
2150b57cec5SDimitry Andric     if (!AT->getElementType()->isIntegerTy(8)) {
2160b57cec5SDimitry Andric       // If we're on a non-Darwin platform or we're inside of a structure, don't
2170b57cec5SDimitry Andric       // add stack protectors unless the array is a character array.
2180b57cec5SDimitry Andric       // However, in strong mode any array, regardless of type and size,
2190b57cec5SDimitry Andric       // triggers a protector.
22006c3fb27SDimitry Andric       if (!Strong && (InStruct || !Triple(M->getTargetTriple()).isOSDarwin()))
2210b57cec5SDimitry Andric         return false;
2220b57cec5SDimitry Andric     }
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric     // If an array has more than SSPBufferSize bytes of allocated space, then we
2250b57cec5SDimitry Andric     // emit stack protectors.
2260b57cec5SDimitry Andric     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
2270b57cec5SDimitry Andric       IsLarge = true;
2280b57cec5SDimitry Andric       return true;
2290b57cec5SDimitry Andric     }
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric     if (Strong)
2320b57cec5SDimitry Andric       // Require a protector for all arrays in strong mode
2330b57cec5SDimitry Andric       return true;
2340b57cec5SDimitry Andric   }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   const StructType *ST = dyn_cast<StructType>(Ty);
2370b57cec5SDimitry Andric   if (!ST)
2380b57cec5SDimitry Andric     return false;
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   bool NeedsProtector = false;
241349cc55cSDimitry Andric   for (Type *ET : ST->elements())
24206c3fb27SDimitry Andric     if (ContainsProtectableArray(ET, M, SSPBufferSize, IsLarge, Strong, true)) {
2430b57cec5SDimitry Andric       // If the element is a protectable array and is large (>= SSPBufferSize)
2440b57cec5SDimitry Andric       // then we are done.  If the protectable array is not large, then
2450b57cec5SDimitry Andric       // keep looking in case a subsequent element is a large array.
2460b57cec5SDimitry Andric       if (IsLarge)
2470b57cec5SDimitry Andric         return true;
2480b57cec5SDimitry Andric       NeedsProtector = true;
2490b57cec5SDimitry Andric     }
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric   return NeedsProtector;
2520b57cec5SDimitry Andric }
2530b57cec5SDimitry Andric 
25406c3fb27SDimitry Andric /// Check whether a stack allocation has its address taken.
HasAddressTaken(const Instruction * AI,TypeSize AllocSize,Module * M,SmallPtrSet<const PHINode *,16> & VisitedPHIs)25506c3fb27SDimitry Andric static bool HasAddressTaken(const Instruction *AI, TypeSize AllocSize,
25606c3fb27SDimitry Andric                             Module *M,
25706c3fb27SDimitry Andric                             SmallPtrSet<const PHINode *, 16> &VisitedPHIs) {
2585ffd83dbSDimitry Andric   const DataLayout &DL = M->getDataLayout();
259c14a5a88SDimitry Andric   for (const User *U : AI->users()) {
260c14a5a88SDimitry Andric     const auto *I = cast<Instruction>(U);
2615ffd83dbSDimitry Andric     // If this instruction accesses memory make sure it doesn't access beyond
2625ffd83dbSDimitry Andric     // the bounds of the allocated object.
263bdd1243dSDimitry Andric     std::optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I);
26481ad6265SDimitry Andric     if (MemLoc && MemLoc->Size.hasValue() &&
2655f757f3fSDimitry Andric         !TypeSize::isKnownGE(AllocSize, MemLoc->Size.getValue()))
2665ffd83dbSDimitry Andric       return true;
267c14a5a88SDimitry Andric     switch (I->getOpcode()) {
268c14a5a88SDimitry Andric     case Instruction::Store:
269c14a5a88SDimitry Andric       if (AI == cast<StoreInst>(I)->getValueOperand())
270c14a5a88SDimitry Andric         return true;
271c14a5a88SDimitry Andric       break;
272c14a5a88SDimitry Andric     case Instruction::AtomicCmpXchg:
273c14a5a88SDimitry Andric       // cmpxchg conceptually includes both a load and store from the same
274c14a5a88SDimitry Andric       // location. So, like store, the value being stored is what matters.
275c14a5a88SDimitry Andric       if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
276c14a5a88SDimitry Andric         return true;
277c14a5a88SDimitry Andric       break;
278c14a5a88SDimitry Andric     case Instruction::PtrToInt:
279c14a5a88SDimitry Andric       if (AI == cast<PtrToIntInst>(I)->getOperand(0))
280c14a5a88SDimitry Andric         return true;
281c14a5a88SDimitry Andric       break;
282c14a5a88SDimitry Andric     case Instruction::Call: {
283c14a5a88SDimitry Andric       // Ignore intrinsics that do not become real instructions.
284c14a5a88SDimitry Andric       // TODO: Narrow this to intrinsics that have store-like effects.
285c14a5a88SDimitry Andric       const auto *CI = cast<CallInst>(I);
286d409305fSDimitry Andric       if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd())
287c14a5a88SDimitry Andric         return true;
288c14a5a88SDimitry Andric       break;
289c14a5a88SDimitry Andric     }
290c14a5a88SDimitry Andric     case Instruction::Invoke:
291c14a5a88SDimitry Andric       return true;
2925ffd83dbSDimitry Andric     case Instruction::GetElementPtr: {
2935ffd83dbSDimitry Andric       // If the GEP offset is out-of-bounds, or is non-constant and so has to be
2945ffd83dbSDimitry Andric       // assumed to be potentially out-of-bounds, then any memory access that
2955ffd83dbSDimitry Andric       // would use it could also be out-of-bounds meaning stack protection is
2965ffd83dbSDimitry Andric       // required.
2975ffd83dbSDimitry Andric       const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
2980eae32dcSDimitry Andric       unsigned IndexSize = DL.getIndexTypeSizeInBits(I->getType());
2990eae32dcSDimitry Andric       APInt Offset(IndexSize, 0);
3000eae32dcSDimitry Andric       if (!GEP->accumulateConstantOffset(DL, Offset))
3010eae32dcSDimitry Andric         return true;
3025f757f3fSDimitry Andric       TypeSize OffsetSize = TypeSize::getFixed(Offset.getLimitedValue());
3030eae32dcSDimitry Andric       if (!TypeSize::isKnownGT(AllocSize, OffsetSize))
3045ffd83dbSDimitry Andric         return true;
3055ffd83dbSDimitry Andric       // Adjust AllocSize to be the space remaining after this offset.
3060eae32dcSDimitry Andric       // We can't subtract a fixed size from a scalable one, so in that case
3070eae32dcSDimitry Andric       // assume the scalable value is of minimum size.
3080eae32dcSDimitry Andric       TypeSize NewAllocSize =
3095f757f3fSDimitry Andric           TypeSize::getFixed(AllocSize.getKnownMinValue()) - OffsetSize;
31006c3fb27SDimitry Andric       if (HasAddressTaken(I, NewAllocSize, M, VisitedPHIs))
3115ffd83dbSDimitry Andric         return true;
3125ffd83dbSDimitry Andric       break;
3135ffd83dbSDimitry Andric     }
314c14a5a88SDimitry Andric     case Instruction::BitCast:
315c14a5a88SDimitry Andric     case Instruction::Select:
316c14a5a88SDimitry Andric     case Instruction::AddrSpaceCast:
31706c3fb27SDimitry Andric       if (HasAddressTaken(I, AllocSize, M, VisitedPHIs))
318c14a5a88SDimitry Andric         return true;
319c14a5a88SDimitry Andric       break;
320c14a5a88SDimitry Andric     case Instruction::PHI: {
321c14a5a88SDimitry Andric       // Keep track of what PHI nodes we have already visited to ensure
322c14a5a88SDimitry Andric       // they are only visited once.
323c14a5a88SDimitry Andric       const auto *PN = cast<PHINode>(I);
324c14a5a88SDimitry Andric       if (VisitedPHIs.insert(PN).second)
32506c3fb27SDimitry Andric         if (HasAddressTaken(PN, AllocSize, M, VisitedPHIs))
326c14a5a88SDimitry Andric           return true;
327c14a5a88SDimitry Andric       break;
328c14a5a88SDimitry Andric     }
329c14a5a88SDimitry Andric     case Instruction::Load:
330c14a5a88SDimitry Andric     case Instruction::AtomicRMW:
331c14a5a88SDimitry Andric     case Instruction::Ret:
332c14a5a88SDimitry Andric       // These instructions take an address operand, but have load-like or
333c14a5a88SDimitry Andric       // other innocuous behavior that should not trigger a stack protector.
334c14a5a88SDimitry Andric       // atomicrmw conceptually has both load and store semantics, but the
335c14a5a88SDimitry Andric       // value being stored must be integer; so if a pointer is being stored,
336c14a5a88SDimitry Andric       // we'll catch it in the PtrToInt case above.
337c14a5a88SDimitry Andric       break;
338c14a5a88SDimitry Andric     default:
339c14a5a88SDimitry Andric       // Conservatively return true for any instruction that takes an address
340c14a5a88SDimitry Andric       // operand, but is not handled above.
341c14a5a88SDimitry Andric       return true;
342c14a5a88SDimitry Andric     }
343c14a5a88SDimitry Andric   }
344c14a5a88SDimitry Andric   return false;
345c14a5a88SDimitry Andric }
346c14a5a88SDimitry Andric 
3470b57cec5SDimitry Andric /// Search for the first call to the llvm.stackprotector intrinsic and return it
3480b57cec5SDimitry Andric /// if present.
findStackProtectorIntrinsic(Function & F)3490b57cec5SDimitry Andric static const CallInst *findStackProtectorIntrinsic(Function &F) {
3500b57cec5SDimitry Andric   for (const BasicBlock &BB : F)
3510b57cec5SDimitry Andric     for (const Instruction &I : BB)
352e8d8bef9SDimitry Andric       if (const auto *II = dyn_cast<IntrinsicInst>(&I))
353e8d8bef9SDimitry Andric         if (II->getIntrinsicID() == Intrinsic::stackprotector)
354e8d8bef9SDimitry Andric           return II;
3550b57cec5SDimitry Andric   return nullptr;
3560b57cec5SDimitry Andric }
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric /// Check whether or not this function needs a stack protector based
3590b57cec5SDimitry Andric /// upon the stack protector level.
3600b57cec5SDimitry Andric ///
3610b57cec5SDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong).
3620b57cec5SDimitry Andric /// The standard heuristic which will add a guard variable to functions that
3630b57cec5SDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize,
3640b57cec5SDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions
3650b57cec5SDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The
3660b57cec5SDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca
3670b57cec5SDimitry Andric /// regardless of size, functions with any buffer regardless of type and size,
3680b57cec5SDimitry Andric /// functions with aggregates that contain any buffer regardless of type and
3690b57cec5SDimitry Andric /// size, and functions that contain stack-based variables that have had their
3700b57cec5SDimitry Andric /// address taken.
requiresStackProtector(Function * F,SSPLayoutMap * Layout)371*1db9f3b2SDimitry Andric bool SSPLayoutAnalysis::requiresStackProtector(Function *F,
372*1db9f3b2SDimitry Andric                                                SSPLayoutMap *Layout) {
37306c3fb27SDimitry Andric   Module *M = F->getParent();
3740b57cec5SDimitry Andric   bool Strong = false;
3750b57cec5SDimitry Andric   bool NeedsProtector = false;
3760b57cec5SDimitry Andric 
37706c3fb27SDimitry Andric   // The set of PHI nodes visited when determining if a variable's reference has
37806c3fb27SDimitry Andric   // been taken.  This set is maintained to ensure we don't visit the same PHI
37906c3fb27SDimitry Andric   // node multiple times.
38006c3fb27SDimitry Andric   SmallPtrSet<const PHINode *, 16> VisitedPHIs;
38106c3fb27SDimitry Andric 
38206c3fb27SDimitry Andric   unsigned SSPBufferSize = F->getFnAttributeAsParsedInteger(
383*1db9f3b2SDimitry Andric       "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
38406c3fb27SDimitry Andric 
3850b57cec5SDimitry Andric   if (F->hasFnAttribute(Attribute::SafeStack))
3860b57cec5SDimitry Andric     return false;
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   // We are constructing the OptimizationRemarkEmitter on the fly rather than
3890b57cec5SDimitry Andric   // using the analysis pass to avoid building DominatorTree and LoopInfo which
3900b57cec5SDimitry Andric   // are not available this late in the IR pipeline.
3910b57cec5SDimitry Andric   OptimizationRemarkEmitter ORE(F);
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
39406c3fb27SDimitry Andric     if (!Layout)
39506c3fb27SDimitry Andric       return true;
3960b57cec5SDimitry Andric     ORE.emit([&]() {
3970b57cec5SDimitry Andric       return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
3980b57cec5SDimitry Andric              << "Stack protection applied to function "
3990b57cec5SDimitry Andric              << ore::NV("Function", F)
4000b57cec5SDimitry Andric              << " due to a function attribute or command-line switch";
4010b57cec5SDimitry Andric     });
4020b57cec5SDimitry Andric     NeedsProtector = true;
4030b57cec5SDimitry Andric     Strong = true; // Use the same heuristic as strong to determine SSPLayout
4040b57cec5SDimitry Andric   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
4050b57cec5SDimitry Andric     Strong = true;
4060b57cec5SDimitry Andric   else if (!F->hasFnAttribute(Attribute::StackProtect))
4070b57cec5SDimitry Andric     return false;
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   for (const BasicBlock &BB : *F) {
4100b57cec5SDimitry Andric     for (const Instruction &I : BB) {
4110b57cec5SDimitry Andric       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
4120b57cec5SDimitry Andric         if (AI->isArrayAllocation()) {
4130b57cec5SDimitry Andric           auto RemarkBuilder = [&]() {
4140b57cec5SDimitry Andric             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
4150b57cec5SDimitry Andric                                       &I)
4160b57cec5SDimitry Andric                    << "Stack protection applied to function "
4170b57cec5SDimitry Andric                    << ore::NV("Function", F)
4180b57cec5SDimitry Andric                    << " due to a call to alloca or use of a variable length "
4190b57cec5SDimitry Andric                       "array";
4200b57cec5SDimitry Andric           };
4210b57cec5SDimitry Andric           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
4220b57cec5SDimitry Andric             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
4230b57cec5SDimitry Andric               // A call to alloca with size >= SSPBufferSize requires
4240b57cec5SDimitry Andric               // stack protectors.
42506c3fb27SDimitry Andric               if (!Layout)
42606c3fb27SDimitry Andric                 return true;
42706c3fb27SDimitry Andric               Layout->insert(
42806c3fb27SDimitry Andric                   std::make_pair(AI, MachineFrameInfo::SSPLK_LargeArray));
4290b57cec5SDimitry Andric               ORE.emit(RemarkBuilder);
4300b57cec5SDimitry Andric               NeedsProtector = true;
4310b57cec5SDimitry Andric             } else if (Strong) {
4320b57cec5SDimitry Andric               // Require protectors for all alloca calls in strong mode.
43306c3fb27SDimitry Andric               if (!Layout)
43406c3fb27SDimitry Andric                 return true;
43506c3fb27SDimitry Andric               Layout->insert(
43606c3fb27SDimitry Andric                   std::make_pair(AI, MachineFrameInfo::SSPLK_SmallArray));
4370b57cec5SDimitry Andric               ORE.emit(RemarkBuilder);
4380b57cec5SDimitry Andric               NeedsProtector = true;
4390b57cec5SDimitry Andric             }
4400b57cec5SDimitry Andric           } else {
4410b57cec5SDimitry Andric             // A call to alloca with a variable size requires protectors.
44206c3fb27SDimitry Andric             if (!Layout)
44306c3fb27SDimitry Andric               return true;
44406c3fb27SDimitry Andric             Layout->insert(
44506c3fb27SDimitry Andric                 std::make_pair(AI, MachineFrameInfo::SSPLK_LargeArray));
4460b57cec5SDimitry Andric             ORE.emit(RemarkBuilder);
4470b57cec5SDimitry Andric             NeedsProtector = true;
4480b57cec5SDimitry Andric           }
4490b57cec5SDimitry Andric           continue;
4500b57cec5SDimitry Andric         }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric         bool IsLarge = false;
45306c3fb27SDimitry Andric         if (ContainsProtectableArray(AI->getAllocatedType(), M, SSPBufferSize,
45406c3fb27SDimitry Andric                                      IsLarge, Strong, false)) {
45506c3fb27SDimitry Andric           if (!Layout)
45606c3fb27SDimitry Andric             return true;
45706c3fb27SDimitry Andric           Layout->insert(std::make_pair(
45806c3fb27SDimitry Andric               AI, IsLarge ? MachineFrameInfo::SSPLK_LargeArray
4590b57cec5SDimitry Andric                           : MachineFrameInfo::SSPLK_SmallArray));
4600b57cec5SDimitry Andric           ORE.emit([&]() {
4610b57cec5SDimitry Andric             return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
4620b57cec5SDimitry Andric                    << "Stack protection applied to function "
4630b57cec5SDimitry Andric                    << ore::NV("Function", F)
4640b57cec5SDimitry Andric                    << " due to a stack allocated buffer or struct containing a "
4650b57cec5SDimitry Andric                       "buffer";
4660b57cec5SDimitry Andric           });
4670b57cec5SDimitry Andric           NeedsProtector = true;
4680b57cec5SDimitry Andric           continue;
4690b57cec5SDimitry Andric         }
4700b57cec5SDimitry Andric 
47106c3fb27SDimitry Andric         if (Strong &&
47206c3fb27SDimitry Andric             HasAddressTaken(
47306c3fb27SDimitry Andric                 AI, M->getDataLayout().getTypeAllocSize(AI->getAllocatedType()),
47406c3fb27SDimitry Andric                 M, VisitedPHIs)) {
4750b57cec5SDimitry Andric           ++NumAddrTaken;
47606c3fb27SDimitry Andric           if (!Layout)
47706c3fb27SDimitry Andric             return true;
47806c3fb27SDimitry Andric           Layout->insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
4790b57cec5SDimitry Andric           ORE.emit([&]() {
4800b57cec5SDimitry Andric             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
4810b57cec5SDimitry Andric                                       &I)
4820b57cec5SDimitry Andric                    << "Stack protection applied to function "
4830b57cec5SDimitry Andric                    << ore::NV("Function", F)
4840b57cec5SDimitry Andric                    << " due to the address of a local variable being taken";
4850b57cec5SDimitry Andric           });
4860b57cec5SDimitry Andric           NeedsProtector = true;
4870b57cec5SDimitry Andric         }
4885ffd83dbSDimitry Andric         // Clear any PHIs that we visited, to make sure we examine all uses of
4895ffd83dbSDimitry Andric         // any subsequent allocas that we look at.
4905ffd83dbSDimitry Andric         VisitedPHIs.clear();
4910b57cec5SDimitry Andric       }
4920b57cec5SDimitry Andric     }
4930b57cec5SDimitry Andric   }
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   return NeedsProtector;
4960b57cec5SDimitry Andric }
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric /// Create a stack guard loading and populate whether SelectionDAG SSP is
4990b57cec5SDimitry Andric /// supported.
getStackGuard(const TargetLoweringBase * TLI,Module * M,IRBuilder<> & B,bool * SupportsSelectionDAGSP=nullptr)5000b57cec5SDimitry Andric static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
5010b57cec5SDimitry Andric                             IRBuilder<> &B,
5020b57cec5SDimitry Andric                             bool *SupportsSelectionDAGSP = nullptr) {
503e8d8bef9SDimitry Andric   Value *Guard = TLI->getIRStackGuard(B);
504fe6060f1SDimitry Andric   StringRef GuardMode = M->getStackProtectorGuard();
505fe6060f1SDimitry Andric   if ((GuardMode == "tls" || GuardMode.empty()) && Guard)
5065f757f3fSDimitry Andric     return B.CreateLoad(B.getPtrTy(), Guard, true, "StackGuard");
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   // Use SelectionDAG SSP handling, since there isn't an IR guard.
5090b57cec5SDimitry Andric   //
5100b57cec5SDimitry Andric   // This is more or less weird, since we optionally output whether we
5110b57cec5SDimitry Andric   // should perform a SelectionDAG SP here. The reason is that it's strictly
5120b57cec5SDimitry Andric   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
5130b57cec5SDimitry Andric   // mutating. There is no way to get this bit without mutating the IR, so
5140b57cec5SDimitry Andric   // getting this bit has to happen in this right time.
5150b57cec5SDimitry Andric   //
5160b57cec5SDimitry Andric   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
5170b57cec5SDimitry Andric   // will put more burden on the backends' overriding work, especially when it
5180b57cec5SDimitry Andric   // actually conveys the same information getIRStackGuard() already gives.
5190b57cec5SDimitry Andric   if (SupportsSelectionDAGSP)
5200b57cec5SDimitry Andric     *SupportsSelectionDAGSP = true;
5210b57cec5SDimitry Andric   TLI->insertSSPDeclarations(*M);
5220b57cec5SDimitry Andric   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
5230b57cec5SDimitry Andric }
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric /// Insert code into the entry block that stores the stack guard
5260b57cec5SDimitry Andric /// variable onto the stack:
5270b57cec5SDimitry Andric ///
5280b57cec5SDimitry Andric ///   entry:
5290b57cec5SDimitry Andric ///     StackGuardSlot = alloca i8*
5300b57cec5SDimitry Andric ///     StackGuard = <stack guard>
5310b57cec5SDimitry Andric ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
5320b57cec5SDimitry Andric ///
5330b57cec5SDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
5340b57cec5SDimitry Andric /// node.
CreatePrologue(Function * F,Module * M,Instruction * CheckLoc,const TargetLoweringBase * TLI,AllocaInst * & AI)535bdd1243dSDimitry Andric static bool CreatePrologue(Function *F, Module *M, Instruction *CheckLoc,
5360b57cec5SDimitry Andric                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
5370b57cec5SDimitry Andric   bool SupportsSelectionDAGSP = false;
5380b57cec5SDimitry Andric   IRBuilder<> B(&F->getEntryBlock().front());
5395f757f3fSDimitry Andric   PointerType *PtrTy = PointerType::getUnqual(CheckLoc->getContext());
5400b57cec5SDimitry Andric   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
5430b57cec5SDimitry Andric   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
5440b57cec5SDimitry Andric                {GuardSlot, AI});
5450b57cec5SDimitry Andric   return SupportsSelectionDAGSP;
5460b57cec5SDimitry Andric }
5470b57cec5SDimitry Andric 
InsertStackProtectors(const TargetMachine * TM,Function * F,DomTreeUpdater * DTU,bool & HasPrologue,bool & HasIRCheck)548*1db9f3b2SDimitry Andric bool InsertStackProtectors(const TargetMachine *TM, Function *F,
549*1db9f3b2SDimitry Andric                            DomTreeUpdater *DTU, bool &HasPrologue,
550*1db9f3b2SDimitry Andric                            bool &HasIRCheck) {
551*1db9f3b2SDimitry Andric   auto *M = F->getParent();
552*1db9f3b2SDimitry Andric   auto *TLI = TM->getSubtargetImpl(*F)->getTargetLowering();
553*1db9f3b2SDimitry Andric 
5540b57cec5SDimitry Andric   // If the target wants to XOR the frame pointer into the guard value, it's
5550b57cec5SDimitry Andric   // impossible to emit the check in IR, so the target *must* support stack
5560b57cec5SDimitry Andric   // protection in SDAG.
5570b57cec5SDimitry Andric   bool SupportsSelectionDAGSP =
5580b57cec5SDimitry Andric       TLI->useStackGuardXorFP() ||
559349cc55cSDimitry Andric       (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
5600b57cec5SDimitry Andric   AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
561bdd1243dSDimitry Andric   BasicBlock *FailBB = nullptr;
5620b57cec5SDimitry Andric 
563349cc55cSDimitry Andric   for (BasicBlock &BB : llvm::make_early_inc_range(*F)) {
564bdd1243dSDimitry Andric     // This is stack protector auto generated check BB, skip it.
565bdd1243dSDimitry Andric     if (&BB == FailBB)
566bdd1243dSDimitry Andric       continue;
567bdd1243dSDimitry Andric     Instruction *CheckLoc = dyn_cast<ReturnInst>(BB.getTerminator());
5689e7101a8SDimitry Andric     if (!CheckLoc && !DisableCheckNoReturn)
5699e7101a8SDimitry Andric       for (auto &Inst : BB)
5709e7101a8SDimitry Andric         if (auto *CB = dyn_cast<CallBase>(&Inst))
5719e7101a8SDimitry Andric           // Do stack check before noreturn calls that aren't nounwind (e.g:
5729e7101a8SDimitry Andric           // __cxa_throw).
5739e7101a8SDimitry Andric           if (CB->doesNotReturn() && !CB->doesNotThrow()) {
574bdd1243dSDimitry Andric             CheckLoc = CB;
575bdd1243dSDimitry Andric             break;
576bdd1243dSDimitry Andric           }
577bdd1243dSDimitry Andric 
578bdd1243dSDimitry Andric     if (!CheckLoc)
5790b57cec5SDimitry Andric       continue;
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric     // Generate prologue instrumentation if not already generated.
5820b57cec5SDimitry Andric     if (!HasPrologue) {
5830b57cec5SDimitry Andric       HasPrologue = true;
584bdd1243dSDimitry Andric       SupportsSelectionDAGSP &= CreatePrologue(F, M, CheckLoc, TLI, AI);
5850b57cec5SDimitry Andric     }
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric     // SelectionDAG based code generation. Nothing else needs to be done here.
5880b57cec5SDimitry Andric     // The epilogue instrumentation is postponed to SelectionDAG.
5890b57cec5SDimitry Andric     if (SupportsSelectionDAGSP)
5900b57cec5SDimitry Andric       break;
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric     // Find the stack guard slot if the prologue was not created by this pass
5930b57cec5SDimitry Andric     // itself via a previous call to CreatePrologue().
5940b57cec5SDimitry Andric     if (!AI) {
5950b57cec5SDimitry Andric       const CallInst *SPCall = findStackProtectorIntrinsic(*F);
5960b57cec5SDimitry Andric       assert(SPCall && "Call to llvm.stackprotector is missing");
5970b57cec5SDimitry Andric       AI = cast<AllocaInst>(SPCall->getArgOperand(1));
5980b57cec5SDimitry Andric     }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
6010b57cec5SDimitry Andric     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
6020b57cec5SDimitry Andric     // instrumentation has already been generated.
6030b57cec5SDimitry Andric     HasIRCheck = true;
6040b57cec5SDimitry Andric 
605bdd1243dSDimitry Andric     // If we're instrumenting a block with a tail call, the check has to be
60623408297SDimitry Andric     // inserted before the call rather than between it and the return. The
607bdd1243dSDimitry Andric     // verifier guarantees that a tail call is either directly before the
60823408297SDimitry Andric     // return or with a single correct bitcast of the return value in between so
60923408297SDimitry Andric     // we don't need to worry about many situations here.
610bdd1243dSDimitry Andric     Instruction *Prev = CheckLoc->getPrevNonDebugInstruction();
611bdd1243dSDimitry Andric     if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isTailCall())
61223408297SDimitry Andric       CheckLoc = Prev;
61323408297SDimitry Andric     else if (Prev) {
61423408297SDimitry Andric       Prev = Prev->getPrevNonDebugInstruction();
615bdd1243dSDimitry Andric       if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isTailCall())
61623408297SDimitry Andric         CheckLoc = Prev;
61723408297SDimitry Andric     }
61823408297SDimitry Andric 
6190b57cec5SDimitry Andric     // Generate epilogue instrumentation. The epilogue intrumentation can be
6200b57cec5SDimitry Andric     // function-based or inlined depending on which mechanism the target is
6210b57cec5SDimitry Andric     // providing.
6220b57cec5SDimitry Andric     if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
6230b57cec5SDimitry Andric       // Generate the function-based epilogue instrumentation.
6240b57cec5SDimitry Andric       // The target provides a guard check function, generate a call to it.
62523408297SDimitry Andric       IRBuilder<> B(CheckLoc);
6265f757f3fSDimitry Andric       LoadInst *Guard = B.CreateLoad(B.getPtrTy(), AI, true, "Guard");
6270b57cec5SDimitry Andric       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
6280b57cec5SDimitry Andric       Call->setAttributes(GuardCheck->getAttributes());
6290b57cec5SDimitry Andric       Call->setCallingConv(GuardCheck->getCallingConv());
6300b57cec5SDimitry Andric     } else {
6310b57cec5SDimitry Andric       // Generate the epilogue with inline instrumentation.
63223408297SDimitry Andric       // If we do not support SelectionDAG based calls, generate IR level
63323408297SDimitry Andric       // calls.
6340b57cec5SDimitry Andric       //
6350b57cec5SDimitry Andric       // For each block with a return instruction, convert this:
6360b57cec5SDimitry Andric       //
6370b57cec5SDimitry Andric       //   return:
6380b57cec5SDimitry Andric       //     ...
6390b57cec5SDimitry Andric       //     ret ...
6400b57cec5SDimitry Andric       //
6410b57cec5SDimitry Andric       // into this:
6420b57cec5SDimitry Andric       //
6430b57cec5SDimitry Andric       //   return:
6440b57cec5SDimitry Andric       //     ...
6450b57cec5SDimitry Andric       //     %1 = <stack guard>
6460b57cec5SDimitry Andric       //     %2 = load StackGuardSlot
647bdd1243dSDimitry Andric       //     %3 = icmp ne i1 %1, %2
648bdd1243dSDimitry Andric       //     br i1 %3, label %CallStackCheckFailBlk, label %SP_return
6490b57cec5SDimitry Andric       //
6500b57cec5SDimitry Andric       //   SP_return:
6510b57cec5SDimitry Andric       //     ret ...
6520b57cec5SDimitry Andric       //
6530b57cec5SDimitry Andric       //   CallStackCheckFailBlk:
6540b57cec5SDimitry Andric       //     call void @__stack_chk_fail()
6550b57cec5SDimitry Andric       //     unreachable
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric       // Create the FailBB. We duplicate the BB every time since the MI tail
6580b57cec5SDimitry Andric       // merge pass will merge together all of the various BB into one including
6590b57cec5SDimitry Andric       // fail BB generated by the stack protector pseudo instruction.
660bdd1243dSDimitry Andric       if (!FailBB)
661*1db9f3b2SDimitry Andric         FailBB = CreateFailBB(F, TM->getTargetTriple());
6620b57cec5SDimitry Andric 
663bdd1243dSDimitry Andric       IRBuilder<> B(CheckLoc);
6640b57cec5SDimitry Andric       Value *Guard = getStackGuard(TLI, M, B);
6655f757f3fSDimitry Andric       LoadInst *LI2 = B.CreateLoad(B.getPtrTy(), AI, true);
666bdd1243dSDimitry Andric       auto *Cmp = cast<ICmpInst>(B.CreateICmpNE(Guard, LI2));
6670b57cec5SDimitry Andric       auto SuccessProb =
6680b57cec5SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(true);
6690b57cec5SDimitry Andric       auto FailureProb =
6700b57cec5SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(false);
6710b57cec5SDimitry Andric       MDNode *Weights = MDBuilder(F->getContext())
672bdd1243dSDimitry Andric                             .createBranchWeights(FailureProb.getNumerator(),
673bdd1243dSDimitry Andric                                                  SuccessProb.getNumerator());
674bdd1243dSDimitry Andric 
675bdd1243dSDimitry Andric       SplitBlockAndInsertIfThen(Cmp, CheckLoc,
676*1db9f3b2SDimitry Andric                                 /*Unreachable=*/false, Weights, DTU,
677bdd1243dSDimitry Andric                                 /*LI=*/nullptr, /*ThenBlock=*/FailBB);
678bdd1243dSDimitry Andric 
679bdd1243dSDimitry Andric       auto *BI = cast<BranchInst>(Cmp->getParent()->getTerminator());
680bdd1243dSDimitry Andric       BasicBlock *NewBB = BI->getSuccessor(1);
681bdd1243dSDimitry Andric       NewBB->setName("SP_return");
682bdd1243dSDimitry Andric       NewBB->moveAfter(&BB);
683bdd1243dSDimitry Andric 
684bdd1243dSDimitry Andric       Cmp->setPredicate(Cmp->getInversePredicate());
685bdd1243dSDimitry Andric       BI->swapSuccessors();
6860b57cec5SDimitry Andric     }
6870b57cec5SDimitry Andric   }
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   // Return if we didn't modify any basic blocks. i.e., there are no return
6900b57cec5SDimitry Andric   // statements in the function.
6910b57cec5SDimitry Andric   return HasPrologue;
6920b57cec5SDimitry Andric }
6930b57cec5SDimitry Andric 
CreateFailBB(Function * F,const Triple & Trip)694*1db9f3b2SDimitry Andric BasicBlock *CreateFailBB(Function *F, const Triple &Trip) {
695*1db9f3b2SDimitry Andric   auto *M = F->getParent();
6960b57cec5SDimitry Andric   LLVMContext &Context = F->getContext();
6970b57cec5SDimitry Andric   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
6980b57cec5SDimitry Andric   IRBuilder<> B(FailBB);
699e8d8bef9SDimitry Andric   if (F->getSubprogram())
700e8d8bef9SDimitry Andric     B.SetCurrentDebugLocation(
701e8d8bef9SDimitry Andric         DILocation::get(Context, 0, 0, F->getSubprogram()));
70206c3fb27SDimitry Andric   FunctionCallee StackChkFail;
70306c3fb27SDimitry Andric   SmallVector<Value *, 1> Args;
7040b57cec5SDimitry Andric   if (Trip.isOSOpenBSD()) {
70506c3fb27SDimitry Andric     StackChkFail = M->getOrInsertFunction("__stack_smash_handler",
70606c3fb27SDimitry Andric                                           Type::getVoidTy(Context),
7075f757f3fSDimitry Andric                                           PointerType::getUnqual(Context));
70806c3fb27SDimitry Andric     Args.push_back(B.CreateGlobalStringPtr(F->getName(), "SSH"));
7090b57cec5SDimitry Andric   } else {
71006c3fb27SDimitry Andric     StackChkFail =
7110b57cec5SDimitry Andric         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
7120b57cec5SDimitry Andric   }
71306c3fb27SDimitry Andric   cast<Function>(StackChkFail.getCallee())->addFnAttr(Attribute::NoReturn);
71406c3fb27SDimitry Andric   B.CreateCall(StackChkFail, Args);
7150b57cec5SDimitry Andric   B.CreateUnreachable();
7160b57cec5SDimitry Andric   return FailBB;
7170b57cec5SDimitry Andric }
718