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"
20f785676fSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
2191bc56edSDimitry Andric #include "llvm/CodeGen/Analysis.h"
2291bc56edSDimitry Andric #include "llvm/CodeGen/Passes.h"
23139f7f9bSDimitry Andric #include "llvm/IR/Attributes.h"
24139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
25139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
26139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
27139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
28f785676fSDimitry Andric #include "llvm/IR/GlobalValue.h"
29f785676fSDimitry Andric #include "llvm/IR/GlobalVariable.h"
30f785676fSDimitry Andric #include "llvm/IR/IRBuilder.h"
31139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
32f785676fSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
33139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
34139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
35f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
36f785676fSDimitry Andric #include <cstdlib>
37f22ef01cSRoman Divacky using namespace llvm;
38f22ef01cSRoman Divacky 
3991bc56edSDimitry Andric #define DEBUG_TYPE "stack-protector"
4091bc56edSDimitry Andric 
41139f7f9bSDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected");
42139f7f9bSDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address"
43139f7f9bSDimitry Andric                         " taken.");
44139f7f9bSDimitry Andric 
45f785676fSDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
46f785676fSDimitry Andric                                           cl::init(true), cl::Hidden);
47f22ef01cSRoman Divacky 
48f22ef01cSRoman Divacky char StackProtector::ID = 0;
49f785676fSDimitry Andric INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
50f785676fSDimitry Andric                 false, true)
51f22ef01cSRoman Divacky 
52f785676fSDimitry Andric FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
53f785676fSDimitry Andric   return new StackProtector(TM);
54f785676fSDimitry Andric }
55f785676fSDimitry Andric 
56f785676fSDimitry Andric StackProtector::SSPLayoutKind
57f785676fSDimitry Andric StackProtector::getSSPLayout(const AllocaInst *AI) const {
58f785676fSDimitry Andric   return AI ? Layout.lookup(AI) : SSPLK_None;
59f22ef01cSRoman Divacky }
60f22ef01cSRoman Divacky 
6191bc56edSDimitry Andric void StackProtector::adjustForColoring(const AllocaInst *From,
6291bc56edSDimitry Andric                                        const AllocaInst *To) {
6391bc56edSDimitry Andric   // When coloring replaces one alloca with another, transfer the SSPLayoutKind
6491bc56edSDimitry Andric   // tag from the remapped to the target alloca. The remapped alloca should
6591bc56edSDimitry Andric   // have a size smaller than or equal to the replacement alloca.
6691bc56edSDimitry Andric   SSPLayoutMap::iterator I = Layout.find(From);
6791bc56edSDimitry Andric   if (I != Layout.end()) {
6891bc56edSDimitry Andric     SSPLayoutKind Kind = I->second;
6991bc56edSDimitry Andric     Layout.erase(I);
7091bc56edSDimitry Andric 
7191bc56edSDimitry Andric     // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
7291bc56edSDimitry Andric     // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
7391bc56edSDimitry Andric     // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
7491bc56edSDimitry Andric     I = Layout.find(To);
7591bc56edSDimitry Andric     if (I == Layout.end())
7691bc56edSDimitry Andric       Layout.insert(std::make_pair(To, Kind));
7791bc56edSDimitry Andric     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
7891bc56edSDimitry Andric       I->second = Kind;
7991bc56edSDimitry Andric   }
8091bc56edSDimitry Andric }
8191bc56edSDimitry Andric 
82f22ef01cSRoman Divacky bool StackProtector::runOnFunction(Function &Fn) {
83f22ef01cSRoman Divacky   F = &Fn;
84f22ef01cSRoman Divacky   M = F->getParent();
8591bc56edSDimitry Andric   DominatorTreeWrapperPass *DTWP =
8691bc56edSDimitry Andric       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
8791bc56edSDimitry Andric   DT = DTWP ? &DTWP->getDomTree() : nullptr;
88f785676fSDimitry Andric   TLI = TM->getTargetLowering();
89f22ef01cSRoman Divacky 
90f785676fSDimitry Andric   Attribute Attr = Fn.getAttributes().getAttribute(
91f785676fSDimitry Andric       AttributeSet::FunctionIndex, "stack-protector-buffer-size");
9291bc56edSDimitry Andric   if (Attr.isStringAttribute() &&
9391bc56edSDimitry Andric       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
9491bc56edSDimitry Andric       return false; // Invalid integer string
9591bc56edSDimitry Andric 
9691bc56edSDimitry Andric   if (!RequiresStackProtector())
9791bc56edSDimitry Andric     return false;
98f22ef01cSRoman Divacky 
99139f7f9bSDimitry Andric   ++NumFunProtected;
100f22ef01cSRoman Divacky   return InsertStackProtectors();
101f22ef01cSRoman Divacky }
102f22ef01cSRoman Divacky 
103f785676fSDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and
104f785676fSDimitry Andric /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
105f785676fSDimitry Andric /// multiple arrays, this gets set if any of them is large.
106f785676fSDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
107f785676fSDimitry Andric                                               bool Strong,
108139f7f9bSDimitry Andric                                               bool InStruct) const {
109f785676fSDimitry Andric   if (!Ty)
110f785676fSDimitry Andric     return false;
1113861d79fSDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1123861d79fSDimitry Andric     if (!AT->getElementType()->isIntegerTy(8)) {
1133861d79fSDimitry Andric       // If we're on a non-Darwin platform or we're inside of a structure, don't
1143861d79fSDimitry Andric       // add stack protectors unless the array is a character array.
115f785676fSDimitry Andric       // However, in strong mode any array, regardless of type and size,
116f785676fSDimitry Andric       // triggers a protector.
117f785676fSDimitry Andric       if (!Strong && (InStruct || !Trip.isOSDarwin()))
1183861d79fSDimitry Andric         return false;
1193861d79fSDimitry Andric     }
1203861d79fSDimitry Andric 
1213861d79fSDimitry Andric     // If an array has more than SSPBufferSize bytes of allocated space, then we
1223861d79fSDimitry Andric     // emit stack protectors.
123f785676fSDimitry Andric     if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
124f785676fSDimitry Andric       IsLarge = true;
125f785676fSDimitry Andric       return true;
126f785676fSDimitry Andric     }
127f785676fSDimitry Andric 
128f785676fSDimitry Andric     if (Strong)
129f785676fSDimitry Andric       // Require a protector for all arrays in strong mode
1303861d79fSDimitry Andric       return true;
1313861d79fSDimitry Andric   }
1323861d79fSDimitry Andric 
1333861d79fSDimitry Andric   const StructType *ST = dyn_cast<StructType>(Ty);
134f785676fSDimitry Andric   if (!ST)
1353861d79fSDimitry Andric     return false;
136f785676fSDimitry Andric 
137f785676fSDimitry Andric   bool NeedsProtector = false;
138f785676fSDimitry Andric   for (StructType::element_iterator I = ST->element_begin(),
139f785676fSDimitry Andric                                     E = ST->element_end();
140f785676fSDimitry Andric        I != E; ++I)
141f785676fSDimitry Andric     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
142f785676fSDimitry Andric       // If the element is a protectable array and is large (>= SSPBufferSize)
143f785676fSDimitry Andric       // then we are done.  If the protectable array is not large, then
144f785676fSDimitry Andric       // keep looking in case a subsequent element is a large array.
145f785676fSDimitry Andric       if (IsLarge)
146f785676fSDimitry Andric         return true;
147f785676fSDimitry Andric       NeedsProtector = true;
148f785676fSDimitry Andric     }
149f785676fSDimitry Andric 
150f785676fSDimitry Andric   return NeedsProtector;
1513861d79fSDimitry Andric }
1523861d79fSDimitry Andric 
153139f7f9bSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI) {
15491bc56edSDimitry Andric   for (const User *U : AI->users()) {
155139f7f9bSDimitry Andric     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
156139f7f9bSDimitry Andric       if (AI == SI->getValueOperand())
157f22ef01cSRoman Divacky         return true;
158139f7f9bSDimitry Andric     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
159139f7f9bSDimitry Andric       if (AI == SI->getOperand(0))
160139f7f9bSDimitry Andric         return true;
161139f7f9bSDimitry Andric     } else if (isa<CallInst>(U)) {
162139f7f9bSDimitry Andric       return true;
163139f7f9bSDimitry Andric     } else if (isa<InvokeInst>(U)) {
164139f7f9bSDimitry Andric       return true;
165139f7f9bSDimitry Andric     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
166139f7f9bSDimitry Andric       if (HasAddressTaken(SI))
167139f7f9bSDimitry Andric         return true;
168139f7f9bSDimitry Andric     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
169139f7f9bSDimitry Andric       // Keep track of what PHI nodes we have already visited to ensure
170139f7f9bSDimitry Andric       // they are only visited once.
171139f7f9bSDimitry Andric       if (VisitedPHIs.insert(PN))
172139f7f9bSDimitry Andric         if (HasAddressTaken(PN))
173139f7f9bSDimitry Andric           return true;
174139f7f9bSDimitry Andric     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
175139f7f9bSDimitry Andric       if (HasAddressTaken(GEP))
176139f7f9bSDimitry Andric         return true;
177139f7f9bSDimitry Andric     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
178139f7f9bSDimitry Andric       if (HasAddressTaken(BI))
179139f7f9bSDimitry Andric         return true;
180139f7f9bSDimitry Andric     }
181139f7f9bSDimitry Andric   }
182139f7f9bSDimitry Andric   return false;
183139f7f9bSDimitry Andric }
184f22ef01cSRoman Divacky 
185139f7f9bSDimitry Andric /// \brief Check whether or not this function needs a stack protector based
186139f7f9bSDimitry Andric /// upon the stack protector level.
187139f7f9bSDimitry Andric ///
188139f7f9bSDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong).
189139f7f9bSDimitry Andric /// The standard heuristic which will add a guard variable to functions that
190139f7f9bSDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize,
191139f7f9bSDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions
192139f7f9bSDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The
193139f7f9bSDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca
194139f7f9bSDimitry Andric /// regardless of size, functions with any buffer regardless of type and size,
195139f7f9bSDimitry Andric /// functions with aggregates that contain any buffer regardless of type and
196139f7f9bSDimitry Andric /// size, and functions that contain stack-based variables that have had their
197139f7f9bSDimitry Andric /// address taken.
198139f7f9bSDimitry Andric bool StackProtector::RequiresStackProtector() {
199139f7f9bSDimitry Andric   bool Strong = false;
200f785676fSDimitry Andric   bool NeedsProtector = false;
201139f7f9bSDimitry Andric   if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
202f785676fSDimitry Andric                                       Attribute::StackProtectReq)) {
203f785676fSDimitry Andric     NeedsProtector = true;
204f785676fSDimitry Andric     Strong = true; // Use the same heuristic as strong to determine SSPLayout
205f785676fSDimitry Andric   } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
206139f7f9bSDimitry Andric                                              Attribute::StackProtectStrong))
207139f7f9bSDimitry Andric     Strong = true;
208139f7f9bSDimitry Andric   else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
209139f7f9bSDimitry Andric                                             Attribute::StackProtect))
210f22ef01cSRoman Divacky     return false;
211f22ef01cSRoman Divacky 
212f22ef01cSRoman Divacky   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
213f22ef01cSRoman Divacky     BasicBlock *BB = I;
214f22ef01cSRoman Divacky 
215f785676fSDimitry Andric     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
216f785676fSDimitry Andric          ++II) {
217f22ef01cSRoman Divacky       if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
218139f7f9bSDimitry Andric         if (AI->isArrayAllocation()) {
219139f7f9bSDimitry Andric           // SSP-Strong: Enable protectors for any call to alloca, regardless
220139f7f9bSDimitry Andric           // of size.
221139f7f9bSDimitry Andric           if (Strong)
222f22ef01cSRoman Divacky             return true;
223f22ef01cSRoman Divacky 
224139f7f9bSDimitry Andric           if (const ConstantInt *CI =
225139f7f9bSDimitry Andric                   dyn_cast<ConstantInt>(AI->getArraySize())) {
226f785676fSDimitry Andric             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
227139f7f9bSDimitry Andric               // A call to alloca with size >= SSPBufferSize requires
228139f7f9bSDimitry Andric               // stack protectors.
229f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
230f785676fSDimitry Andric               NeedsProtector = true;
231f785676fSDimitry Andric             } else if (Strong) {
232f785676fSDimitry Andric               // Require protectors for all alloca calls in strong mode.
233f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
234f785676fSDimitry Andric               NeedsProtector = true;
235f785676fSDimitry Andric             }
236f785676fSDimitry Andric           } else {
237f785676fSDimitry Andric             // A call to alloca with a variable size requires protectors.
238f785676fSDimitry Andric             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
239f785676fSDimitry Andric             NeedsProtector = true;
240f785676fSDimitry Andric           }
241f785676fSDimitry Andric           continue;
242139f7f9bSDimitry Andric         }
243139f7f9bSDimitry Andric 
244f785676fSDimitry Andric         bool IsLarge = false;
245f785676fSDimitry Andric         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
246f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
247f785676fSDimitry Andric                                                    : SSPLK_SmallArray));
248f785676fSDimitry Andric           NeedsProtector = true;
249f785676fSDimitry Andric           continue;
250f785676fSDimitry Andric         }
251139f7f9bSDimitry Andric 
252139f7f9bSDimitry Andric         if (Strong && HasAddressTaken(AI)) {
253139f7f9bSDimitry Andric           ++NumAddrTaken;
254f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
255f785676fSDimitry Andric           NeedsProtector = true;
256139f7f9bSDimitry Andric         }
257139f7f9bSDimitry Andric       }
258f22ef01cSRoman Divacky     }
259f22ef01cSRoman Divacky   }
260f22ef01cSRoman Divacky 
261f785676fSDimitry Andric   return NeedsProtector;
262f785676fSDimitry Andric }
263f785676fSDimitry Andric 
264f785676fSDimitry Andric static bool InstructionWillNotHaveChain(const Instruction *I) {
265f785676fSDimitry Andric   return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
266f785676fSDimitry Andric          isSafeToSpeculativelyExecute(I);
267f785676fSDimitry Andric }
268f785676fSDimitry Andric 
269f785676fSDimitry Andric /// Identify if RI has a previous instruction in the "Tail Position" and return
270f785676fSDimitry Andric /// it. Otherwise return 0.
271f785676fSDimitry Andric ///
272f785676fSDimitry Andric /// This is based off of the code in llvm::isInTailCallPosition. The difference
273f785676fSDimitry Andric /// is that it inverts the first part of llvm::isInTailCallPosition since
274f785676fSDimitry Andric /// isInTailCallPosition is checking if a call is in a tail call position, and
275f785676fSDimitry Andric /// we are searching for an unknown tail call that might be in the tail call
276f785676fSDimitry Andric /// position. Once we find the call though, the code uses the same refactored
277f785676fSDimitry Andric /// code, returnTypeIsEligibleForTailCall.
278f785676fSDimitry Andric static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
279f785676fSDimitry Andric                                        const TargetLoweringBase *TLI) {
280f785676fSDimitry Andric   // Establish a reasonable upper bound on the maximum amount of instructions we
281f785676fSDimitry Andric   // will look through to find a tail call.
282f785676fSDimitry Andric   unsigned SearchCounter = 0;
283f785676fSDimitry Andric   const unsigned MaxSearch = 4;
284f785676fSDimitry Andric   bool NoInterposingChain = true;
285f785676fSDimitry Andric 
28691bc56edSDimitry Andric   for (BasicBlock::reverse_iterator I = std::next(BB->rbegin()), E = BB->rend();
287f785676fSDimitry Andric        I != E && SearchCounter < MaxSearch; ++I) {
288f785676fSDimitry Andric     Instruction *Inst = &*I;
289f785676fSDimitry Andric 
290f785676fSDimitry Andric     // Skip over debug intrinsics and do not allow them to affect our MaxSearch
291f785676fSDimitry Andric     // counter.
292f785676fSDimitry Andric     if (isa<DbgInfoIntrinsic>(Inst))
293f785676fSDimitry Andric       continue;
294f785676fSDimitry Andric 
295f785676fSDimitry Andric     // If we find a call and the following conditions are satisifed, then we
296f785676fSDimitry Andric     // have found a tail call that satisfies at least the target independent
297f785676fSDimitry Andric     // requirements of a tail call:
298f785676fSDimitry Andric     //
299f785676fSDimitry Andric     // 1. The call site has the tail marker.
300f785676fSDimitry Andric     //
301f785676fSDimitry Andric     // 2. The call site either will not cause the creation of a chain or if a
302f785676fSDimitry Andric     // chain is necessary there are no instructions in between the callsite and
303f785676fSDimitry Andric     // the call which would create an interposing chain.
304f785676fSDimitry Andric     //
305f785676fSDimitry Andric     // 3. The return type of the function does not impede tail call
306f785676fSDimitry Andric     // optimization.
307f785676fSDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
308f785676fSDimitry Andric       if (CI->isTailCall() &&
309f785676fSDimitry Andric           (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
310f785676fSDimitry Andric           returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
311f785676fSDimitry Andric         return CI;
312f785676fSDimitry Andric     }
313f785676fSDimitry Andric 
314f785676fSDimitry Andric     // If we did not find a call see if we have an instruction that may create
315f785676fSDimitry Andric     // an interposing chain.
316f785676fSDimitry Andric     NoInterposingChain =
317f785676fSDimitry Andric         NoInterposingChain && InstructionWillNotHaveChain(Inst);
318f785676fSDimitry Andric 
319f785676fSDimitry Andric     // Increment max search.
320f785676fSDimitry Andric     SearchCounter++;
321f785676fSDimitry Andric   }
322f785676fSDimitry Andric 
32391bc56edSDimitry Andric   return nullptr;
324f785676fSDimitry Andric }
325f785676fSDimitry Andric 
326f785676fSDimitry Andric /// Insert code into the entry block that stores the __stack_chk_guard
327f785676fSDimitry Andric /// variable onto the stack:
328f785676fSDimitry Andric ///
329f785676fSDimitry Andric ///   entry:
330f785676fSDimitry Andric ///     StackGuardSlot = alloca i8*
331f785676fSDimitry Andric ///     StackGuard = load __stack_chk_guard
332f785676fSDimitry Andric ///     call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
333f785676fSDimitry Andric ///
334f785676fSDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
335f785676fSDimitry Andric /// node.
336f785676fSDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
337f785676fSDimitry Andric                            const TargetLoweringBase *TLI, const Triple &Trip,
338f785676fSDimitry Andric                            AllocaInst *&AI, Value *&StackGuardVar) {
339f785676fSDimitry Andric   bool SupportsSelectionDAGSP = false;
340f785676fSDimitry Andric   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
341f785676fSDimitry Andric   unsigned AddressSpace, Offset;
342f785676fSDimitry Andric   if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
343f785676fSDimitry Andric     Constant *OffsetVal =
344f785676fSDimitry Andric         ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
345f785676fSDimitry Andric 
346f785676fSDimitry Andric     StackGuardVar = ConstantExpr::getIntToPtr(
347f785676fSDimitry Andric         OffsetVal, PointerType::get(PtrTy, AddressSpace));
348f785676fSDimitry Andric   } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
349f785676fSDimitry Andric     StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
350f785676fSDimitry Andric     cast<GlobalValue>(StackGuardVar)
351f785676fSDimitry Andric         ->setVisibility(GlobalValue::HiddenVisibility);
352f785676fSDimitry Andric   } else {
353f785676fSDimitry Andric     SupportsSelectionDAGSP = true;
354f785676fSDimitry Andric     StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
355f785676fSDimitry Andric   }
356f785676fSDimitry Andric 
357f785676fSDimitry Andric   IRBuilder<> B(&F->getEntryBlock().front());
35891bc56edSDimitry Andric   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
359f785676fSDimitry Andric   LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
360f785676fSDimitry Andric   B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
361f785676fSDimitry Andric                 AI);
362f785676fSDimitry Andric 
363f785676fSDimitry Andric   return SupportsSelectionDAGSP;
364f22ef01cSRoman Divacky }
365f22ef01cSRoman Divacky 
366f22ef01cSRoman Divacky /// InsertStackProtectors - Insert code into the prologue and epilogue of the
367f22ef01cSRoman Divacky /// function.
368f22ef01cSRoman Divacky ///
369f22ef01cSRoman Divacky ///  - The prologue code loads and stores the stack guard onto the stack.
370f22ef01cSRoman Divacky ///  - The epilogue checks the value stored in the prologue against the original
371f22ef01cSRoman Divacky ///    value. It calls __stack_chk_fail if they differ.
372f22ef01cSRoman Divacky bool StackProtector::InsertStackProtectors() {
373f785676fSDimitry Andric   bool HasPrologue = false;
374f785676fSDimitry Andric   bool SupportsSelectionDAGSP =
375f785676fSDimitry Andric       EnableSelectionDAGSP && !TM->Options.EnableFastISel;
37691bc56edSDimitry Andric   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
37791bc56edSDimitry Andric   Value *StackGuardVar = nullptr; // The stack guard variable.
378f22ef01cSRoman Divacky 
379f22ef01cSRoman Divacky   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
380f22ef01cSRoman Divacky     BasicBlock *BB = I++;
381f22ef01cSRoman Divacky     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
382f785676fSDimitry Andric     if (!RI)
383f785676fSDimitry Andric       continue;
384f22ef01cSRoman Divacky 
385f785676fSDimitry Andric     if (!HasPrologue) {
386f785676fSDimitry Andric       HasPrologue = true;
387f785676fSDimitry Andric       SupportsSelectionDAGSP &=
388f785676fSDimitry Andric           CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
389f785676fSDimitry Andric     }
390ffd1746dSEd Schouten 
391f785676fSDimitry Andric     if (SupportsSelectionDAGSP) {
392f785676fSDimitry Andric       // Since we have a potential tail call, insert the special stack check
393f785676fSDimitry Andric       // intrinsic.
39491bc56edSDimitry Andric       Instruction *InsertionPt = nullptr;
395f785676fSDimitry Andric       if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
396f785676fSDimitry Andric         InsertionPt = CI;
397ffd1746dSEd Schouten       } else {
398f785676fSDimitry Andric         InsertionPt = RI;
399f785676fSDimitry Andric         // At this point we know that BB has a return statement so it *DOES*
400f785676fSDimitry Andric         // have a terminator.
40191bc56edSDimitry Andric         assert(InsertionPt != nullptr && "BB must have a terminator instruction at "
402f785676fSDimitry Andric                                    "this point.");
403ffd1746dSEd Schouten       }
404f22ef01cSRoman Divacky 
405f785676fSDimitry Andric       Function *Intrinsic =
406f785676fSDimitry Andric           Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
407f785676fSDimitry Andric       CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
408f22ef01cSRoman Divacky 
409f785676fSDimitry Andric     } else {
410f785676fSDimitry Andric       // If we do not support SelectionDAG based tail calls, generate IR level
411f785676fSDimitry Andric       // tail calls.
412f785676fSDimitry Andric       //
413f22ef01cSRoman Divacky       // For each block with a return instruction, convert this:
414f22ef01cSRoman Divacky       //
415f22ef01cSRoman Divacky       //   return:
416f22ef01cSRoman Divacky       //     ...
417f22ef01cSRoman Divacky       //     ret ...
418f22ef01cSRoman Divacky       //
419f22ef01cSRoman Divacky       // into this:
420f22ef01cSRoman Divacky       //
421f22ef01cSRoman Divacky       //   return:
422f22ef01cSRoman Divacky       //     ...
423f22ef01cSRoman Divacky       //     %1 = load __stack_chk_guard
424f22ef01cSRoman Divacky       //     %2 = load StackGuardSlot
425f22ef01cSRoman Divacky       //     %3 = cmp i1 %1, %2
426f22ef01cSRoman Divacky       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
427f22ef01cSRoman Divacky       //
428f22ef01cSRoman Divacky       //   SP_return:
429f22ef01cSRoman Divacky       //     ret ...
430f22ef01cSRoman Divacky       //
431f22ef01cSRoman Divacky       //   CallStackCheckFailBlk:
432f22ef01cSRoman Divacky       //     call void @__stack_chk_fail()
433f22ef01cSRoman Divacky       //     unreachable
434f22ef01cSRoman Divacky 
435f785676fSDimitry Andric       // Create the FailBB. We duplicate the BB every time since the MI tail
436f785676fSDimitry Andric       // merge pass will merge together all of the various BB into one including
437f785676fSDimitry Andric       // fail BB generated by the stack protector pseudo instruction.
438f785676fSDimitry Andric       BasicBlock *FailBB = CreateFailBB();
439f785676fSDimitry Andric 
440f22ef01cSRoman Divacky       // Split the basic block before the return instruction.
441f22ef01cSRoman Divacky       BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
4423b0f4066SDimitry Andric 
443f785676fSDimitry Andric       // Update the dominator tree if we need to.
4443b0f4066SDimitry Andric       if (DT && DT->isReachableFromEntry(BB)) {
4453b0f4066SDimitry Andric         DT->addNewBlock(NewBB, BB);
446f785676fSDimitry Andric         DT->addNewBlock(FailBB, BB);
4472754fe60SDimitry Andric       }
448f22ef01cSRoman Divacky 
449f22ef01cSRoman Divacky       // Remove default branch instruction to the new BB.
450f22ef01cSRoman Divacky       BB->getTerminator()->eraseFromParent();
451f22ef01cSRoman Divacky 
452f785676fSDimitry Andric       // Move the newly created basic block to the point right after the old
453f785676fSDimitry Andric       // basic block so that it's in the "fall through" position.
454f22ef01cSRoman Divacky       NewBB->moveAfter(BB);
455f22ef01cSRoman Divacky 
456f22ef01cSRoman Divacky       // Generate the stack protector instructions in the old basic block.
457f785676fSDimitry Andric       IRBuilder<> B(BB);
458f785676fSDimitry Andric       LoadInst *LI1 = B.CreateLoad(StackGuardVar);
459f785676fSDimitry Andric       LoadInst *LI2 = B.CreateLoad(AI);
460f785676fSDimitry Andric       Value *Cmp = B.CreateICmpEQ(LI1, LI2);
461f785676fSDimitry Andric       B.CreateCondBr(Cmp, NewBB, FailBB);
462f785676fSDimitry Andric     }
463f22ef01cSRoman Divacky   }
464f22ef01cSRoman Divacky 
465f22ef01cSRoman Divacky   // Return if we didn't modify any basic blocks. I.e., there are no return
466f22ef01cSRoman Divacky   // statements in the function.
467f785676fSDimitry Andric   if (!HasPrologue)
468f785676fSDimitry Andric     return false;
4692754fe60SDimitry Andric 
470f22ef01cSRoman Divacky   return true;
471f22ef01cSRoman Divacky }
472f22ef01cSRoman Divacky 
473f22ef01cSRoman Divacky /// CreateFailBB - Create a basic block to jump to when the stack protector
474f22ef01cSRoman Divacky /// check fails.
475f22ef01cSRoman Divacky BasicBlock *StackProtector::CreateFailBB() {
476f785676fSDimitry Andric   LLVMContext &Context = F->getContext();
477f785676fSDimitry Andric   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
478f785676fSDimitry Andric   IRBuilder<> B(FailBB);
479f785676fSDimitry Andric   if (Trip.getOS() == llvm::Triple::OpenBSD) {
480f785676fSDimitry Andric     Constant *StackChkFail = M->getOrInsertFunction(
481f785676fSDimitry Andric         "__stack_smash_handler", Type::getVoidTy(Context),
482f785676fSDimitry Andric         Type::getInt8PtrTy(Context), NULL);
483f785676fSDimitry Andric 
484f785676fSDimitry Andric     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
485f785676fSDimitry Andric   } else {
486f785676fSDimitry Andric     Constant *StackChkFail = M->getOrInsertFunction(
487f785676fSDimitry Andric         "__stack_chk_fail", Type::getVoidTy(Context), NULL);
488f785676fSDimitry Andric     B.CreateCall(StackChkFail);
489f785676fSDimitry Andric   }
490f785676fSDimitry Andric   B.CreateUnreachable();
491f22ef01cSRoman Divacky   return FailBB;
492f22ef01cSRoman Divacky }
493