1f22ef01cSRoman Divacky //===-- 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 
17f785676fSDimitry Andric #include "llvm/CodeGen/StackProtector.h"
18139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
19139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
2039d628a0SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
21f785676fSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
2291bc56edSDimitry Andric #include "llvm/CodeGen/Analysis.h"
2391bc56edSDimitry Andric #include "llvm/CodeGen/Passes.h"
24139f7f9bSDimitry Andric #include "llvm/IR/Attributes.h"
25139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
26139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
27139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
28139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
29f785676fSDimitry Andric #include "llvm/IR/GlobalValue.h"
30f785676fSDimitry Andric #include "llvm/IR/GlobalVariable.h"
31f785676fSDimitry Andric #include "llvm/IR/IRBuilder.h"
32139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
33f785676fSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
34139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
3539d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h"
36139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
37f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
3839d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
39f785676fSDimitry Andric #include <cstdlib>
40f22ef01cSRoman Divacky using namespace llvm;
41f22ef01cSRoman Divacky 
4291bc56edSDimitry Andric #define DEBUG_TYPE "stack-protector"
4391bc56edSDimitry Andric 
44139f7f9bSDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected");
45139f7f9bSDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address"
46139f7f9bSDimitry Andric                         " taken.");
47139f7f9bSDimitry Andric 
48f785676fSDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
49f785676fSDimitry Andric                                           cl::init(true), cl::Hidden);
50f22ef01cSRoman Divacky 
51f22ef01cSRoman Divacky char StackProtector::ID = 0;
52f785676fSDimitry Andric INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
53f785676fSDimitry Andric                 false, true)
54f22ef01cSRoman Divacky 
55f785676fSDimitry Andric FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
56f785676fSDimitry Andric   return new StackProtector(TM);
57f785676fSDimitry Andric }
58f785676fSDimitry Andric 
59f785676fSDimitry Andric StackProtector::SSPLayoutKind
60f785676fSDimitry Andric StackProtector::getSSPLayout(const AllocaInst *AI) const {
61f785676fSDimitry Andric   return AI ? Layout.lookup(AI) : SSPLK_None;
62f22ef01cSRoman Divacky }
63f22ef01cSRoman Divacky 
6491bc56edSDimitry Andric void StackProtector::adjustForColoring(const AllocaInst *From,
6591bc56edSDimitry Andric                                        const AllocaInst *To) {
6691bc56edSDimitry Andric   // When coloring replaces one alloca with another, transfer the SSPLayoutKind
6791bc56edSDimitry Andric   // tag from the remapped to the target alloca. The remapped alloca should
6891bc56edSDimitry Andric   // have a size smaller than or equal to the replacement alloca.
6991bc56edSDimitry Andric   SSPLayoutMap::iterator I = Layout.find(From);
7091bc56edSDimitry Andric   if (I != Layout.end()) {
7191bc56edSDimitry Andric     SSPLayoutKind Kind = I->second;
7291bc56edSDimitry Andric     Layout.erase(I);
7391bc56edSDimitry Andric 
7491bc56edSDimitry Andric     // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
7591bc56edSDimitry Andric     // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
7691bc56edSDimitry Andric     // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
7791bc56edSDimitry Andric     I = Layout.find(To);
7891bc56edSDimitry Andric     if (I == Layout.end())
7991bc56edSDimitry Andric       Layout.insert(std::make_pair(To, Kind));
8091bc56edSDimitry Andric     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
8191bc56edSDimitry Andric       I->second = Kind;
8291bc56edSDimitry Andric   }
8391bc56edSDimitry Andric }
8491bc56edSDimitry Andric 
85f22ef01cSRoman Divacky bool StackProtector::runOnFunction(Function &Fn) {
86f22ef01cSRoman Divacky   F = &Fn;
87f22ef01cSRoman Divacky   M = F->getParent();
8891bc56edSDimitry Andric   DominatorTreeWrapperPass *DTWP =
8991bc56edSDimitry Andric       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
9091bc56edSDimitry Andric   DT = DTWP ? &DTWP->getDomTree() : nullptr;
91ff0cc061SDimitry Andric   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
92f22ef01cSRoman Divacky 
93ff0cc061SDimitry Andric   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
9491bc56edSDimitry Andric   if (Attr.isStringAttribute() &&
9591bc56edSDimitry Andric       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
9691bc56edSDimitry Andric       return false; // Invalid integer string
9791bc56edSDimitry Andric 
9891bc56edSDimitry Andric   if (!RequiresStackProtector())
9991bc56edSDimitry Andric     return false;
100f22ef01cSRoman Divacky 
101139f7f9bSDimitry Andric   ++NumFunProtected;
102f22ef01cSRoman Divacky   return InsertStackProtectors();
103f22ef01cSRoman Divacky }
104f22ef01cSRoman Divacky 
105f785676fSDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and
106f785676fSDimitry Andric /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
107f785676fSDimitry Andric /// multiple arrays, this gets set if any of them is large.
108f785676fSDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
109f785676fSDimitry Andric                                               bool Strong,
110139f7f9bSDimitry Andric                                               bool InStruct) const {
111f785676fSDimitry Andric   if (!Ty)
112f785676fSDimitry Andric     return false;
1133861d79fSDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1143861d79fSDimitry Andric     if (!AT->getElementType()->isIntegerTy(8)) {
1153861d79fSDimitry Andric       // If we're on a non-Darwin platform or we're inside of a structure, don't
1163861d79fSDimitry Andric       // add stack protectors unless the array is a character array.
117f785676fSDimitry Andric       // However, in strong mode any array, regardless of type and size,
118f785676fSDimitry Andric       // triggers a protector.
119f785676fSDimitry Andric       if (!Strong && (InStruct || !Trip.isOSDarwin()))
1203861d79fSDimitry Andric         return false;
1213861d79fSDimitry Andric     }
1223861d79fSDimitry Andric 
1233861d79fSDimitry Andric     // If an array has more than SSPBufferSize bytes of allocated space, then we
1243861d79fSDimitry Andric     // emit stack protectors.
125875ed548SDimitry Andric     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
126f785676fSDimitry Andric       IsLarge = true;
127f785676fSDimitry Andric       return true;
128f785676fSDimitry Andric     }
129f785676fSDimitry Andric 
130f785676fSDimitry Andric     if (Strong)
131f785676fSDimitry Andric       // Require a protector for all arrays in strong mode
1323861d79fSDimitry Andric       return true;
1333861d79fSDimitry Andric   }
1343861d79fSDimitry Andric 
1353861d79fSDimitry Andric   const StructType *ST = dyn_cast<StructType>(Ty);
136f785676fSDimitry Andric   if (!ST)
1373861d79fSDimitry Andric     return false;
138f785676fSDimitry Andric 
139f785676fSDimitry Andric   bool NeedsProtector = false;
140f785676fSDimitry Andric   for (StructType::element_iterator I = ST->element_begin(),
141f785676fSDimitry Andric                                     E = ST->element_end();
142f785676fSDimitry Andric        I != E; ++I)
143f785676fSDimitry Andric     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
144f785676fSDimitry Andric       // If the element is a protectable array and is large (>= SSPBufferSize)
145f785676fSDimitry Andric       // then we are done.  If the protectable array is not large, then
146f785676fSDimitry Andric       // keep looking in case a subsequent element is a large array.
147f785676fSDimitry Andric       if (IsLarge)
148f785676fSDimitry Andric         return true;
149f785676fSDimitry Andric       NeedsProtector = true;
150f785676fSDimitry Andric     }
151f785676fSDimitry Andric 
152f785676fSDimitry Andric   return NeedsProtector;
1533861d79fSDimitry Andric }
1543861d79fSDimitry Andric 
155139f7f9bSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI) {
15691bc56edSDimitry Andric   for (const User *U : AI->users()) {
157139f7f9bSDimitry Andric     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
158139f7f9bSDimitry Andric       if (AI == SI->getValueOperand())
159f22ef01cSRoman Divacky         return true;
160139f7f9bSDimitry Andric     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
161139f7f9bSDimitry Andric       if (AI == SI->getOperand(0))
162139f7f9bSDimitry Andric         return true;
163139f7f9bSDimitry Andric     } else if (isa<CallInst>(U)) {
164139f7f9bSDimitry Andric       return true;
165139f7f9bSDimitry Andric     } else if (isa<InvokeInst>(U)) {
166139f7f9bSDimitry Andric       return true;
167139f7f9bSDimitry Andric     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
168139f7f9bSDimitry Andric       if (HasAddressTaken(SI))
169139f7f9bSDimitry Andric         return true;
170139f7f9bSDimitry Andric     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
171139f7f9bSDimitry Andric       // Keep track of what PHI nodes we have already visited to ensure
172139f7f9bSDimitry Andric       // they are only visited once.
17339d628a0SDimitry Andric       if (VisitedPHIs.insert(PN).second)
174139f7f9bSDimitry Andric         if (HasAddressTaken(PN))
175139f7f9bSDimitry Andric           return true;
176139f7f9bSDimitry Andric     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
177139f7f9bSDimitry Andric       if (HasAddressTaken(GEP))
178139f7f9bSDimitry Andric         return true;
179139f7f9bSDimitry Andric     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
180139f7f9bSDimitry Andric       if (HasAddressTaken(BI))
181139f7f9bSDimitry Andric         return true;
182139f7f9bSDimitry Andric     }
183139f7f9bSDimitry Andric   }
184139f7f9bSDimitry Andric   return false;
185139f7f9bSDimitry Andric }
186f22ef01cSRoman Divacky 
187139f7f9bSDimitry Andric /// \brief Check whether or not this function needs a stack protector based
188139f7f9bSDimitry Andric /// upon the stack protector level.
189139f7f9bSDimitry Andric ///
190139f7f9bSDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong).
191139f7f9bSDimitry Andric /// The standard heuristic which will add a guard variable to functions that
192139f7f9bSDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize,
193139f7f9bSDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions
194139f7f9bSDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The
195139f7f9bSDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca
196139f7f9bSDimitry Andric /// regardless of size, functions with any buffer regardless of type and size,
197139f7f9bSDimitry Andric /// functions with aggregates that contain any buffer regardless of type and
198139f7f9bSDimitry Andric /// size, and functions that contain stack-based variables that have had their
199139f7f9bSDimitry Andric /// address taken.
200139f7f9bSDimitry Andric bool StackProtector::RequiresStackProtector() {
201139f7f9bSDimitry Andric   bool Strong = false;
202f785676fSDimitry Andric   bool NeedsProtector = false;
203ff0cc061SDimitry Andric   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
204f785676fSDimitry Andric     NeedsProtector = true;
205f785676fSDimitry Andric     Strong = true; // Use the same heuristic as strong to determine SSPLayout
206ff0cc061SDimitry Andric   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
207139f7f9bSDimitry Andric     Strong = true;
208ff0cc061SDimitry Andric   else if (!F->hasFnAttribute(Attribute::StackProtect))
209f22ef01cSRoman Divacky     return false;
210f22ef01cSRoman Divacky 
21139d628a0SDimitry Andric   for (const BasicBlock &BB : *F) {
21239d628a0SDimitry Andric     for (const Instruction &I : BB) {
21339d628a0SDimitry Andric       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
214139f7f9bSDimitry Andric         if (AI->isArrayAllocation()) {
215139f7f9bSDimitry Andric           // SSP-Strong: Enable protectors for any call to alloca, regardless
216139f7f9bSDimitry Andric           // of size.
217139f7f9bSDimitry Andric           if (Strong)
218f22ef01cSRoman Divacky             return true;
219f22ef01cSRoman Divacky 
22039d628a0SDimitry Andric           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
221f785676fSDimitry Andric             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
222139f7f9bSDimitry Andric               // A call to alloca with size >= SSPBufferSize requires
223139f7f9bSDimitry Andric               // stack protectors.
224f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
225f785676fSDimitry Andric               NeedsProtector = true;
226f785676fSDimitry Andric             } else if (Strong) {
227f785676fSDimitry Andric               // Require protectors for all alloca calls in strong mode.
228f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
229f785676fSDimitry Andric               NeedsProtector = true;
230f785676fSDimitry Andric             }
231f785676fSDimitry Andric           } else {
232f785676fSDimitry Andric             // A call to alloca with a variable size requires protectors.
233f785676fSDimitry Andric             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
234f785676fSDimitry Andric             NeedsProtector = true;
235f785676fSDimitry Andric           }
236f785676fSDimitry Andric           continue;
237139f7f9bSDimitry Andric         }
238139f7f9bSDimitry Andric 
239f785676fSDimitry Andric         bool IsLarge = false;
240f785676fSDimitry Andric         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
241f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
242f785676fSDimitry Andric                                                    : SSPLK_SmallArray));
243f785676fSDimitry Andric           NeedsProtector = true;
244f785676fSDimitry Andric           continue;
245f785676fSDimitry Andric         }
246139f7f9bSDimitry Andric 
247139f7f9bSDimitry Andric         if (Strong && HasAddressTaken(AI)) {
248139f7f9bSDimitry Andric           ++NumAddrTaken;
249f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
250f785676fSDimitry Andric           NeedsProtector = true;
251139f7f9bSDimitry Andric         }
252139f7f9bSDimitry Andric       }
253f22ef01cSRoman Divacky     }
254f22ef01cSRoman Divacky   }
255f22ef01cSRoman Divacky 
256f785676fSDimitry Andric   return NeedsProtector;
257f785676fSDimitry Andric }
258f785676fSDimitry Andric 
259f785676fSDimitry Andric static bool InstructionWillNotHaveChain(const Instruction *I) {
260f785676fSDimitry Andric   return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
261f785676fSDimitry Andric          isSafeToSpeculativelyExecute(I);
262f785676fSDimitry Andric }
263f785676fSDimitry Andric 
264f785676fSDimitry Andric /// Identify if RI has a previous instruction in the "Tail Position" and return
265f785676fSDimitry Andric /// it. Otherwise return 0.
266f785676fSDimitry Andric ///
267f785676fSDimitry Andric /// This is based off of the code in llvm::isInTailCallPosition. The difference
268f785676fSDimitry Andric /// is that it inverts the first part of llvm::isInTailCallPosition since
269f785676fSDimitry Andric /// isInTailCallPosition is checking if a call is in a tail call position, and
270f785676fSDimitry Andric /// we are searching for an unknown tail call that might be in the tail call
271f785676fSDimitry Andric /// position. Once we find the call though, the code uses the same refactored
272f785676fSDimitry Andric /// code, returnTypeIsEligibleForTailCall.
273f785676fSDimitry Andric static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
274f785676fSDimitry Andric                                        const TargetLoweringBase *TLI) {
275f785676fSDimitry Andric   // Establish a reasonable upper bound on the maximum amount of instructions we
276f785676fSDimitry Andric   // will look through to find a tail call.
277f785676fSDimitry Andric   unsigned SearchCounter = 0;
278f785676fSDimitry Andric   const unsigned MaxSearch = 4;
279f785676fSDimitry Andric   bool NoInterposingChain = true;
280f785676fSDimitry Andric 
28191bc56edSDimitry Andric   for (BasicBlock::reverse_iterator I = std::next(BB->rbegin()), E = BB->rend();
282f785676fSDimitry Andric        I != E && SearchCounter < MaxSearch; ++I) {
283f785676fSDimitry Andric     Instruction *Inst = &*I;
284f785676fSDimitry Andric 
285f785676fSDimitry Andric     // Skip over debug intrinsics and do not allow them to affect our MaxSearch
286f785676fSDimitry Andric     // counter.
287f785676fSDimitry Andric     if (isa<DbgInfoIntrinsic>(Inst))
288f785676fSDimitry Andric       continue;
289f785676fSDimitry Andric 
290f785676fSDimitry Andric     // If we find a call and the following conditions are satisifed, then we
291f785676fSDimitry Andric     // have found a tail call that satisfies at least the target independent
292f785676fSDimitry Andric     // requirements of a tail call:
293f785676fSDimitry Andric     //
294f785676fSDimitry Andric     // 1. The call site has the tail marker.
295f785676fSDimitry Andric     //
296f785676fSDimitry Andric     // 2. The call site either will not cause the creation of a chain or if a
297f785676fSDimitry Andric     // chain is necessary there are no instructions in between the callsite and
298f785676fSDimitry Andric     // the call which would create an interposing chain.
299f785676fSDimitry Andric     //
300f785676fSDimitry Andric     // 3. The return type of the function does not impede tail call
301f785676fSDimitry Andric     // optimization.
302f785676fSDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
303f785676fSDimitry Andric       if (CI->isTailCall() &&
304f785676fSDimitry Andric           (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
305f785676fSDimitry Andric           returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
306f785676fSDimitry Andric         return CI;
307f785676fSDimitry Andric     }
308f785676fSDimitry Andric 
309f785676fSDimitry Andric     // If we did not find a call see if we have an instruction that may create
310f785676fSDimitry Andric     // an interposing chain.
311f785676fSDimitry Andric     NoInterposingChain =
312f785676fSDimitry Andric         NoInterposingChain && InstructionWillNotHaveChain(Inst);
313f785676fSDimitry Andric 
314f785676fSDimitry Andric     // Increment max search.
315f785676fSDimitry Andric     SearchCounter++;
316f785676fSDimitry Andric   }
317f785676fSDimitry Andric 
31891bc56edSDimitry Andric   return nullptr;
319f785676fSDimitry Andric }
320f785676fSDimitry Andric 
321f785676fSDimitry Andric /// Insert code into the entry block that stores the __stack_chk_guard
322f785676fSDimitry Andric /// variable onto the stack:
323f785676fSDimitry Andric ///
324f785676fSDimitry Andric ///   entry:
325f785676fSDimitry Andric ///     StackGuardSlot = alloca i8*
326f785676fSDimitry Andric ///     StackGuard = load __stack_chk_guard
327f785676fSDimitry Andric ///     call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
328f785676fSDimitry Andric ///
329f785676fSDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
330f785676fSDimitry Andric /// node.
331f785676fSDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
33239d628a0SDimitry Andric                            const TargetLoweringBase *TLI, const Triple &TT,
333f785676fSDimitry Andric                            AllocaInst *&AI, Value *&StackGuardVar) {
334f785676fSDimitry Andric   bool SupportsSelectionDAGSP = false;
335f785676fSDimitry Andric   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
336f785676fSDimitry Andric   unsigned AddressSpace, Offset;
337f785676fSDimitry Andric   if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
338f785676fSDimitry Andric     Constant *OffsetVal =
339f785676fSDimitry Andric         ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
340f785676fSDimitry Andric 
34139d628a0SDimitry Andric     StackGuardVar =
34239d628a0SDimitry Andric         ConstantExpr::getIntToPtr(OffsetVal, PointerType::get(PtrTy,
34339d628a0SDimitry Andric                                                               AddressSpace));
34439d628a0SDimitry Andric   } else if (TT.isOSOpenBSD()) {
345f785676fSDimitry Andric     StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
346f785676fSDimitry Andric     cast<GlobalValue>(StackGuardVar)
347f785676fSDimitry Andric         ->setVisibility(GlobalValue::HiddenVisibility);
348f785676fSDimitry Andric   } else {
349f785676fSDimitry Andric     SupportsSelectionDAGSP = true;
350f785676fSDimitry Andric     StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
351f785676fSDimitry Andric   }
352f785676fSDimitry Andric 
353f785676fSDimitry Andric   IRBuilder<> B(&F->getEntryBlock().front());
35491bc56edSDimitry Andric   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
355f785676fSDimitry Andric   LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
356ff0cc061SDimitry Andric   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
357ff0cc061SDimitry Andric                {LI, AI});
358f785676fSDimitry Andric 
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 HasPrologue = false;
370f785676fSDimitry Andric   bool SupportsSelectionDAGSP =
371f785676fSDimitry Andric       EnableSelectionDAGSP && !TM->Options.EnableFastISel;
37291bc56edSDimitry Andric   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
37391bc56edSDimitry Andric   Value *StackGuardVar = nullptr; // The stack guard variable.
374f22ef01cSRoman Divacky 
375f22ef01cSRoman Divacky   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
376f22ef01cSRoman Divacky     BasicBlock *BB = I++;
377f22ef01cSRoman Divacky     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
378f785676fSDimitry Andric     if (!RI)
379f785676fSDimitry Andric       continue;
380f22ef01cSRoman Divacky 
381f785676fSDimitry Andric     if (!HasPrologue) {
382f785676fSDimitry Andric       HasPrologue = true;
383f785676fSDimitry Andric       SupportsSelectionDAGSP &=
384f785676fSDimitry Andric           CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
385f785676fSDimitry Andric     }
386ffd1746dSEd Schouten 
387f785676fSDimitry Andric     if (SupportsSelectionDAGSP) {
388f785676fSDimitry Andric       // Since we have a potential tail call, insert the special stack check
389f785676fSDimitry Andric       // intrinsic.
39091bc56edSDimitry Andric       Instruction *InsertionPt = nullptr;
391f785676fSDimitry Andric       if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
392f785676fSDimitry Andric         InsertionPt = CI;
393ffd1746dSEd Schouten       } else {
394f785676fSDimitry Andric         InsertionPt = RI;
395f785676fSDimitry Andric         // At this point we know that BB has a return statement so it *DOES*
396f785676fSDimitry Andric         // have a terminator.
39739d628a0SDimitry Andric         assert(InsertionPt != nullptr &&
39839d628a0SDimitry Andric                "BB must have a terminator instruction at this point.");
399ffd1746dSEd Schouten       }
400f22ef01cSRoman Divacky 
401f785676fSDimitry Andric       Function *Intrinsic =
402f785676fSDimitry Andric           Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
403f785676fSDimitry Andric       CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
404f785676fSDimitry Andric     } else {
405f785676fSDimitry Andric       // If we do not support SelectionDAG based tail calls, generate IR level
406f785676fSDimitry Andric       // tail calls.
407f785676fSDimitry Andric       //
408f22ef01cSRoman Divacky       // For each block with a return instruction, convert this:
409f22ef01cSRoman Divacky       //
410f22ef01cSRoman Divacky       //   return:
411f22ef01cSRoman Divacky       //     ...
412f22ef01cSRoman Divacky       //     ret ...
413f22ef01cSRoman Divacky       //
414f22ef01cSRoman Divacky       // into this:
415f22ef01cSRoman Divacky       //
416f22ef01cSRoman Divacky       //   return:
417f22ef01cSRoman Divacky       //     ...
418f22ef01cSRoman Divacky       //     %1 = load __stack_chk_guard
419f22ef01cSRoman Divacky       //     %2 = load StackGuardSlot
420f22ef01cSRoman Divacky       //     %3 = cmp i1 %1, %2
421f22ef01cSRoman Divacky       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
422f22ef01cSRoman Divacky       //
423f22ef01cSRoman Divacky       //   SP_return:
424f22ef01cSRoman Divacky       //     ret ...
425f22ef01cSRoman Divacky       //
426f22ef01cSRoman Divacky       //   CallStackCheckFailBlk:
427f22ef01cSRoman Divacky       //     call void @__stack_chk_fail()
428f22ef01cSRoman Divacky       //     unreachable
429f22ef01cSRoman Divacky 
430f785676fSDimitry Andric       // Create the FailBB. We duplicate the BB every time since the MI tail
431f785676fSDimitry Andric       // merge pass will merge together all of the various BB into one including
432f785676fSDimitry Andric       // fail BB generated by the stack protector pseudo instruction.
433f785676fSDimitry Andric       BasicBlock *FailBB = CreateFailBB();
434f785676fSDimitry Andric 
435f22ef01cSRoman Divacky       // Split the basic block before the return instruction.
436f22ef01cSRoman Divacky       BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
4373b0f4066SDimitry Andric 
438f785676fSDimitry Andric       // Update the dominator tree if we need to.
4393b0f4066SDimitry Andric       if (DT && DT->isReachableFromEntry(BB)) {
4403b0f4066SDimitry Andric         DT->addNewBlock(NewBB, BB);
441f785676fSDimitry Andric         DT->addNewBlock(FailBB, BB);
4422754fe60SDimitry Andric       }
443f22ef01cSRoman Divacky 
444f22ef01cSRoman Divacky       // Remove default branch instruction to the new BB.
445f22ef01cSRoman Divacky       BB->getTerminator()->eraseFromParent();
446f22ef01cSRoman Divacky 
447f785676fSDimitry Andric       // Move the newly created basic block to the point right after the old
448f785676fSDimitry Andric       // basic block so that it's in the "fall through" position.
449f22ef01cSRoman Divacky       NewBB->moveAfter(BB);
450f22ef01cSRoman Divacky 
451f22ef01cSRoman Divacky       // Generate the stack protector instructions in the old basic block.
452f785676fSDimitry Andric       IRBuilder<> B(BB);
453f785676fSDimitry Andric       LoadInst *LI1 = B.CreateLoad(StackGuardVar);
454f785676fSDimitry Andric       LoadInst *LI2 = B.CreateLoad(AI);
455f785676fSDimitry Andric       Value *Cmp = B.CreateICmpEQ(LI1, LI2);
45639d628a0SDimitry Andric       unsigned SuccessWeight =
45739d628a0SDimitry Andric           BranchProbabilityInfo::getBranchWeightStackProtector(true);
45839d628a0SDimitry Andric       unsigned FailureWeight =
45939d628a0SDimitry Andric           BranchProbabilityInfo::getBranchWeightStackProtector(false);
46039d628a0SDimitry Andric       MDNode *Weights = MDBuilder(F->getContext())
46139d628a0SDimitry Andric                             .createBranchWeights(SuccessWeight, FailureWeight);
46239d628a0SDimitry Andric       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
463f785676fSDimitry Andric     }
464f22ef01cSRoman Divacky   }
465f22ef01cSRoman Divacky 
46639d628a0SDimitry Andric   // Return if we didn't modify any basic blocks. i.e., there are no return
467f22ef01cSRoman Divacky   // statements in the function.
468f785676fSDimitry Andric   if (!HasPrologue)
469f785676fSDimitry Andric     return false;
4702754fe60SDimitry Andric 
471f22ef01cSRoman Divacky   return true;
472f22ef01cSRoman Divacky }
473f22ef01cSRoman Divacky 
474f22ef01cSRoman Divacky /// CreateFailBB - Create a basic block to jump to when the stack protector
475f22ef01cSRoman Divacky /// check fails.
476f22ef01cSRoman Divacky BasicBlock *StackProtector::CreateFailBB() {
477f785676fSDimitry Andric   LLVMContext &Context = F->getContext();
478f785676fSDimitry Andric   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
479f785676fSDimitry Andric   IRBuilder<> B(FailBB);
48039d628a0SDimitry Andric   if (Trip.isOSOpenBSD()) {
48139d628a0SDimitry Andric     Constant *StackChkFail =
48239d628a0SDimitry Andric         M->getOrInsertFunction("__stack_smash_handler",
48339d628a0SDimitry Andric                                Type::getVoidTy(Context),
48439d628a0SDimitry Andric                                Type::getInt8PtrTy(Context), nullptr);
485f785676fSDimitry Andric 
486f785676fSDimitry Andric     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
487f785676fSDimitry Andric   } else {
48839d628a0SDimitry Andric     Constant *StackChkFail =
48939d628a0SDimitry Andric         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context),
49039d628a0SDimitry Andric                                nullptr);
491ff0cc061SDimitry Andric     B.CreateCall(StackChkFail, {});
492f785676fSDimitry Andric   }
493f785676fSDimitry Andric   B.CreateUnreachable();
494f22ef01cSRoman Divacky   return FailBB;
495f22ef01cSRoman Divacky }
496