blob: 349b733418e9bd915838de82c9a6c83359403e51 [file] [log] [blame]
Bill Wendling05d84172008-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 Wendling64adc712008-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 Wendling05d84172008-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 Magee8ecfb522013-09-27 21:58:43 +000018#include "llvm/CodeGen/StackProtector.h"
Bill Wendling7c8f96a2013-01-23 06:43:53 +000019#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/Statistic.h"
Michael Gottesman5e570682013-08-20 08:36:53 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/CodeGen/Analysis.h"
23#include "llvm/CodeGen/Passes.h"
Chandler Carruth9fb823b2013-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 Espindolaaad6c242013-06-07 16:35:57 +000029#include "llvm/IR/GlobalValue.h"
30#include "llvm/IR/GlobalVariable.h"
Benjamin Kramerd93817f2013-09-09 17:38:01 +000031#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Instructions.h"
Michael Gottesman5e570682013-08-20 08:36:53 +000033#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Module.h"
Bill Wendling05d84172008-11-04 02:10:20 +000036#include "llvm/Support/CommandLine.h"
Bill Wendlingc02a0aa2013-07-22 20:15:21 +000037#include <cstdlib>
Bill Wendling05d84172008-11-04 02:10:20 +000038using namespace llvm;
39
Bill Wendling7c8f96a2013-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 Magee7245f1d2013-10-30 02:25:14 +000044static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
45 cl::init(true), cl::Hidden);
Michael Gottesman5e570682013-08-20 08:36:53 +000046
Bill Wendling05d84172008-11-04 02:10:20 +000047char StackProtector::ID = 0;
Josh Magee7245f1d2013-10-30 02:25:14 +000048INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
49 false, true)
Bill Wendling05d84172008-11-04 02:10:20 +000050
Bill Wendlingafc10362013-06-19 20:51:24 +000051FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
52 return new StackProtector(TM);
Bill Wendling05d84172008-11-04 02:10:20 +000053}
54
Josh Magee7245f1d2013-10-30 02:25:14 +000055StackProtector::SSPLayoutKind
56StackProtector::getSSPLayout(const AllocaInst *AI) const {
Josh Magee3f1c0e32013-10-29 21:16:16 +000057 return AI ? Layout.lookup(AI) : SSPLK_None;
58}
59
Hal Finkela69e5b82014-01-20 19:49:14 +000060void 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 Wendling05d84172008-11-04 02:10:20 +000081bool StackProtector::runOnFunction(Function &Fn) {
82 F = &Fn;
83 M = F->getParent();
Chandler Carruth73523022014-01-13 13:07:17 +000084 DominatorTreeWrapperPass *DTWP =
85 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
86 DT = DTWP ? &DTWP->getDomTree() : 0;
Bill Wendlingafc10362013-06-19 20:51:24 +000087 TLI = TM->getTargetLowering();
Bill Wendling05d84172008-11-04 02:10:20 +000088
Josh Magee7245f1d2013-10-30 02:25:14 +000089 if (!RequiresStackProtector())
90 return false;
Bill Wendling49aeb5c2012-08-13 21:20:43 +000091
Josh Magee7245f1d2013-10-30 02:25:14 +000092 Attribute Attr = Fn.getAttributes().getAttribute(
93 AttributeSet::FunctionIndex, "stack-protector-buffer-size");
Renato Goline195f9c2014-01-21 10:24:35 +000094 if (Attr.isStringAttribute() &&
95 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
96 return false; // Invalid integer string
Bill Wendlingc02a0aa2013-07-22 20:15:21 +000097
Bill Wendling7c8f96a2013-01-23 06:43:53 +000098 ++NumFunProtected;
Bill Wendling782e8342008-11-05 00:00:21 +000099 return InsertStackProtectors();
Bill Wendling05d84172008-11-04 02:10:20 +0000100}
101
Josh Magee3f1c0e32013-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 Magee7245f1d2013-10-30 02:25:14 +0000106 bool Strong,
107 bool InStruct) const {
108 if (!Ty)
109 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000110 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
111 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlingbfb9b752012-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 Magee3f1c0e32013-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 Wendlingbfb9b752012-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 Magee3f1c0e32013-10-29 21:16:16 +0000122 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
123 IsLarge = true;
124 return true;
Josh Magee7245f1d2013-10-30 02:25:14 +0000125 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000126
127 if (Strong)
128 // Require a protector for all arrays in strong mode
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000129 return true;
130 }
131
132 const StructType *ST = dyn_cast<StructType>(Ty);
Josh Magee7245f1d2013-10-30 02:25:14 +0000133 if (!ST)
134 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000135
Josh Magee3f1c0e32013-10-29 21:16:16 +0000136 bool NeedsProtector = false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000137 for (StructType::element_iterator I = ST->element_begin(),
Josh Magee7245f1d2013-10-30 02:25:14 +0000138 E = ST->element_end();
139 I != E; ++I)
Josh Magee3f1c0e32013-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 Wendlingbfb9b752012-08-17 20:59:56 +0000148
Josh Magee3f1c0e32013-10-29 21:16:16 +0000149 return NeedsProtector;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000150}
151
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000152bool StackProtector::HasAddressTaken(const Instruction *AI) {
153 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
Josh Magee7245f1d2013-10-30 02:25:14 +0000154 UI != UE; ++UI) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000155 const User *U = *UI;
156 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
157 if (AI == SI->getValueOperand())
158 return true;
159 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
160 if (AI == SI->getOperand(0))
161 return true;
162 } else if (isa<CallInst>(U)) {
163 return true;
164 } else if (isa<InvokeInst>(U)) {
165 return true;
166 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
167 if (HasAddressTaken(SI))
168 return true;
169 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
170 // Keep track of what PHI nodes we have already visited to ensure
171 // they are only visited once.
172 if (VisitedPHIs.insert(PN))
173 if (HasAddressTaken(PN))
174 return true;
175 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
176 if (HasAddressTaken(GEP))
177 return true;
178 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
179 if (HasAddressTaken(BI))
180 return true;
181 }
182 }
183 return false;
184}
185
186/// \brief Check whether or not this function needs a stack protector based
187/// upon the stack protector level.
188///
189/// We use two heuristics: a standard (ssp) and strong (sspstrong).
190/// The standard heuristic which will add a guard variable to functions that
191/// call alloca with a either a variable size or a size >= SSPBufferSize,
192/// functions with character buffers larger than SSPBufferSize, and functions
193/// with aggregates containing character buffers larger than SSPBufferSize. The
194/// strong heuristic will add a guard variables to functions that call alloca
195/// regardless of size, functions with any buffer regardless of type and size,
196/// functions with aggregates that contain any buffer regardless of type and
197/// size, and functions that contain stack-based variables that have had their
198/// address taken.
199bool StackProtector::RequiresStackProtector() {
200 bool Strong = false;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000201 bool NeedsProtector = false;
Bill Wendling698e84f2012-12-30 10:32:01 +0000202 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Josh Magee3f1c0e32013-10-29 21:16:16 +0000203 Attribute::StackProtectReq)) {
204 NeedsProtector = true;
205 Strong = true; // Use the same heuristic as strong to determine SSPLayout
206 } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
207 Attribute::StackProtectStrong))
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000208 Strong = true;
209 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
210 Attribute::StackProtect))
Bill Wendlingeeb04152008-11-18 05:32:11 +0000211 return false;
212
Bill Wendlingeeb04152008-11-18 05:32:11 +0000213 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
214 BasicBlock *BB = I;
215
Josh Magee7245f1d2013-10-30 02:25:14 +0000216 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
217 ++II) {
Bill Wendlingeeb04152008-11-18 05:32:11 +0000218 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000219 if (AI->isArrayAllocation()) {
220 // SSP-Strong: Enable protectors for any call to alloca, regardless
221 // of size.
222 if (Strong)
223 return true;
Michael Gottesman62c5d712013-08-20 08:46:16 +0000224
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000225 if (const ConstantInt *CI =
Josh Magee7245f1d2013-10-30 02:25:14 +0000226 dyn_cast<ConstantInt>(AI->getArraySize())) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000227 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000228 // A call to alloca with size >= SSPBufferSize requires
229 // stack protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000230 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
231 NeedsProtector = true;
232 } else if (Strong) {
233 // Require protectors for all alloca calls in strong mode.
234 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
235 NeedsProtector = true;
236 }
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000237 } else {
238 // A call to alloca with a variable size requires protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000239 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
240 NeedsProtector = true;
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000241 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000242 continue;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000243 }
244
Josh Magee3f1c0e32013-10-29 21:16:16 +0000245 bool IsLarge = false;
246 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
247 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
248 : SSPLK_SmallArray));
249 NeedsProtector = true;
250 continue;
251 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000252
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000253 if (Strong && HasAddressTaken(AI)) {
Michael Gottesman62c5d712013-08-20 08:46:16 +0000254 ++NumAddrTaken;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000255 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
256 NeedsProtector = true;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000257 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000258 }
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000259 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000260 }
261
Josh Magee3f1c0e32013-10-29 21:16:16 +0000262 return NeedsProtector;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000263}
264
Michael Gottesman5e570682013-08-20 08:36:53 +0000265static bool InstructionWillNotHaveChain(const Instruction *I) {
266 return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
Josh Magee7245f1d2013-10-30 02:25:14 +0000267 isSafeToSpeculativelyExecute(I);
Michael Gottesman5e570682013-08-20 08:36:53 +0000268}
269
270/// Identify if RI has a previous instruction in the "Tail Position" and return
271/// it. Otherwise return 0.
272///
Michael Gottesman1977d152013-08-20 08:56:23 +0000273/// This is based off of the code in llvm::isInTailCallPosition. The difference
274/// is that it inverts the first part of llvm::isInTailCallPosition since
275/// isInTailCallPosition is checking if a call is in a tail call position, and
276/// we are searching for an unknown tail call that might be in the tail call
277/// position. Once we find the call though, the code uses the same refactored
278/// code, returnTypeIsEligibleForTailCall.
Michael Gottesman5e570682013-08-20 08:36:53 +0000279static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
280 const TargetLoweringBase *TLI) {
281 // Establish a reasonable upper bound on the maximum amount of instructions we
282 // will look through to find a tail call.
283 unsigned SearchCounter = 0;
284 const unsigned MaxSearch = 4;
285 bool NoInterposingChain = true;
286
Josh Magee7245f1d2013-10-30 02:25:14 +0000287 for (BasicBlock::reverse_iterator I = llvm::next(BB->rbegin()),
288 E = BB->rend();
Michael Gottesman5e570682013-08-20 08:36:53 +0000289 I != E && SearchCounter < MaxSearch; ++I) {
290 Instruction *Inst = &*I;
291
292 // Skip over debug intrinsics and do not allow them to affect our MaxSearch
293 // counter.
294 if (isa<DbgInfoIntrinsic>(Inst))
295 continue;
296
297 // If we find a call and the following conditions are satisifed, then we
298 // have found a tail call that satisfies at least the target independent
299 // requirements of a tail call:
300 //
301 // 1. The call site has the tail marker.
302 //
303 // 2. The call site either will not cause the creation of a chain or if a
304 // chain is necessary there are no instructions in between the callsite and
305 // the call which would create an interposing chain.
306 //
307 // 3. The return type of the function does not impede tail call
308 // optimization.
309 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
310 if (CI->isTailCall() &&
311 (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
312 returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
313 return CI;
314 }
315
316 // If we did not find a call see if we have an instruction that may create
317 // an interposing chain.
Josh Magee7245f1d2013-10-30 02:25:14 +0000318 NoInterposingChain =
319 NoInterposingChain && InstructionWillNotHaveChain(Inst);
Michael Gottesman5e570682013-08-20 08:36:53 +0000320
321 // Increment max search.
322 SearchCounter++;
323 }
324
325 return 0;
326}
327
Michael Gottesmana6188f92013-07-22 20:44:11 +0000328/// Insert code into the entry block that stores the __stack_chk_guard
329/// variable onto the stack:
330///
331/// entry:
332/// StackGuardSlot = alloca i8*
333/// StackGuard = load __stack_chk_guard
334/// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
335///
Michael Gottesman5e570682013-08-20 08:36:53 +0000336/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
337/// node.
338static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
Michael Gottesmana6188f92013-07-22 20:44:11 +0000339 const TargetLoweringBase *TLI, const Triple &Trip,
340 AllocaInst *&AI, Value *&StackGuardVar) {
Michael Gottesman5e570682013-08-20 08:36:53 +0000341 bool SupportsSelectionDAGSP = false;
Michael Gottesmana6188f92013-07-22 20:44:11 +0000342 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
343 unsigned AddressSpace, Offset;
344 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
345 Constant *OffsetVal =
Josh Magee7245f1d2013-10-30 02:25:14 +0000346 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000347
Josh Magee7245f1d2013-10-30 02:25:14 +0000348 StackGuardVar = ConstantExpr::getIntToPtr(
349 OffsetVal, PointerType::get(PtrTy, AddressSpace));
Michael Gottesmana6188f92013-07-22 20:44:11 +0000350 } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
351 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
352 cast<GlobalValue>(StackGuardVar)
Josh Magee7245f1d2013-10-30 02:25:14 +0000353 ->setVisibility(GlobalValue::HiddenVisibility);
Michael Gottesmana6188f92013-07-22 20:44:11 +0000354 } else {
Michael Gottesman5e570682013-08-20 08:36:53 +0000355 SupportsSelectionDAGSP = true;
Michael Gottesman62c5d712013-08-20 08:46:16 +0000356 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Michael Gottesmana6188f92013-07-22 20:44:11 +0000357 }
Michael Gottesman62c5d712013-08-20 08:46:16 +0000358
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000359 IRBuilder<> B(&F->getEntryBlock().front());
360 AI = B.CreateAlloca(PtrTy, 0, "StackGuardSlot");
361 LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
362 B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
363 AI);
Michael Gottesman5e570682013-08-20 08:36:53 +0000364
365 return SupportsSelectionDAGSP;
Michael Gottesmana6188f92013-07-22 20:44:11 +0000366}
367
Bill Wendling782e8342008-11-05 00:00:21 +0000368/// InsertStackProtectors - Insert code into the prologue and epilogue of the
369/// function.
370///
371/// - The prologue code loads and stores the stack guard onto the stack.
372/// - The epilogue checks the value stored in the prologue against the original
373/// value. It calls __stack_chk_fail if they differ.
374bool StackProtector::InsertStackProtectors() {
Michael Gottesman8afcf3a2013-08-09 21:26:18 +0000375 bool HasPrologue = false;
Michael Gottesman76c44be2013-08-20 08:56:26 +0000376 bool SupportsSelectionDAGSP =
Josh Magee7245f1d2013-10-30 02:25:14 +0000377 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
378 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
379 Value *StackGuardVar = 0; // The stack guard variable.
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000380
Josh Magee7245f1d2013-10-30 02:25:14 +0000381 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
Bill Wendlingeeb04152008-11-18 05:32:11 +0000382 BasicBlock *BB = I++;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000383 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
Michael Gottesmandc985ef2013-08-20 08:56:28 +0000384 if (!RI)
385 continue;
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000386
Michael Gottesman8afcf3a2013-08-09 21:26:18 +0000387 if (!HasPrologue) {
388 HasPrologue = true;
Josh Magee7245f1d2013-10-30 02:25:14 +0000389 SupportsSelectionDAGSP &=
390 CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000391 }
Michael Gottesman5e570682013-08-20 08:36:53 +0000392
Michael Gottesman76c44be2013-08-20 08:56:26 +0000393 if (SupportsSelectionDAGSP) {
Michael Gottesman5e570682013-08-20 08:36:53 +0000394 // Since we have a potential tail call, insert the special stack check
395 // intrinsic.
396 Instruction *InsertionPt = 0;
397 if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
398 InsertionPt = CI;
Michael Gottesman62c5d712013-08-20 08:46:16 +0000399 } else {
Michael Gottesman5e570682013-08-20 08:36:53 +0000400 InsertionPt = RI;
401 // At this point we know that BB has a return statement so it *DOES*
402 // have a terminator.
403 assert(InsertionPt != 0 && "BB must have a terminator instruction at "
Josh Magee7245f1d2013-10-30 02:25:14 +0000404 "this point.");
Michael Gottesman5e570682013-08-20 08:36:53 +0000405 }
406
407 Function *Intrinsic =
Josh Magee7245f1d2013-10-30 02:25:14 +0000408 Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000409 CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
Michael Gottesman5e570682013-08-20 08:36:53 +0000410
411 } else {
Michael Gottesman56e246b2013-08-20 08:46:13 +0000412 // If we do not support SelectionDAG based tail calls, generate IR level
413 // tail calls.
414 //
Michael Gottesman5e570682013-08-20 08:36:53 +0000415 // For each block with a return instruction, convert this:
416 //
417 // return:
418 // ...
419 // ret ...
420 //
421 // into this:
422 //
423 // return:
424 // ...
425 // %1 = load __stack_chk_guard
426 // %2 = load StackGuardSlot
427 // %3 = cmp i1 %1, %2
428 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
429 //
430 // SP_return:
431 // ret ...
432 //
433 // CallStackCheckFailBlk:
434 // call void @__stack_chk_fail()
435 // unreachable
436
437 // Create the FailBB. We duplicate the BB every time since the MI tail
438 // merge pass will merge together all of the various BB into one including
Michael Gottesman62c5d712013-08-20 08:46:16 +0000439 // fail BB generated by the stack protector pseudo instruction.
Michael Gottesman5e570682013-08-20 08:36:53 +0000440 BasicBlock *FailBB = CreateFailBB();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000441
Michael Gottesman5e570682013-08-20 08:36:53 +0000442 // Split the basic block before the return instruction.
443 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Michael Gottesman62c5d712013-08-20 08:46:16 +0000444
Michael Gottesman5e570682013-08-20 08:36:53 +0000445 // Update the dominator tree if we need to.
446 if (DT && DT->isReachableFromEntry(BB)) {
447 DT->addNewBlock(NewBB, BB);
448 DT->addNewBlock(FailBB, BB);
449 }
Michael Gottesman62c5d712013-08-20 08:46:16 +0000450
Michael Gottesman5e570682013-08-20 08:36:53 +0000451 // Remove default branch instruction to the new BB.
452 BB->getTerminator()->eraseFromParent();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000453
Michael Gottesman5e570682013-08-20 08:36:53 +0000454 // Move the newly created basic block to the point right after the old
455 // basic block so that it's in the "fall through" position.
456 NewBB->moveAfter(BB);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000457
Michael Gottesman5e570682013-08-20 08:36:53 +0000458 // Generate the stack protector instructions in the old basic block.
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000459 IRBuilder<> B(BB);
460 LoadInst *LI1 = B.CreateLoad(StackGuardVar);
461 LoadInst *LI2 = B.CreateLoad(AI);
462 Value *Cmp = B.CreateICmpEQ(LI1, LI2);
463 B.CreateCondBr(Cmp, NewBB, FailBB);
Bill Wendlinga0826e182008-11-06 23:55:49 +0000464 }
Bill Wendling05d84172008-11-04 02:10:20 +0000465 }
Bill Wendling782e8342008-11-05 00:00:21 +0000466
Bill Wendlinga0826e182008-11-06 23:55:49 +0000467 // Return if we didn't modify any basic blocks. I.e., there are no return
468 // statements in the function.
Michael Gottesman8afcf3a2013-08-09 21:26:18 +0000469 if (!HasPrologue)
470 return false;
Cameron Zwarich84986b22011-01-08 17:01:52 +0000471
Bill Wendling782e8342008-11-05 00:00:21 +0000472 return true;
Bill Wendling05d84172008-11-04 02:10:20 +0000473}
474
475/// CreateFailBB - Create a basic block to jump to when the stack protector
476/// check fails.
Bill Wendling782e8342008-11-05 00:00:21 +0000477BasicBlock *StackProtector::CreateFailBB() {
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000478 LLVMContext &Context = F->getContext();
479 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000480 IRBuilder<> B(FailBB);
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000481 if (Trip.getOS() == llvm::Triple::OpenBSD) {
482 Constant *StackChkFail = M->getOrInsertFunction(
483 "__stack_smash_handler", Type::getVoidTy(Context),
484 Type::getInt8PtrTy(Context), NULL);
485
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000486 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000487 } else {
488 Constant *StackChkFail = M->getOrInsertFunction(
489 "__stack_chk_fail", Type::getVoidTy(Context), NULL);
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000490 B.CreateCall(StackChkFail);
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000491 }
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000492 B.CreateUnreachable();
Bill Wendling782e8342008-11-05 00:00:21 +0000493 return FailBB;
Bill Wendling05d84172008-11-04 02:10:20 +0000494}