blob: f3749e5d0b7c6a29272d686145528df68407246f [file] [log] [blame]
Bill Wendling2b58ce52008-11-04 02:10:20 +00001//===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Bill Wendling80a320d2008-11-04 21:53:09 +000010// This pass inserts stack protectors into functions which need them. A variable
11// with a random value in it is stored onto the stack before the local variables
12// are allocated. Upon exiting the block, the stored value is checked. If it's
Bill Wendling2b58ce52008-11-04 02:10:20 +000013// changed, then there was some sort of violation and the program aborts.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "stack-protector"
Josh Magee18ebd482013-09-27 21:58:43 +000018#include "llvm/CodeGen/StackProtector.h"
Bill Wendlinge4957fb2013-01-23 06:43:53 +000019#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/Statistic.h"
Michael Gottesman3480d1b2013-08-20 08:36:53 +000021#include "llvm/Analysis/ValueTracking.h"
Stephen Hines36b56882014-04-23 16:57:46 -070022#include "llvm/CodeGen/Analysis.h"
23#include "llvm/CodeGen/Passes.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000024#include "llvm/IR/Attributes.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
Rafael Espindola62ed8d32013-06-07 16:35:57 +000029#include "llvm/IR/GlobalValue.h"
30#include "llvm/IR/GlobalVariable.h"
Benjamin Kramer54cf1412013-09-09 17:38:01 +000031#include "llvm/IR/IRBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000032#include "llvm/IR/Instructions.h"
Michael Gottesman3480d1b2013-08-20 08:36:53 +000033#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000034#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Module.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000036#include "llvm/Support/CommandLine.h"
Bill Wendling0dcba2f2013-07-22 20:15:21 +000037#include <cstdlib>
Bill Wendling2b58ce52008-11-04 02:10:20 +000038using namespace llvm;
39
Bill Wendlinge4957fb2013-01-23 06:43:53 +000040STATISTIC(NumFunProtected, "Number of functions protected");
41STATISTIC(NumAddrTaken, "Number of local variables that have their address"
42 " taken.");
43
Josh Magee62406fd2013-10-30 02:25:14 +000044static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
45 cl::init(true), cl::Hidden);
Michael Gottesman3480d1b2013-08-20 08:36:53 +000046
Bill Wendling2b58ce52008-11-04 02:10:20 +000047char StackProtector::ID = 0;
Josh Magee62406fd2013-10-30 02:25:14 +000048INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
49 false, true)
Bill Wendling2b58ce52008-11-04 02:10:20 +000050
Bill Wendlingea442812013-06-19 20:51:24 +000051FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
52 return new StackProtector(TM);
Bill Wendling2b58ce52008-11-04 02:10:20 +000053}
54
Josh Magee62406fd2013-10-30 02:25:14 +000055StackProtector::SSPLayoutKind
56StackProtector::getSSPLayout(const AllocaInst *AI) const {
Josh Magee4598b402013-10-29 21:16:16 +000057 return AI ? Layout.lookup(AI) : SSPLK_None;
58}
59
Stephen Hines36b56882014-04-23 16:57:46 -070060void StackProtector::adjustForColoring(const AllocaInst *From,
61 const AllocaInst *To) {
62 // When coloring replaces one alloca with another, transfer the SSPLayoutKind
63 // tag from the remapped to the target alloca. The remapped alloca should
64 // have a size smaller than or equal to the replacement alloca.
65 SSPLayoutMap::iterator I = Layout.find(From);
66 if (I != Layout.end()) {
67 SSPLayoutKind Kind = I->second;
68 Layout.erase(I);
69
70 // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
71 // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
72 // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
73 I = Layout.find(To);
74 if (I == Layout.end())
75 Layout.insert(std::make_pair(To, Kind));
76 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
77 I->second = Kind;
78 }
79}
80
Bill Wendling2b58ce52008-11-04 02:10:20 +000081bool StackProtector::runOnFunction(Function &Fn) {
82 F = &Fn;
83 M = F->getParent();
Stephen Hines36b56882014-04-23 16:57:46 -070084 DominatorTreeWrapperPass *DTWP =
85 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
86 DT = DTWP ? &DTWP->getDomTree() : 0;
Bill Wendlingea442812013-06-19 20:51:24 +000087 TLI = TM->getTargetLowering();
Bill Wendling2b58ce52008-11-04 02:10:20 +000088
Josh Magee62406fd2013-10-30 02:25:14 +000089 if (!RequiresStackProtector())
90 return false;
Bill Wendling6d86f3c2012-08-13 21:20:43 +000091
Josh Magee62406fd2013-10-30 02:25:14 +000092 Attribute Attr = Fn.getAttributes().getAttribute(
93 AttributeSet::FunctionIndex, "stack-protector-buffer-size");
Stephen Hines36b56882014-04-23 16:57:46 -070094 if (Attr.isStringAttribute() &&
95 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
96 return false; // Invalid integer string
Bill Wendling0dcba2f2013-07-22 20:15:21 +000097
Bill Wendlinge4957fb2013-01-23 06:43:53 +000098 ++NumFunProtected;
Bill Wendling613f7742008-11-05 00:00:21 +000099 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000100}
101
Josh Magee4598b402013-10-29 21:16:16 +0000102/// \param [out] IsLarge is set to true if a protectable array is found and
103/// it is "large" ( >= ssp-buffer-size). In the case of a structure with
104/// multiple arrays, this gets set if any of them is large.
105bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
Josh Magee62406fd2013-10-30 02:25:14 +0000106 bool Strong,
107 bool InStruct) const {
108 if (!Ty)
109 return false;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000110 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
111 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlinga67eda72012-08-17 20:59:56 +0000112 // If we're on a non-Darwin platform or we're inside of a structure, don't
113 // add stack protectors unless the array is a character array.
Josh Magee4598b402013-10-29 21:16:16 +0000114 // However, in strong mode any array, regardless of type and size,
115 // triggers a protector.
116 if (!Strong && (InStruct || !Trip.isOSDarwin()))
117 return false;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000118 }
119
120 // If an array has more than SSPBufferSize bytes of allocated space, then we
121 // emit stack protectors.
Josh Magee4598b402013-10-29 21:16:16 +0000122 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
123 IsLarge = true;
124 return true;
Josh Magee62406fd2013-10-30 02:25:14 +0000125 }
Josh Magee4598b402013-10-29 21:16:16 +0000126
127 if (Strong)
128 // Require a protector for all arrays in strong mode
Bill Wendlinga67eda72012-08-17 20:59:56 +0000129 return true;
130 }
131
132 const StructType *ST = dyn_cast<StructType>(Ty);
Josh Magee62406fd2013-10-30 02:25:14 +0000133 if (!ST)
134 return false;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000135
Josh Magee4598b402013-10-29 21:16:16 +0000136 bool NeedsProtector = false;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000137 for (StructType::element_iterator I = ST->element_begin(),
Josh Magee62406fd2013-10-30 02:25:14 +0000138 E = ST->element_end();
139 I != E; ++I)
Josh Magee4598b402013-10-29 21:16:16 +0000140 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
141 // If the element is a protectable array and is large (>= SSPBufferSize)
142 // then we are done. If the protectable array is not large, then
143 // keep looking in case a subsequent element is a large array.
144 if (IsLarge)
145 return true;
146 NeedsProtector = true;
147 }
Bill Wendlinga67eda72012-08-17 20:59:56 +0000148
Josh Magee4598b402013-10-29 21:16:16 +0000149 return NeedsProtector;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000150}
151
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000152bool StackProtector::HasAddressTaken(const Instruction *AI) {
Stephen Hines36b56882014-04-23 16:57:46 -0700153 for (const User *U : AI->users()) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000154 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
155 if (AI == SI->getValueOperand())
156 return true;
157 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
158 if (AI == SI->getOperand(0))
159 return true;
160 } else if (isa<CallInst>(U)) {
161 return true;
162 } else if (isa<InvokeInst>(U)) {
163 return true;
164 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
165 if (HasAddressTaken(SI))
166 return true;
167 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
168 // Keep track of what PHI nodes we have already visited to ensure
169 // they are only visited once.
170 if (VisitedPHIs.insert(PN))
171 if (HasAddressTaken(PN))
172 return true;
173 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
174 if (HasAddressTaken(GEP))
175 return true;
176 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
177 if (HasAddressTaken(BI))
178 return true;
179 }
180 }
181 return false;
182}
183
184/// \brief Check whether or not this function needs a stack protector based
185/// upon the stack protector level.
186///
187/// We use two heuristics: a standard (ssp) and strong (sspstrong).
188/// The standard heuristic which will add a guard variable to functions that
189/// call alloca with a either a variable size or a size >= SSPBufferSize,
190/// functions with character buffers larger than SSPBufferSize, and functions
191/// with aggregates containing character buffers larger than SSPBufferSize. The
192/// strong heuristic will add a guard variables to functions that call alloca
193/// regardless of size, functions with any buffer regardless of type and size,
194/// functions with aggregates that contain any buffer regardless of type and
195/// size, and functions that contain stack-based variables that have had their
196/// address taken.
197bool StackProtector::RequiresStackProtector() {
198 bool Strong = false;
Josh Magee4598b402013-10-29 21:16:16 +0000199 bool NeedsProtector = false;
Bill Wendling831737d2012-12-30 10:32:01 +0000200 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Josh Magee4598b402013-10-29 21:16:16 +0000201 Attribute::StackProtectReq)) {
202 NeedsProtector = true;
203 Strong = true; // Use the same heuristic as strong to determine SSPLayout
204 } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
205 Attribute::StackProtectStrong))
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000206 Strong = true;
207 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
208 Attribute::StackProtect))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000209 return false;
210
Bill Wendlingc3348a72008-11-18 05:32:11 +0000211 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
212 BasicBlock *BB = I;
213
Josh Magee62406fd2013-10-30 02:25:14 +0000214 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
215 ++II) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000216 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000217 if (AI->isArrayAllocation()) {
218 // SSP-Strong: Enable protectors for any call to alloca, regardless
219 // of size.
220 if (Strong)
221 return true;
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000222
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000223 if (const ConstantInt *CI =
Josh Magee62406fd2013-10-30 02:25:14 +0000224 dyn_cast<ConstantInt>(AI->getArraySize())) {
Josh Magee4598b402013-10-29 21:16:16 +0000225 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000226 // A call to alloca with size >= SSPBufferSize requires
227 // stack protectors.
Josh Magee4598b402013-10-29 21:16:16 +0000228 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
229 NeedsProtector = true;
230 } else if (Strong) {
231 // Require protectors for all alloca calls in strong mode.
232 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
233 NeedsProtector = true;
234 }
Bill Wendling0dcba2f2013-07-22 20:15:21 +0000235 } else {
236 // A call to alloca with a variable size requires protectors.
Josh Magee4598b402013-10-29 21:16:16 +0000237 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
238 NeedsProtector = true;
Bill Wendling0dcba2f2013-07-22 20:15:21 +0000239 }
Josh Magee4598b402013-10-29 21:16:16 +0000240 continue;
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000241 }
242
Josh Magee4598b402013-10-29 21:16:16 +0000243 bool IsLarge = false;
244 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
245 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
246 : SSPLK_SmallArray));
247 NeedsProtector = true;
248 continue;
249 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000250
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000251 if (Strong && HasAddressTaken(AI)) {
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000252 ++NumAddrTaken;
Josh Magee4598b402013-10-29 21:16:16 +0000253 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
254 NeedsProtector = true;
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000255 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000256 }
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000257 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000258 }
259
Josh Magee4598b402013-10-29 21:16:16 +0000260 return NeedsProtector;
Bill Wendlingc3348a72008-11-18 05:32:11 +0000261}
262
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000263static bool InstructionWillNotHaveChain(const Instruction *I) {
264 return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
Josh Magee62406fd2013-10-30 02:25:14 +0000265 isSafeToSpeculativelyExecute(I);
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000266}
267
268/// Identify if RI has a previous instruction in the "Tail Position" and return
269/// it. Otherwise return 0.
270///
Michael Gottesmanb99272a2013-08-20 08:56:23 +0000271/// This is based off of the code in llvm::isInTailCallPosition. The difference
272/// is that it inverts the first part of llvm::isInTailCallPosition since
273/// isInTailCallPosition is checking if a call is in a tail call position, and
274/// we are searching for an unknown tail call that might be in the tail call
275/// position. Once we find the call though, the code uses the same refactored
276/// code, returnTypeIsEligibleForTailCall.
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000277static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
278 const TargetLoweringBase *TLI) {
279 // Establish a reasonable upper bound on the maximum amount of instructions we
280 // will look through to find a tail call.
281 unsigned SearchCounter = 0;
282 const unsigned MaxSearch = 4;
283 bool NoInterposingChain = true;
284
Stephen Hines36b56882014-04-23 16:57:46 -0700285 for (BasicBlock::reverse_iterator I = std::next(BB->rbegin()), E = BB->rend();
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000286 I != E && SearchCounter < MaxSearch; ++I) {
287 Instruction *Inst = &*I;
288
289 // Skip over debug intrinsics and do not allow them to affect our MaxSearch
290 // counter.
291 if (isa<DbgInfoIntrinsic>(Inst))
292 continue;
293
294 // If we find a call and the following conditions are satisifed, then we
295 // have found a tail call that satisfies at least the target independent
296 // requirements of a tail call:
297 //
298 // 1. The call site has the tail marker.
299 //
300 // 2. The call site either will not cause the creation of a chain or if a
301 // chain is necessary there are no instructions in between the callsite and
302 // the call which would create an interposing chain.
303 //
304 // 3. The return type of the function does not impede tail call
305 // optimization.
306 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
307 if (CI->isTailCall() &&
308 (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
309 returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
310 return CI;
311 }
312
313 // If we did not find a call see if we have an instruction that may create
314 // an interposing chain.
Josh Magee62406fd2013-10-30 02:25:14 +0000315 NoInterposingChain =
316 NoInterposingChain && InstructionWillNotHaveChain(Inst);
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000317
318 // Increment max search.
319 SearchCounter++;
320 }
321
322 return 0;
323}
324
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000325/// Insert code into the entry block that stores the __stack_chk_guard
326/// variable onto the stack:
327///
328/// entry:
329/// StackGuardSlot = alloca i8*
330/// StackGuard = load __stack_chk_guard
331/// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
332///
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000333/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
334/// node.
335static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000336 const TargetLoweringBase *TLI, const Triple &Trip,
337 AllocaInst *&AI, Value *&StackGuardVar) {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000338 bool SupportsSelectionDAGSP = false;
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000339 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
340 unsigned AddressSpace, Offset;
341 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
342 Constant *OffsetVal =
Josh Magee62406fd2013-10-30 02:25:14 +0000343 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000344
Josh Magee62406fd2013-10-30 02:25:14 +0000345 StackGuardVar = ConstantExpr::getIntToPtr(
346 OffsetVal, PointerType::get(PtrTy, AddressSpace));
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000347 } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
348 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
349 cast<GlobalValue>(StackGuardVar)
Josh Magee62406fd2013-10-30 02:25:14 +0000350 ->setVisibility(GlobalValue::HiddenVisibility);
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000351 } else {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000352 SupportsSelectionDAGSP = true;
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000353 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000354 }
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000355
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000356 IRBuilder<> B(&F->getEntryBlock().front());
357 AI = B.CreateAlloca(PtrTy, 0, "StackGuardSlot");
358 LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
359 B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
360 AI);
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000361
362 return SupportsSelectionDAGSP;
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000363}
364
Bill Wendling613f7742008-11-05 00:00:21 +0000365/// InsertStackProtectors - Insert code into the prologue and epilogue of the
366/// function.
367///
368/// - The prologue code loads and stores the stack guard onto the stack.
369/// - The epilogue checks the value stored in the prologue against the original
370/// value. It calls __stack_chk_fail if they differ.
371bool StackProtector::InsertStackProtectors() {
Michael Gottesman236e3892013-08-09 21:26:18 +0000372 bool HasPrologue = false;
Michael Gottesmand4f47882013-08-20 08:56:26 +0000373 bool SupportsSelectionDAGSP =
Josh Magee62406fd2013-10-30 02:25:14 +0000374 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
375 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
376 Value *StackGuardVar = 0; // The stack guard variable.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000377
Josh Magee62406fd2013-10-30 02:25:14 +0000378 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000379 BasicBlock *BB = I++;
Bill Wendlingc3348a72008-11-18 05:32:11 +0000380 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
Michael Gottesmanade30752013-08-20 08:56:28 +0000381 if (!RI)
382 continue;
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000383
Michael Gottesman236e3892013-08-09 21:26:18 +0000384 if (!HasPrologue) {
385 HasPrologue = true;
Josh Magee62406fd2013-10-30 02:25:14 +0000386 SupportsSelectionDAGSP &=
387 CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000388 }
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000389
Michael Gottesmand4f47882013-08-20 08:56:26 +0000390 if (SupportsSelectionDAGSP) {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000391 // Since we have a potential tail call, insert the special stack check
392 // intrinsic.
393 Instruction *InsertionPt = 0;
394 if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
395 InsertionPt = CI;
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000396 } else {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000397 InsertionPt = RI;
398 // At this point we know that BB has a return statement so it *DOES*
399 // have a terminator.
400 assert(InsertionPt != 0 && "BB must have a terminator instruction at "
Josh Magee62406fd2013-10-30 02:25:14 +0000401 "this point.");
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000402 }
403
404 Function *Intrinsic =
Josh Magee62406fd2013-10-30 02:25:14 +0000405 Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000406 CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000407
408 } else {
Michael Gottesman47d6e072013-08-20 08:46:13 +0000409 // If we do not support SelectionDAG based tail calls, generate IR level
410 // tail calls.
411 //
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000412 // For each block with a return instruction, convert this:
413 //
414 // return:
415 // ...
416 // ret ...
417 //
418 // into this:
419 //
420 // return:
421 // ...
422 // %1 = load __stack_chk_guard
423 // %2 = load StackGuardSlot
424 // %3 = cmp i1 %1, %2
425 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
426 //
427 // SP_return:
428 // ret ...
429 //
430 // CallStackCheckFailBlk:
431 // call void @__stack_chk_fail()
432 // unreachable
433
434 // Create the FailBB. We duplicate the BB every time since the MI tail
435 // merge pass will merge together all of the various BB into one including
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000436 // fail BB generated by the stack protector pseudo instruction.
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000437 BasicBlock *FailBB = CreateFailBB();
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000438
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000439 // Split the basic block before the return instruction.
440 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000441
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000442 // Update the dominator tree if we need to.
443 if (DT && DT->isReachableFromEntry(BB)) {
444 DT->addNewBlock(NewBB, BB);
445 DT->addNewBlock(FailBB, BB);
446 }
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000447
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000448 // Remove default branch instruction to the new BB.
449 BB->getTerminator()->eraseFromParent();
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000450
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000451 // Move the newly created basic block to the point right after the old
452 // basic block so that it's in the "fall through" position.
453 NewBB->moveAfter(BB);
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000454
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000455 // Generate the stack protector instructions in the old basic block.
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000456 IRBuilder<> B(BB);
457 LoadInst *LI1 = B.CreateLoad(StackGuardVar);
458 LoadInst *LI2 = B.CreateLoad(AI);
459 Value *Cmp = B.CreateICmpEQ(LI1, LI2);
460 B.CreateCondBr(Cmp, NewBB, FailBB);
Bill Wendling1fb615f2008-11-06 23:55:49 +0000461 }
Bill Wendling2b58ce52008-11-04 02:10:20 +0000462 }
Bill Wendling613f7742008-11-05 00:00:21 +0000463
Bill Wendling1fb615f2008-11-06 23:55:49 +0000464 // Return if we didn't modify any basic blocks. I.e., there are no return
465 // statements in the function.
Michael Gottesman236e3892013-08-09 21:26:18 +0000466 if (!HasPrologue)
467 return false;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000468
Bill Wendling613f7742008-11-05 00:00:21 +0000469 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000470}
471
472/// CreateFailBB - Create a basic block to jump to when the stack protector
473/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000474BasicBlock *StackProtector::CreateFailBB() {
Rafael Espindola62ed8d32013-06-07 16:35:57 +0000475 LLVMContext &Context = F->getContext();
476 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000477 IRBuilder<> B(FailBB);
Rafael Espindola62ed8d32013-06-07 16:35:57 +0000478 if (Trip.getOS() == llvm::Triple::OpenBSD) {
479 Constant *StackChkFail = M->getOrInsertFunction(
480 "__stack_smash_handler", Type::getVoidTy(Context),
481 Type::getInt8PtrTy(Context), NULL);
482
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000483 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
Rafael Espindola62ed8d32013-06-07 16:35:57 +0000484 } else {
485 Constant *StackChkFail = M->getOrInsertFunction(
486 "__stack_chk_fail", Type::getVoidTy(Context), NULL);
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000487 B.CreateCall(StackChkFail);
Rafael Espindola62ed8d32013-06-07 16:35:57 +0000488 }
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000489 B.CreateUnreachable();
Bill Wendling613f7742008-11-05 00:00:21 +0000490 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000491}