17a7e6055SDimitry Andric //===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This pass inserts stack protectors into functions which need them. A variable
11f22ef01cSRoman Divacky // with a random value in it is stored onto the stack before the local variables
12f22ef01cSRoman Divacky // are allocated. Upon exiting the block, the stored value is checked. If it's
13f22ef01cSRoman Divacky // changed, then there was some sort of violation and the program aborts.
14f22ef01cSRoman Divacky //
15f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
16f22ef01cSRoman Divacky 
17139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
18139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
1939d628a0SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
203ca95b02SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
217a7e6055SDimitry Andric #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
2291bc56edSDimitry Andric #include "llvm/CodeGen/Passes.h"
237a7e6055SDimitry Andric #include "llvm/CodeGen/StackProtector.h"
24139f7f9bSDimitry Andric #include "llvm/IR/Attributes.h"
257a7e6055SDimitry Andric #include "llvm/IR/BasicBlock.h"
26139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
27139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
283ca95b02SDimitry Andric #include "llvm/IR/DebugInfo.h"
297a7e6055SDimitry Andric #include "llvm/IR/DebugLoc.h"
30139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
31139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
32f785676fSDimitry Andric #include "llvm/IR/IRBuilder.h"
337a7e6055SDimitry Andric #include "llvm/IR/Instruction.h"
34139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
35139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
3639d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h"
37139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
387a7e6055SDimitry Andric #include "llvm/IR/Type.h"
397a7e6055SDimitry Andric #include "llvm/IR/User.h"
407a7e6055SDimitry Andric #include "llvm/Pass.h"
417a7e6055SDimitry Andric #include "llvm/Support/Casting.h"
42f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
437a7e6055SDimitry Andric #include "llvm/Target/TargetLowering.h"
447a7e6055SDimitry Andric #include "llvm/Target/TargetMachine.h"
457a7e6055SDimitry Andric #include "llvm/Target/TargetOptions.h"
4639d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
477a7e6055SDimitry Andric #include <utility>
487a7e6055SDimitry Andric 
49f22ef01cSRoman Divacky using namespace llvm;
50f22ef01cSRoman Divacky 
5191bc56edSDimitry Andric #define DEBUG_TYPE "stack-protector"
5291bc56edSDimitry Andric 
53139f7f9bSDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected");
54139f7f9bSDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address"
55139f7f9bSDimitry Andric                         " taken.");
56139f7f9bSDimitry Andric 
57f785676fSDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
58f785676fSDimitry Andric                                           cl::init(true), cl::Hidden);
59f22ef01cSRoman Divacky 
60f22ef01cSRoman Divacky char StackProtector::ID = 0;
61d88c1a5aSDimitry Andric INITIALIZE_TM_PASS(StackProtector, "stack-protector", "Insert stack protectors",
62f785676fSDimitry Andric                    false, true)
63f22ef01cSRoman Divacky 
64f785676fSDimitry Andric FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
65f785676fSDimitry Andric   return new StackProtector(TM);
66f785676fSDimitry Andric }
67f785676fSDimitry Andric 
68f785676fSDimitry Andric StackProtector::SSPLayoutKind
69f785676fSDimitry Andric StackProtector::getSSPLayout(const AllocaInst *AI) const {
70f785676fSDimitry Andric   return AI ? Layout.lookup(AI) : SSPLK_None;
71f22ef01cSRoman Divacky }
72f22ef01cSRoman Divacky 
7391bc56edSDimitry Andric void StackProtector::adjustForColoring(const AllocaInst *From,
7491bc56edSDimitry Andric                                        const AllocaInst *To) {
7591bc56edSDimitry Andric   // When coloring replaces one alloca with another, transfer the SSPLayoutKind
7691bc56edSDimitry Andric   // tag from the remapped to the target alloca. The remapped alloca should
7791bc56edSDimitry Andric   // have a size smaller than or equal to the replacement alloca.
7891bc56edSDimitry Andric   SSPLayoutMap::iterator I = Layout.find(From);
7991bc56edSDimitry Andric   if (I != Layout.end()) {
8091bc56edSDimitry Andric     SSPLayoutKind Kind = I->second;
8191bc56edSDimitry Andric     Layout.erase(I);
8291bc56edSDimitry Andric 
8391bc56edSDimitry Andric     // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
8491bc56edSDimitry Andric     // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
8591bc56edSDimitry Andric     // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
8691bc56edSDimitry Andric     I = Layout.find(To);
8791bc56edSDimitry Andric     if (I == Layout.end())
8891bc56edSDimitry Andric       Layout.insert(std::make_pair(To, Kind));
8991bc56edSDimitry Andric     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
9091bc56edSDimitry Andric       I->second = Kind;
9191bc56edSDimitry Andric   }
9291bc56edSDimitry Andric }
9391bc56edSDimitry Andric 
94f22ef01cSRoman Divacky bool StackProtector::runOnFunction(Function &Fn) {
95f22ef01cSRoman Divacky   F = &Fn;
96f22ef01cSRoman Divacky   M = F->getParent();
9791bc56edSDimitry Andric   DominatorTreeWrapperPass *DTWP =
9891bc56edSDimitry Andric       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
9991bc56edSDimitry Andric   DT = DTWP ? &DTWP->getDomTree() : nullptr;
100ff0cc061SDimitry Andric   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
1013ca95b02SDimitry Andric   HasPrologue = false;
1023ca95b02SDimitry Andric   HasIRCheck = false;
103f22ef01cSRoman Divacky 
104ff0cc061SDimitry Andric   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
10591bc56edSDimitry Andric   if (Attr.isStringAttribute() &&
10691bc56edSDimitry Andric       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
10791bc56edSDimitry Andric     return false; // Invalid integer string
10891bc56edSDimitry Andric 
10991bc56edSDimitry Andric   if (!RequiresStackProtector())
11091bc56edSDimitry Andric     return false;
111f22ef01cSRoman Divacky 
1123ca95b02SDimitry Andric   // TODO(etienneb): Functions with funclets are not correctly supported now.
1133ca95b02SDimitry Andric   // Do nothing if this is funclet-based personality.
1143ca95b02SDimitry Andric   if (Fn.hasPersonalityFn()) {
1153ca95b02SDimitry Andric     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
1163ca95b02SDimitry Andric     if (isFuncletEHPersonality(Personality))
1173ca95b02SDimitry Andric       return false;
1183ca95b02SDimitry Andric   }
1193ca95b02SDimitry Andric 
120139f7f9bSDimitry Andric   ++NumFunProtected;
121f22ef01cSRoman Divacky   return InsertStackProtectors();
122f22ef01cSRoman Divacky }
123f22ef01cSRoman Divacky 
124f785676fSDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and
125f785676fSDimitry Andric /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
126f785676fSDimitry Andric /// multiple arrays, this gets set if any of them is large.
127f785676fSDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
128f785676fSDimitry Andric                                               bool Strong,
129139f7f9bSDimitry Andric                                               bool InStruct) const {
130f785676fSDimitry Andric   if (!Ty)
131f785676fSDimitry Andric     return false;
1323861d79fSDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1333861d79fSDimitry Andric     if (!AT->getElementType()->isIntegerTy(8)) {
1343861d79fSDimitry Andric       // If we're on a non-Darwin platform or we're inside of a structure, don't
1353861d79fSDimitry Andric       // add stack protectors unless the array is a character array.
136f785676fSDimitry Andric       // However, in strong mode any array, regardless of type and size,
137f785676fSDimitry Andric       // triggers a protector.
138f785676fSDimitry Andric       if (!Strong && (InStruct || !Trip.isOSDarwin()))
1393861d79fSDimitry Andric         return false;
1403861d79fSDimitry Andric     }
1413861d79fSDimitry Andric 
1423861d79fSDimitry Andric     // If an array has more than SSPBufferSize bytes of allocated space, then we
1433861d79fSDimitry Andric     // emit stack protectors.
144875ed548SDimitry Andric     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
145f785676fSDimitry Andric       IsLarge = true;
146f785676fSDimitry Andric       return true;
147f785676fSDimitry Andric     }
148f785676fSDimitry Andric 
149f785676fSDimitry Andric     if (Strong)
150f785676fSDimitry Andric       // Require a protector for all arrays in strong mode
1513861d79fSDimitry Andric       return true;
1523861d79fSDimitry Andric   }
1533861d79fSDimitry Andric 
1543861d79fSDimitry Andric   const StructType *ST = dyn_cast<StructType>(Ty);
155f785676fSDimitry Andric   if (!ST)
1563861d79fSDimitry Andric     return false;
157f785676fSDimitry Andric 
158f785676fSDimitry Andric   bool NeedsProtector = false;
159f785676fSDimitry Andric   for (StructType::element_iterator I = ST->element_begin(),
160f785676fSDimitry Andric                                     E = ST->element_end();
161f785676fSDimitry Andric        I != E; ++I)
162f785676fSDimitry Andric     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
163f785676fSDimitry Andric       // If the element is a protectable array and is large (>= SSPBufferSize)
164f785676fSDimitry Andric       // then we are done.  If the protectable array is not large, then
165f785676fSDimitry Andric       // keep looking in case a subsequent element is a large array.
166f785676fSDimitry Andric       if (IsLarge)
167f785676fSDimitry Andric         return true;
168f785676fSDimitry Andric       NeedsProtector = true;
169f785676fSDimitry Andric     }
170f785676fSDimitry Andric 
171f785676fSDimitry Andric   return NeedsProtector;
1723861d79fSDimitry Andric }
1733861d79fSDimitry Andric 
174139f7f9bSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI) {
17591bc56edSDimitry Andric   for (const User *U : AI->users()) {
176139f7f9bSDimitry Andric     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
177139f7f9bSDimitry Andric       if (AI == SI->getValueOperand())
178f22ef01cSRoman Divacky         return true;
179139f7f9bSDimitry Andric     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
180139f7f9bSDimitry Andric       if (AI == SI->getOperand(0))
181139f7f9bSDimitry Andric         return true;
182139f7f9bSDimitry Andric     } else if (isa<CallInst>(U)) {
183139f7f9bSDimitry Andric       return true;
184139f7f9bSDimitry Andric     } else if (isa<InvokeInst>(U)) {
185139f7f9bSDimitry Andric       return true;
186139f7f9bSDimitry Andric     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
187139f7f9bSDimitry Andric       if (HasAddressTaken(SI))
188139f7f9bSDimitry Andric         return true;
189139f7f9bSDimitry Andric     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
190139f7f9bSDimitry Andric       // Keep track of what PHI nodes we have already visited to ensure
191139f7f9bSDimitry Andric       // they are only visited once.
19239d628a0SDimitry Andric       if (VisitedPHIs.insert(PN).second)
193139f7f9bSDimitry Andric         if (HasAddressTaken(PN))
194139f7f9bSDimitry Andric           return true;
195139f7f9bSDimitry Andric     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
196139f7f9bSDimitry Andric       if (HasAddressTaken(GEP))
197139f7f9bSDimitry Andric         return true;
198139f7f9bSDimitry Andric     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
199139f7f9bSDimitry Andric       if (HasAddressTaken(BI))
200139f7f9bSDimitry Andric         return true;
201139f7f9bSDimitry Andric     }
202139f7f9bSDimitry Andric   }
203139f7f9bSDimitry Andric   return false;
204139f7f9bSDimitry Andric }
205f22ef01cSRoman Divacky 
206139f7f9bSDimitry Andric /// \brief Check whether or not this function needs a stack protector based
207139f7f9bSDimitry Andric /// upon the stack protector level.
208139f7f9bSDimitry Andric ///
209139f7f9bSDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong).
210139f7f9bSDimitry Andric /// The standard heuristic which will add a guard variable to functions that
211139f7f9bSDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize,
212139f7f9bSDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions
213139f7f9bSDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The
214139f7f9bSDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca
215139f7f9bSDimitry Andric /// regardless of size, functions with any buffer regardless of type and size,
216139f7f9bSDimitry Andric /// functions with aggregates that contain any buffer regardless of type and
217139f7f9bSDimitry Andric /// size, and functions that contain stack-based variables that have had their
218139f7f9bSDimitry Andric /// address taken.
219139f7f9bSDimitry Andric bool StackProtector::RequiresStackProtector() {
220139f7f9bSDimitry Andric   bool Strong = false;
221f785676fSDimitry Andric   bool NeedsProtector = false;
2223ca95b02SDimitry Andric   for (const BasicBlock &BB : *F)
2233ca95b02SDimitry Andric     for (const Instruction &I : BB)
2243ca95b02SDimitry Andric       if (const CallInst *CI = dyn_cast<CallInst>(&I))
2253ca95b02SDimitry Andric         if (CI->getCalledFunction() ==
2263ca95b02SDimitry Andric             Intrinsic::getDeclaration(F->getParent(),
2273ca95b02SDimitry Andric                                       Intrinsic::stackprotector))
2283ca95b02SDimitry Andric           HasPrologue = true;
2293ca95b02SDimitry Andric 
2303ca95b02SDimitry Andric   if (F->hasFnAttribute(Attribute::SafeStack))
2313ca95b02SDimitry Andric     return false;
2323ca95b02SDimitry Andric 
2337a7e6055SDimitry Andric   // We are constructing the OptimizationRemarkEmitter on the fly rather than
2347a7e6055SDimitry Andric   // using the analysis pass to avoid building DominatorTree and LoopInfo which
2357a7e6055SDimitry Andric   // are not available this late in the IR pipeline.
2367a7e6055SDimitry Andric   OptimizationRemarkEmitter ORE(F);
2377a7e6055SDimitry Andric 
238ff0cc061SDimitry Andric   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
2397a7e6055SDimitry Andric     ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
2407a7e6055SDimitry Andric              << "Stack protection applied to function "
2417a7e6055SDimitry Andric              << ore::NV("Function", F)
2427a7e6055SDimitry Andric              << " due to a function attribute or command-line switch");
243f785676fSDimitry Andric     NeedsProtector = true;
244f785676fSDimitry Andric     Strong = true; // Use the same heuristic as strong to determine SSPLayout
245ff0cc061SDimitry Andric   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
246139f7f9bSDimitry Andric     Strong = true;
2473ca95b02SDimitry Andric   else if (HasPrologue)
2483ca95b02SDimitry Andric     NeedsProtector = true;
249ff0cc061SDimitry Andric   else if (!F->hasFnAttribute(Attribute::StackProtect))
250f22ef01cSRoman Divacky     return false;
251f22ef01cSRoman Divacky 
25239d628a0SDimitry Andric   for (const BasicBlock &BB : *F) {
25339d628a0SDimitry Andric     for (const Instruction &I : BB) {
25439d628a0SDimitry Andric       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
255139f7f9bSDimitry Andric         if (AI->isArrayAllocation()) {
2567a7e6055SDimitry Andric           OptimizationRemark Remark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
2577a7e6055SDimitry Andric                                     &I);
2587a7e6055SDimitry Andric           Remark
2597a7e6055SDimitry Andric               << "Stack protection applied to function "
2607a7e6055SDimitry Andric               << ore::NV("Function", F)
2617a7e6055SDimitry Andric               << " due to a call to alloca or use of a variable length array";
26239d628a0SDimitry Andric           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
263f785676fSDimitry Andric             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
264139f7f9bSDimitry Andric               // A call to alloca with size >= SSPBufferSize requires
265139f7f9bSDimitry Andric               // stack protectors.
266f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
2677a7e6055SDimitry Andric               ORE.emit(Remark);
268f785676fSDimitry Andric               NeedsProtector = true;
269f785676fSDimitry Andric             } else if (Strong) {
270f785676fSDimitry Andric               // Require protectors for all alloca calls in strong mode.
271f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
2727a7e6055SDimitry Andric               ORE.emit(Remark);
273f785676fSDimitry Andric               NeedsProtector = true;
274f785676fSDimitry Andric             }
275f785676fSDimitry Andric           } else {
276f785676fSDimitry Andric             // A call to alloca with a variable size requires protectors.
277f785676fSDimitry Andric             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
2787a7e6055SDimitry Andric             ORE.emit(Remark);
279f785676fSDimitry Andric             NeedsProtector = true;
280f785676fSDimitry Andric           }
281f785676fSDimitry Andric           continue;
282139f7f9bSDimitry Andric         }
283139f7f9bSDimitry Andric 
284f785676fSDimitry Andric         bool IsLarge = false;
285f785676fSDimitry Andric         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
286f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
287f785676fSDimitry Andric                                                    : SSPLK_SmallArray));
2887a7e6055SDimitry Andric           ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
2897a7e6055SDimitry Andric                    << "Stack protection applied to function "
2907a7e6055SDimitry Andric                    << ore::NV("Function", F)
2917a7e6055SDimitry Andric                    << " due to a stack allocated buffer or struct containing a "
2927a7e6055SDimitry Andric                       "buffer");
293f785676fSDimitry Andric           NeedsProtector = true;
294f785676fSDimitry Andric           continue;
295f785676fSDimitry Andric         }
296139f7f9bSDimitry Andric 
297139f7f9bSDimitry Andric         if (Strong && HasAddressTaken(AI)) {
298139f7f9bSDimitry Andric           ++NumAddrTaken;
299f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
3007a7e6055SDimitry Andric           ORE.emit(
3017a7e6055SDimitry Andric               OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", &I)
3027a7e6055SDimitry Andric               << "Stack protection applied to function "
3037a7e6055SDimitry Andric               << ore::NV("Function", F)
3047a7e6055SDimitry Andric               << " due to the address of a local variable being taken");
305f785676fSDimitry Andric           NeedsProtector = true;
306139f7f9bSDimitry Andric         }
307139f7f9bSDimitry Andric       }
308f22ef01cSRoman Divacky     }
309f22ef01cSRoman Divacky   }
310f22ef01cSRoman Divacky 
311f785676fSDimitry Andric   return NeedsProtector;
312f785676fSDimitry Andric }
313f785676fSDimitry Andric 
3143ca95b02SDimitry Andric /// Create a stack guard loading and populate whether SelectionDAG SSP is
3153ca95b02SDimitry Andric /// supported.
3163ca95b02SDimitry Andric static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
3173ca95b02SDimitry Andric                             IRBuilder<> &B,
3183ca95b02SDimitry Andric                             bool *SupportsSelectionDAGSP = nullptr) {
3193ca95b02SDimitry Andric   if (Value *Guard = TLI->getIRStackGuard(B))
3203ca95b02SDimitry Andric     return B.CreateLoad(Guard, true, "StackGuard");
321f785676fSDimitry Andric 
3223ca95b02SDimitry Andric   // Use SelectionDAG SSP handling, since there isn't an IR guard.
323f785676fSDimitry Andric   //
3243ca95b02SDimitry Andric   // This is more or less weird, since we optionally output whether we
3253ca95b02SDimitry Andric   // should perform a SelectionDAG SP here. The reason is that it's strictly
3263ca95b02SDimitry Andric   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
3273ca95b02SDimitry Andric   // mutating. There is no way to get this bit without mutating the IR, so
3283ca95b02SDimitry Andric   // getting this bit has to happen in this right time.
329f785676fSDimitry Andric   //
3303ca95b02SDimitry Andric   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
3313ca95b02SDimitry Andric   // will put more burden on the backends' overriding work, especially when it
3323ca95b02SDimitry Andric   // actually conveys the same information getIRStackGuard() already gives.
3333ca95b02SDimitry Andric   if (SupportsSelectionDAGSP)
3343ca95b02SDimitry Andric     *SupportsSelectionDAGSP = true;
3353ca95b02SDimitry Andric   TLI->insertSSPDeclarations(*M);
3363ca95b02SDimitry Andric   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
337f785676fSDimitry Andric }
338f785676fSDimitry Andric 
3393ca95b02SDimitry Andric /// Insert code into the entry block that stores the stack guard
340f785676fSDimitry Andric /// variable onto the stack:
341f785676fSDimitry Andric ///
342f785676fSDimitry Andric ///   entry:
343f785676fSDimitry Andric ///     StackGuardSlot = alloca i8*
3443ca95b02SDimitry Andric ///     StackGuard = <stack guard>
3453ca95b02SDimitry Andric ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
346f785676fSDimitry Andric ///
347f785676fSDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
348f785676fSDimitry Andric /// node.
349f785676fSDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
3503ca95b02SDimitry Andric                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
351f785676fSDimitry Andric   bool SupportsSelectionDAGSP = false;
352f785676fSDimitry Andric   IRBuilder<> B(&F->getEntryBlock().front());
3533ca95b02SDimitry Andric   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
35491bc56edSDimitry Andric   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
355f785676fSDimitry Andric 
3563ca95b02SDimitry Andric   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
3573ca95b02SDimitry Andric   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
3583ca95b02SDimitry Andric                {GuardSlot, AI});
359f785676fSDimitry Andric   return SupportsSelectionDAGSP;
360f22ef01cSRoman Divacky }
361f22ef01cSRoman Divacky 
362f22ef01cSRoman Divacky /// InsertStackProtectors - Insert code into the prologue and epilogue of the
363f22ef01cSRoman Divacky /// function.
364f22ef01cSRoman Divacky ///
365f22ef01cSRoman Divacky ///  - The prologue code loads and stores the stack guard onto the stack.
366f22ef01cSRoman Divacky ///  - The epilogue checks the value stored in the prologue against the original
367f22ef01cSRoman Divacky ///    value. It calls __stack_chk_fail if they differ.
368f22ef01cSRoman Divacky bool StackProtector::InsertStackProtectors() {
369f785676fSDimitry Andric   bool SupportsSelectionDAGSP =
370f785676fSDimitry Andric       EnableSelectionDAGSP && !TM->Options.EnableFastISel;
37191bc56edSDimitry Andric   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
372f22ef01cSRoman Divacky 
373f22ef01cSRoman Divacky   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
3747d523365SDimitry Andric     BasicBlock *BB = &*I++;
375f22ef01cSRoman Divacky     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
376f785676fSDimitry Andric     if (!RI)
377f785676fSDimitry Andric       continue;
378f22ef01cSRoman Divacky 
3793ca95b02SDimitry Andric     // Generate prologue instrumentation if not already generated.
380f785676fSDimitry Andric     if (!HasPrologue) {
381f785676fSDimitry Andric       HasPrologue = true;
3823ca95b02SDimitry Andric       SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
383f785676fSDimitry Andric     }
384ffd1746dSEd Schouten 
3853ca95b02SDimitry Andric     // SelectionDAG based code generation. Nothing else needs to be done here.
3863ca95b02SDimitry Andric     // The epilogue instrumentation is postponed to SelectionDAG.
3873ca95b02SDimitry Andric     if (SupportsSelectionDAGSP)
3883ca95b02SDimitry Andric       break;
389f22ef01cSRoman Divacky 
3903ca95b02SDimitry Andric     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
3913ca95b02SDimitry Andric     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
3923ca95b02SDimitry Andric     // instrumentation has already been generated.
3933ca95b02SDimitry Andric     HasIRCheck = true;
3943ca95b02SDimitry Andric 
3953ca95b02SDimitry Andric     // Generate epilogue instrumentation. The epilogue intrumentation can be
3963ca95b02SDimitry Andric     // function-based or inlined depending on which mechanism the target is
3973ca95b02SDimitry Andric     // providing.
3983ca95b02SDimitry Andric     if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
3993ca95b02SDimitry Andric       // Generate the function-based epilogue instrumentation.
4003ca95b02SDimitry Andric       // The target provides a guard check function, generate a call to it.
4013ca95b02SDimitry Andric       IRBuilder<> B(RI);
4023ca95b02SDimitry Andric       LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
4033ca95b02SDimitry Andric       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
4043ca95b02SDimitry Andric       llvm::Function *Function = cast<llvm::Function>(GuardCheck);
4053ca95b02SDimitry Andric       Call->setAttributes(Function->getAttributes());
4063ca95b02SDimitry Andric       Call->setCallingConv(Function->getCallingConv());
407f785676fSDimitry Andric     } else {
4083ca95b02SDimitry Andric       // Generate the epilogue with inline instrumentation.
409f785676fSDimitry Andric       // If we do not support SelectionDAG based tail calls, generate IR level
410f785676fSDimitry Andric       // tail calls.
411f785676fSDimitry Andric       //
412f22ef01cSRoman Divacky       // For each block with a return instruction, convert this:
413f22ef01cSRoman Divacky       //
414f22ef01cSRoman Divacky       //   return:
415f22ef01cSRoman Divacky       //     ...
416f22ef01cSRoman Divacky       //     ret ...
417f22ef01cSRoman Divacky       //
418f22ef01cSRoman Divacky       // into this:
419f22ef01cSRoman Divacky       //
420f22ef01cSRoman Divacky       //   return:
421f22ef01cSRoman Divacky       //     ...
4223ca95b02SDimitry Andric       //     %1 = <stack guard>
423f22ef01cSRoman Divacky       //     %2 = load StackGuardSlot
424f22ef01cSRoman Divacky       //     %3 = cmp i1 %1, %2
425f22ef01cSRoman Divacky       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
426f22ef01cSRoman Divacky       //
427f22ef01cSRoman Divacky       //   SP_return:
428f22ef01cSRoman Divacky       //     ret ...
429f22ef01cSRoman Divacky       //
430f22ef01cSRoman Divacky       //   CallStackCheckFailBlk:
431f22ef01cSRoman Divacky       //     call void @__stack_chk_fail()
432f22ef01cSRoman Divacky       //     unreachable
433f22ef01cSRoman Divacky 
434f785676fSDimitry Andric       // Create the FailBB. We duplicate the BB every time since the MI tail
435f785676fSDimitry Andric       // merge pass will merge together all of the various BB into one including
436f785676fSDimitry Andric       // fail BB generated by the stack protector pseudo instruction.
437f785676fSDimitry Andric       BasicBlock *FailBB = CreateFailBB();
438f785676fSDimitry Andric 
439f22ef01cSRoman Divacky       // Split the basic block before the return instruction.
4407d523365SDimitry Andric       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
4413b0f4066SDimitry Andric 
442f785676fSDimitry Andric       // Update the dominator tree if we need to.
4433b0f4066SDimitry Andric       if (DT && DT->isReachableFromEntry(BB)) {
4443b0f4066SDimitry Andric         DT->addNewBlock(NewBB, BB);
445f785676fSDimitry Andric         DT->addNewBlock(FailBB, BB);
4462754fe60SDimitry Andric       }
447f22ef01cSRoman Divacky 
448f22ef01cSRoman Divacky       // Remove default branch instruction to the new BB.
449f22ef01cSRoman Divacky       BB->getTerminator()->eraseFromParent();
450f22ef01cSRoman Divacky 
451f785676fSDimitry Andric       // Move the newly created basic block to the point right after the old
452f785676fSDimitry Andric       // basic block so that it's in the "fall through" position.
453f22ef01cSRoman Divacky       NewBB->moveAfter(BB);
454f22ef01cSRoman Divacky 
455f22ef01cSRoman Divacky       // Generate the stack protector instructions in the old basic block.
456f785676fSDimitry Andric       IRBuilder<> B(BB);
4573ca95b02SDimitry Andric       Value *Guard = getStackGuard(TLI, M, B);
4583ca95b02SDimitry Andric       LoadInst *LI2 = B.CreateLoad(AI, true);
4593ca95b02SDimitry Andric       Value *Cmp = B.CreateICmpEQ(Guard, LI2);
4607d523365SDimitry Andric       auto SuccessProb =
4617d523365SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(true);
4627d523365SDimitry Andric       auto FailureProb =
4637d523365SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(false);
46439d628a0SDimitry Andric       MDNode *Weights = MDBuilder(F->getContext())
4657d523365SDimitry Andric                             .createBranchWeights(SuccessProb.getNumerator(),
4667d523365SDimitry Andric                                                  FailureProb.getNumerator());
46739d628a0SDimitry Andric       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
468f785676fSDimitry Andric     }
469f22ef01cSRoman Divacky   }
470f22ef01cSRoman Divacky 
47139d628a0SDimitry Andric   // Return if we didn't modify any basic blocks. i.e., there are no return
472f22ef01cSRoman Divacky   // statements in the function.
4737d523365SDimitry Andric   return HasPrologue;
474f22ef01cSRoman Divacky }
475f22ef01cSRoman Divacky 
476f22ef01cSRoman Divacky /// CreateFailBB - Create a basic block to jump to when the stack protector
477f22ef01cSRoman Divacky /// check fails.
478f22ef01cSRoman Divacky BasicBlock *StackProtector::CreateFailBB() {
479f785676fSDimitry Andric   LLVMContext &Context = F->getContext();
480f785676fSDimitry Andric   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
481f785676fSDimitry Andric   IRBuilder<> B(FailBB);
4823ca95b02SDimitry Andric   B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
48339d628a0SDimitry Andric   if (Trip.isOSOpenBSD()) {
48439d628a0SDimitry Andric     Constant *StackChkFail =
48539d628a0SDimitry Andric         M->getOrInsertFunction("__stack_smash_handler",
48639d628a0SDimitry Andric                                Type::getVoidTy(Context),
4877a7e6055SDimitry Andric                                Type::getInt8PtrTy(Context));
488f785676fSDimitry Andric 
489f785676fSDimitry Andric     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
490f785676fSDimitry Andric   } else {
49139d628a0SDimitry Andric     Constant *StackChkFail =
4927a7e6055SDimitry Andric         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
4937a7e6055SDimitry Andric 
494ff0cc061SDimitry Andric     B.CreateCall(StackChkFail, {});
495f785676fSDimitry Andric   }
496f785676fSDimitry Andric   B.CreateUnreachable();
497f22ef01cSRoman Divacky   return FailBB;
498f22ef01cSRoman Divacky }
4993ca95b02SDimitry Andric 
5003ca95b02SDimitry Andric bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
5013ca95b02SDimitry Andric   return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
5023ca95b02SDimitry Andric }
503