12b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling//===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
22b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling//
32b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling//                     The LLVM Compiler Infrastructure
42b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling//
52b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling// This file is distributed under the University of Illinois Open Source
62b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling// License. See LICENSE.TXT for details.
72b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling//
82b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling//===----------------------------------------------------------------------===//
92b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling//
1080a320d974dae7666157e80b141d7ff97e5f6544Bill Wendling// This pass inserts stack protectors into functions which need them. A variable
1180a320d974dae7666157e80b141d7ff97e5f6544Bill Wendling// with a random value in it is stored onto the stack before the local variables
1280a320d974dae7666157e80b141d7ff97e5f6544Bill Wendling// are allocated. Upon exiting the block, the stored value is checked. If it's
132b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling// changed, then there was some sort of violation and the program aborts.
142b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling//
152b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling//===----------------------------------------------------------------------===//
162b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling
1718ebd48960afe9a4e694dac3ba0ee1002044d297Josh Magee#include "llvm/CodeGen/StackProtector.h"
18e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling#include "llvm/ADT/SmallPtrSet.h"
19e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling#include "llvm/ADT/Statistic.h"
20ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines#include "llvm/Analysis/BranchProbabilityInfo.h"
21de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar#include "llvm/Analysis/EHPersonalities.h"
223480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman#include "llvm/Analysis/ValueTracking.h"
2336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/CodeGen/Passes.h"
240b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Attributes.h"
250b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Constants.h"
260b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DataLayout.h"
27de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar#include "llvm/IR/DebugInfo.h"
280b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DerivedTypes.h"
290b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Function.h"
3062ed8d3e35d25853e32db946a0a60da0bbf862e1Rafael Espindola#include "llvm/IR/GlobalValue.h"
3162ed8d3e35d25853e32db946a0a60da0bbf862e1Rafael Espindola#include "llvm/IR/GlobalVariable.h"
3254cf1413aca342753ab846d915c6a55d9c087bc6Benjamin Kramer#include "llvm/IR/IRBuilder.h"
330b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Instructions.h"
343480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman#include "llvm/IR/IntrinsicInst.h"
350b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Intrinsics.h"
36ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines#include "llvm/IR/MDBuilder.h"
370b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Module.h"
382b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling#include "llvm/Support/CommandLine.h"
3937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines#include "llvm/Target/TargetSubtargetInfo.h"
400dcba2fadb990ba2298ba43d76372c754b240ceeBill Wendling#include <cstdlib>
412b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendlingusing namespace llvm;
422b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling
43dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines#define DEBUG_TYPE "stack-protector"
44dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
45e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill WendlingSTATISTIC(NumFunProtected, "Number of functions protected");
46e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill WendlingSTATISTIC(NumAddrTaken, "Number of local variables that have their address"
47e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling                        " taken.");
48e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling
4962406fdc6f199e4e7df60830be45de4da97b34c7Josh Mageestatic cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
5062406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee                                          cl::init(true), cl::Hidden);
513480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman
522b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendlingchar StackProtector::ID = 0;
5362406fdc6f199e4e7df60830be45de4da97b34c7Josh MageeINITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
5462406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee                false, true)
552b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling
56ea44281d5da5096de50ce1cb358ff0c6f20e1a2aBill WendlingFunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
57ea44281d5da5096de50ce1cb358ff0c6f20e1a2aBill Wendling  return new StackProtector(TM);
582b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling}
592b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling
6062406fdc6f199e4e7df60830be45de4da97b34c7Josh MageeStackProtector::SSPLayoutKind
6162406fdc6f199e4e7df60830be45de4da97b34c7Josh MageeStackProtector::getSSPLayout(const AllocaInst *AI) const {
624598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee  return AI ? Layout.lookup(AI) : SSPLK_None;
634598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee}
644598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee
6536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesvoid StackProtector::adjustForColoring(const AllocaInst *From,
6636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                       const AllocaInst *To) {
6736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // When coloring replaces one alloca with another, transfer the SSPLayoutKind
6836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // tag from the remapped to the target alloca. The remapped alloca should
6936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // have a size smaller than or equal to the replacement alloca.
7036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  SSPLayoutMap::iterator I = Layout.find(From);
7136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (I != Layout.end()) {
7236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    SSPLayoutKind Kind = I->second;
7336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Layout.erase(I);
7436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
7536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
7636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
7736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
7836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    I = Layout.find(To);
7936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (I == Layout.end())
8036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Layout.insert(std::make_pair(To, Kind));
8136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
8236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      I->second = Kind;
8336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
8436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines}
8536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
862b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendlingbool StackProtector::runOnFunction(Function &Fn) {
872b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling  F = &Fn;
882b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling  M = F->getParent();
8936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  DominatorTreeWrapperPass *DTWP =
9036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      getAnalysisIfAvailable<DominatorTreeWrapperPass>();
91dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  DT = DTWP ? &DTWP->getDomTree() : nullptr;
92ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
93de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  HasPrologue = false;
94de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  HasIRCheck = false;
952b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling
96ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
9736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (Attr.isStringAttribute() &&
9836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
99de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    return false; // Invalid integer string
1000dcba2fadb990ba2298ba43d76372c754b240ceeBill Wendling
101dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (!RequiresStackProtector())
102dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return false;
103dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
104de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // TODO(etienneb): Functions with funclets are not correctly supported now.
105de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // Do nothing if this is funclet-based personality.
106de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (Fn.hasPersonalityFn()) {
107de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
108de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    if (isFuncletEHPersonality(Personality))
109de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      return false;
110de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  }
111de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
112e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling  ++NumFunProtected;
113613f77439eb6e1f660e615e0e851187da13255aeBill Wendling  return InsertStackProtectors();
1142b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling}
1152b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling
1164598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee/// \param [out] IsLarge is set to true if a protectable array is found and
1174598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee/// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
1184598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee/// multiple arrays, this gets set if any of them is large.
1194598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Mageebool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
12062406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee                                              bool Strong,
12162406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee                                              bool InStruct) const {
12262406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee  if (!Ty)
12362406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee    return false;
124a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling  if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
125a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling    if (!AT->getElementType()->isIntegerTy(8)) {
126a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling      // If we're on a non-Darwin platform or we're inside of a structure, don't
127a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling      // add stack protectors unless the array is a character array.
1284598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      // However, in strong mode any array, regardless of type and size,
1294598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      // triggers a protector.
1304598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      if (!Strong && (InStruct || !Trip.isOSDarwin()))
1314598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee        return false;
132a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling    }
133a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling
134a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling    // If an array has more than SSPBufferSize bytes of allocated space, then we
135a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling    // emit stack protectors.
136f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
1374598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      IsLarge = true;
1384598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      return true;
13962406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee    }
1404598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee
1414598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee    if (Strong)
1424598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      // Require a protector for all arrays in strong mode
143a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling      return true;
144a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling  }
145a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling
146a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling  const StructType *ST = dyn_cast<StructType>(Ty);
14762406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee  if (!ST)
14862406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee    return false;
149a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling
1504598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee  bool NeedsProtector = false;
151a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling  for (StructType::element_iterator I = ST->element_begin(),
15262406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee                                    E = ST->element_end();
15362406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee       I != E; ++I)
1544598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee    if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
1554598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      // If the element is a protectable array and is large (>= SSPBufferSize)
1564598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      // then we are done.  If the protectable array is not large, then
1574598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      // keep looking in case a subsequent element is a large array.
1584598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      if (IsLarge)
1594598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee        return true;
1604598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee      NeedsProtector = true;
1614598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee    }
162a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling
1634598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee  return NeedsProtector;
164a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling}
165a67eda76c0224ec272e2cc7cf919f4e6e213e275Bill Wendling
166e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendlingbool StackProtector::HasAddressTaken(const Instruction *AI) {
16736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (const User *U : AI->users()) {
168e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
169e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling      if (AI == SI->getValueOperand())
170e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling        return true;
171e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
172e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling      if (AI == SI->getOperand(0))
173e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling        return true;
174e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    } else if (isa<CallInst>(U)) {
175e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling      return true;
176e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    } else if (isa<InvokeInst>(U)) {
177e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling      return true;
178e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
179e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling      if (HasAddressTaken(SI))
180e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling        return true;
181e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
182e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling      // Keep track of what PHI nodes we have already visited to ensure
183e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling      // they are only visited once.
18437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (VisitedPHIs.insert(PN).second)
185e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling        if (HasAddressTaken(PN))
186e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling          return true;
187e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
188e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling      if (HasAddressTaken(GEP))
189e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling        return true;
190e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
191e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling      if (HasAddressTaken(BI))
192e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling        return true;
193e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    }
194e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling  }
195e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling  return false;
196e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling}
197c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling
198e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// \brief Check whether or not this function needs a stack protector based
199e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// upon the stack protector level.
200e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling///
201e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// We use two heuristics: a standard (ssp) and strong (sspstrong).
202e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// The standard heuristic which will add a guard variable to functions that
203e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// call alloca with a either a variable size or a size >= SSPBufferSize,
204e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// functions with character buffers larger than SSPBufferSize, and functions
205e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// with aggregates containing character buffers larger than SSPBufferSize. The
206e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// strong heuristic will add a guard variables to functions that call alloca
207e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// regardless of size, functions with any buffer regardless of type and size,
208e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// functions with aggregates that contain any buffer regardless of type and
209e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// size, and functions that contain stack-based variables that have had their
210e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling/// address taken.
211e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendlingbool StackProtector::RequiresStackProtector() {
212e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling  bool Strong = false;
2134598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee  bool NeedsProtector = false;
214de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  for (const BasicBlock &BB : *F)
215de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    for (const Instruction &I : BB)
216de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      if (const CallInst *CI = dyn_cast<CallInst>(&I))
217de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        if (CI->getCalledFunction() ==
218de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            Intrinsic::getDeclaration(F->getParent(),
219de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                                      Intrinsic::stackprotector))
220de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          HasPrologue = true;
221de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
222de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (F->hasFnAttribute(Attribute::SafeStack))
223de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    return false;
224de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
225ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (F->hasFnAttribute(Attribute::StackProtectReq)) {
2264598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee    NeedsProtector = true;
2274598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee    Strong = true; // Use the same heuristic as strong to determine SSPLayout
228ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
229e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    Strong = true;
230de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  else if (HasPrologue)
231de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    NeedsProtector = true;
232ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  else if (!F->hasFnAttribute(Attribute::StackProtect))
233c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling    return false;
234c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling
235ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  for (const BasicBlock &BB : *F) {
236ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    for (const Instruction &I : BB) {
237ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
238e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling        if (AI->isArrayAllocation()) {
239e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling          // SSP-Strong: Enable protectors for any call to alloca, regardless
240e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling          // of size.
241e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling          if (Strong)
242e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling            return true;
243c02dbeb429f3a11f396c3915b638a9a525c97c62Michael Gottesman
244ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines          if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
2454598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee            if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
246e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling              // A call to alloca with size >= SSPBufferSize requires
247e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling              // stack protectors.
2484598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee              Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
2494598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee              NeedsProtector = true;
2504598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee            } else if (Strong) {
2514598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee              // Require protectors for all alloca calls in strong mode.
2524598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee              Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
2534598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee              NeedsProtector = true;
2544598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee            }
2550dcba2fadb990ba2298ba43d76372c754b240ceeBill Wendling          } else {
2560dcba2fadb990ba2298ba43d76372c754b240ceeBill Wendling            // A call to alloca with a variable size requires protectors.
2574598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee            Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
2584598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee            NeedsProtector = true;
2590dcba2fadb990ba2298ba43d76372c754b240ceeBill Wendling          }
2604598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee          continue;
261e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling        }
262e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling
2634598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee        bool IsLarge = false;
2644598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee        if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
2654598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee          Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
2664598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee                                                   : SSPLK_SmallArray));
2674598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee          NeedsProtector = true;
2684598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee          continue;
2694598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee        }
270c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling
271e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling        if (Strong && HasAddressTaken(AI)) {
272c02dbeb429f3a11f396c3915b638a9a525c97c62Michael Gottesman          ++NumAddrTaken;
2734598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee          Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
2744598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee          NeedsProtector = true;
275e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling        }
276c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling      }
277e4957fb9b77a4fbdf711b9e5a722d107d86ccc50Bill Wendling    }
278c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling  }
279c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling
2804598b40ce62dceb5ff96bbb7caeebd1ca57ae3feJosh Magee  return NeedsProtector;
281c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling}
282c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling
283de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar/// Create a stack guard loading and populate whether SelectionDAG SSP is
284de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar/// supported.
285de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainarstatic Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
286de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                            IRBuilder<> &B,
287de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                            bool *SupportsSelectionDAGSP = nullptr) {
288de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (Value *Guard = TLI->getIRStackGuard(B))
289de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    return B.CreateLoad(Guard, true, "StackGuard");
290de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
291de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // Use SelectionDAG SSP handling, since there isn't an IR guard.
292de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  //
293de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // This is more or less weird, since we optionally output whether we
294de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // should perform a SelectionDAG SP here. The reason is that it's strictly
295de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
296de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // mutating. There is no way to get this bit without mutating the IR, so
297de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // getting this bit has to happen in this right time.
298de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  //
299de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // We could have define a new function TLI::supportsSelectionDAGSP(), but that
300de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // will put more burden on the backends' overriding work, especially when it
301de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // actually conveys the same information getIRStackGuard() already gives.
302de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (SupportsSelectionDAGSP)
303de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    *SupportsSelectionDAGSP = true;
304de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  TLI->insertSSPDeclarations(*M);
305de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
3063480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman}
3073480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman
308de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar/// Insert code into the entry block that stores the stack guard
309c03d5ec32041892734324f4dc635e7644aebd672Michael Gottesman/// variable onto the stack:
310c03d5ec32041892734324f4dc635e7644aebd672Michael Gottesman///
311c03d5ec32041892734324f4dc635e7644aebd672Michael Gottesman///   entry:
312c03d5ec32041892734324f4dc635e7644aebd672Michael Gottesman///     StackGuardSlot = alloca i8*
313de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar///     StackGuard = <stack guard>
314de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
315c03d5ec32041892734324f4dc635e7644aebd672Michael Gottesman///
3163480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
3173480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman/// node.
3183480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesmanstatic bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
319de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                           const TargetLoweringBase *TLI, AllocaInst *&AI) {
3203480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman  bool SupportsSelectionDAGSP = false;
32154cf1413aca342753ab846d915c6a55d9c087bc6Benjamin Kramer  IRBuilder<> B(&F->getEntryBlock().front());
322de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
323dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
3243480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman
325de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
326de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
327de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar               {GuardSlot, AI});
3283480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman  return SupportsSelectionDAGSP;
329c03d5ec32041892734324f4dc635e7644aebd672Michael Gottesman}
330c03d5ec32041892734324f4dc635e7644aebd672Michael Gottesman
331613f77439eb6e1f660e615e0e851187da13255aeBill Wendling/// InsertStackProtectors - Insert code into the prologue and epilogue of the
332613f77439eb6e1f660e615e0e851187da13255aeBill Wendling/// function.
333613f77439eb6e1f660e615e0e851187da13255aeBill Wendling///
334613f77439eb6e1f660e615e0e851187da13255aeBill Wendling///  - The prologue code loads and stores the stack guard onto the stack.
335613f77439eb6e1f660e615e0e851187da13255aeBill Wendling///  - The epilogue checks the value stored in the prologue against the original
336613f77439eb6e1f660e615e0e851187da13255aeBill Wendling///    value. It calls __stack_chk_fail if they differ.
337613f77439eb6e1f660e615e0e851187da13255aeBill Wendlingbool StackProtector::InsertStackProtectors() {
338d4f478899e6229648f94c4aa70256986cdc6ee18Michael Gottesman  bool SupportsSelectionDAGSP =
33962406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee      EnableSelectionDAGSP && !TM->Options.EnableFastISel;
340dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
341b7c6ebcb4732302310cfaca81e1d26c3802c1646Bill Wendling
34262406fdc6f199e4e7df60830be45de4da97b34c7Josh Magee  for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
343f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    BasicBlock *BB = &*I++;
344c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling    ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
345ade3075030ddd6db370649993a6da5e21e73daabMichael Gottesman    if (!RI)
346ade3075030ddd6db370649993a6da5e21e73daabMichael Gottesman      continue;
347c3348a77f7e1bdc8e52a9f70fd190555df34d7c1Bill Wendling
348de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // Generate prologue instrumentation if not already generated.
349236e389be4bb7f65e78bd378143b67f401f05338Michael Gottesman    if (!HasPrologue) {
350236e389be4bb7f65e78bd378143b67f401f05338Michael Gottesman      HasPrologue = true;
351de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
352c02dbeb429f3a11f396c3915b638a9a525c97c62Michael Gottesman    }
3533480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman
354de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // SelectionDAG based code generation. Nothing else needs to be done here.
355de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // The epilogue instrumentation is postponed to SelectionDAG.
356de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    if (SupportsSelectionDAGSP)
357de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      break;
358de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
359de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // Set HasIRCheck to true, so that SelectionDAG will not generate its own
360de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
361de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // instrumentation has already been generated.
362de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    HasIRCheck = true;
363de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
364de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // Generate epilogue instrumentation. The epilogue intrumentation can be
365de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // function-based or inlined depending on which mechanism the target is
366de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // providing.
367de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
368de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      // Generate the function-based epilogue instrumentation.
369de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      // The target provides a guard check function, generate a call to it.
370de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      IRBuilder<> B(RI);
371de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
372de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      CallInst *Call = B.CreateCall(GuardCheck, {Guard});
373de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      llvm::Function *Function = cast<llvm::Function>(GuardCheck);
374de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      Call->setAttributes(Function->getAttributes());
375de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      Call->setCallingConv(Function->getCallingConv());
3763480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman    } else {
377de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      // Generate the epilogue with inline instrumentation.
37847d6e07a9be631c582d47d8187a9073619d1c158Michael Gottesman      // If we do not support SelectionDAG based tail calls, generate IR level
37947d6e07a9be631c582d47d8187a9073619d1c158Michael Gottesman      // tail calls.
38047d6e07a9be631c582d47d8187a9073619d1c158Michael Gottesman      //
3813480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      // For each block with a return instruction, convert this:
3823480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //
3833480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //   return:
3843480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //     ...
3853480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //     ret ...
3863480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //
3873480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      // into this:
3883480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //
3893480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //   return:
3903480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //     ...
391de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      //     %1 = <stack guard>
3923480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //     %2 = load StackGuardSlot
3933480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //     %3 = cmp i1 %1, %2
3943480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
3953480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //
3963480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //   SP_return:
3973480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //     ret ...
3983480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //
3993480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //   CallStackCheckFailBlk:
4003480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //     call void @__stack_chk_fail()
4013480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      //     unreachable
4023480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman
4033480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      // Create the FailBB. We duplicate the BB every time since the MI tail
4043480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      // merge pass will merge together all of the various BB into one including
405c02dbeb429f3a11f396c3915b638a9a525c97c62Michael Gottesman      // fail BB generated by the stack protector pseudo instruction.
4063480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      BasicBlock *FailBB = CreateFailBB();
407c02dbeb429f3a11f396c3915b638a9a525c97c62Michael Gottesman
4083480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      // Split the basic block before the return instruction.
409f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
410c02dbeb429f3a11f396c3915b638a9a525c97c62Michael Gottesman
4113480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      // Update the dominator tree if we need to.
4123480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      if (DT && DT->isReachableFromEntry(BB)) {
4133480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman        DT->addNewBlock(NewBB, BB);
4143480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman        DT->addNewBlock(FailBB, BB);
4153480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      }
416c02dbeb429f3a11f396c3915b638a9a525c97c62Michael Gottesman
4173480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      // Remove default branch instruction to the new BB.
4183480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      BB->getTerminator()->eraseFromParent();
419c02dbeb429f3a11f396c3915b638a9a525c97c62Michael Gottesman
4203480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      // Move the newly created basic block to the point right after the old
4213480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      // basic block so that it's in the "fall through" position.
4223480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      NewBB->moveAfter(BB);
423c02dbeb429f3a11f396c3915b638a9a525c97c62Michael Gottesman
4243480d1b84e0bdea91c08dcd931fe86b562971f3dMichael Gottesman      // Generate the stack protector instructions in the old basic block.
42554cf1413aca342753ab846d915c6a55d9c087bc6Benjamin Kramer      IRBuilder<> B(BB);
426de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      Value *Guard = getStackGuard(TLI, M, B);
427de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      LoadInst *LI2 = B.CreateLoad(AI, true);
428de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      Value *Cmp = B.CreateICmpEQ(Guard, LI2);
429de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      auto SuccessProb =
430de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          BranchProbabilityInfo::getBranchProbStackProtector(true);
431de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      auto FailureProb =
432de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          BranchProbabilityInfo::getBranchProbStackProtector(false);
433ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      MDNode *Weights = MDBuilder(F->getContext())
434de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                            .createBranchWeights(SuccessProb.getNumerator(),
435de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                                                 FailureProb.getNumerator());
436ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
43780f6a507d4e11ba066ad0e53e12ad25ad8cf07baCameron Zwarich    }
4382b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling  }
439613f77439eb6e1f660e615e0e851187da13255aeBill Wendling
440ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  // Return if we didn't modify any basic blocks. i.e., there are no return
4411fb615f820ee0ff415e78b25ef583a430c86a743Bill Wendling  // statements in the function.
442f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  return HasPrologue;
4432b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling}
4442b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling
4452b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling/// CreateFailBB - Create a basic block to jump to when the stack protector
4462b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling/// check fails.
447613f77439eb6e1f660e615e0e851187da13255aeBill WendlingBasicBlock *StackProtector::CreateFailBB() {
44862ed8d3e35d25853e32db946a0a60da0bbf862e1Rafael Espindola  LLVMContext &Context = F->getContext();
44962ed8d3e35d25853e32db946a0a60da0bbf862e1Rafael Espindola  BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
45054cf1413aca342753ab846d915c6a55d9c087bc6Benjamin Kramer  IRBuilder<> B(FailBB);
451de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
452ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (Trip.isOSOpenBSD()) {
453ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    Constant *StackChkFail =
454ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        M->getOrInsertFunction("__stack_smash_handler",
455ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines                               Type::getVoidTy(Context),
456ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines                               Type::getInt8PtrTy(Context), nullptr);
45762ed8d3e35d25853e32db946a0a60da0bbf862e1Rafael Espindola
45854cf1413aca342753ab846d915c6a55d9c087bc6Benjamin Kramer    B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
45962ed8d3e35d25853e32db946a0a60da0bbf862e1Rafael Espindola  } else {
460ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    Constant *StackChkFail =
461ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context),
462ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines                               nullptr);
4636948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    B.CreateCall(StackChkFail, {});
46462ed8d3e35d25853e32db946a0a60da0bbf862e1Rafael Espindola  }
46554cf1413aca342753ab846d915c6a55d9c087bc6Benjamin Kramer  B.CreateUnreachable();
466613f77439eb6e1f660e615e0e851187da13255aeBill Wendling  return FailBB;
4672b58ce5ab4e22e796303d68fb246d4031cb5d4caBill Wendling}
468de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
469de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainarbool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
470de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
471de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar}
472