blob: 45f97acaeacffe2348502245c20b02262a2821b6 [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
Josh Magee18ebd482013-09-27 21:58:43 +000017#include "llvm/CodeGen/StackProtector.h"
Bill Wendlinge4957fb2013-01-23 06:43:53 +000018#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/Statistic.h"
Michael Gottesman3480d1b2013-08-20 08:36:53 +000020#include "llvm/Analysis/ValueTracking.h"
Stephen Hines36b56882014-04-23 16:57:46 -070021#include "llvm/CodeGen/Analysis.h"
22#include "llvm/CodeGen/Passes.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000023#include "llvm/IR/Attributes.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/Function.h"
Rafael Espindola62ed8d32013-06-07 16:35:57 +000028#include "llvm/IR/GlobalValue.h"
29#include "llvm/IR/GlobalVariable.h"
Benjamin Kramer54cf1412013-09-09 17:38:01 +000030#include "llvm/IR/IRBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000031#include "llvm/IR/Instructions.h"
Michael Gottesman3480d1b2013-08-20 08:36:53 +000032#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000033#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/Module.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000035#include "llvm/Support/CommandLine.h"
Stephen Hines37ed9c12014-12-01 14:51:49 -080036#include "llvm/Target/TargetSubtargetInfo.h"
Bill Wendling0dcba2f2013-07-22 20:15:21 +000037#include <cstdlib>
Bill Wendling2b58ce52008-11-04 02:10:20 +000038using namespace llvm;
39
Stephen Hinesdce4a402014-05-29 02:49:00 -070040#define DEBUG_TYPE "stack-protector"
41
Bill Wendlinge4957fb2013-01-23 06:43:53 +000042STATISTIC(NumFunProtected, "Number of functions protected");
43STATISTIC(NumAddrTaken, "Number of local variables that have their address"
44 " taken.");
45
Josh Magee62406fd2013-10-30 02:25:14 +000046static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
47 cl::init(true), cl::Hidden);
Michael Gottesman3480d1b2013-08-20 08:36:53 +000048
Bill Wendling2b58ce52008-11-04 02:10:20 +000049char StackProtector::ID = 0;
Josh Magee62406fd2013-10-30 02:25:14 +000050INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
51 false, true)
Bill Wendling2b58ce52008-11-04 02:10:20 +000052
Bill Wendlingea442812013-06-19 20:51:24 +000053FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
54 return new StackProtector(TM);
Bill Wendling2b58ce52008-11-04 02:10:20 +000055}
56
Josh Magee62406fd2013-10-30 02:25:14 +000057StackProtector::SSPLayoutKind
58StackProtector::getSSPLayout(const AllocaInst *AI) const {
Josh Magee4598b402013-10-29 21:16:16 +000059 return AI ? Layout.lookup(AI) : SSPLK_None;
60}
61
Stephen Hines36b56882014-04-23 16:57:46 -070062void StackProtector::adjustForColoring(const AllocaInst *From,
63 const AllocaInst *To) {
64 // When coloring replaces one alloca with another, transfer the SSPLayoutKind
65 // tag from the remapped to the target alloca. The remapped alloca should
66 // have a size smaller than or equal to the replacement alloca.
67 SSPLayoutMap::iterator I = Layout.find(From);
68 if (I != Layout.end()) {
69 SSPLayoutKind Kind = I->second;
70 Layout.erase(I);
71
72 // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
73 // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
74 // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
75 I = Layout.find(To);
76 if (I == Layout.end())
77 Layout.insert(std::make_pair(To, Kind));
78 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
79 I->second = Kind;
80 }
81}
82
Bill Wendling2b58ce52008-11-04 02:10:20 +000083bool StackProtector::runOnFunction(Function &Fn) {
84 F = &Fn;
85 M = F->getParent();
Stephen Hines36b56882014-04-23 16:57:46 -070086 DominatorTreeWrapperPass *DTWP =
87 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Stephen Hinesdce4a402014-05-29 02:49:00 -070088 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Stephen Hines37ed9c12014-12-01 14:51:49 -080089 TLI = TM->getSubtargetImpl()->getTargetLowering();
Bill Wendling2b58ce52008-11-04 02:10:20 +000090
Josh Magee62406fd2013-10-30 02:25:14 +000091 Attribute Attr = Fn.getAttributes().getAttribute(
92 AttributeSet::FunctionIndex, "stack-protector-buffer-size");
Stephen Hines36b56882014-04-23 16:57:46 -070093 if (Attr.isStringAttribute() &&
94 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
95 return false; // Invalid integer string
Bill Wendling0dcba2f2013-07-22 20:15:21 +000096
Stephen Hinesdce4a402014-05-29 02:49:00 -070097 if (!RequiresStackProtector())
98 return false;
99
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000100 ++NumFunProtected;
Bill Wendling613f7742008-11-05 00:00:21 +0000101 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000102}
103
Josh Magee4598b402013-10-29 21:16:16 +0000104/// \param [out] IsLarge is set to true if a protectable array is found and
105/// it is "large" ( >= ssp-buffer-size). In the case of a structure with
106/// multiple arrays, this gets set if any of them is large.
107bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
Josh Magee62406fd2013-10-30 02:25:14 +0000108 bool Strong,
109 bool InStruct) const {
110 if (!Ty)
111 return false;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000112 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
113 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlinga67eda72012-08-17 20:59:56 +0000114 // If we're on a non-Darwin platform or we're inside of a structure, don't
115 // add stack protectors unless the array is a character array.
Josh Magee4598b402013-10-29 21:16:16 +0000116 // However, in strong mode any array, regardless of type and size,
117 // triggers a protector.
118 if (!Strong && (InStruct || !Trip.isOSDarwin()))
119 return false;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000120 }
121
122 // If an array has more than SSPBufferSize bytes of allocated space, then we
123 // emit stack protectors.
Josh Magee4598b402013-10-29 21:16:16 +0000124 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
125 IsLarge = true;
126 return true;
Josh Magee62406fd2013-10-30 02:25:14 +0000127 }
Josh Magee4598b402013-10-29 21:16:16 +0000128
129 if (Strong)
130 // Require a protector for all arrays in strong mode
Bill Wendlinga67eda72012-08-17 20:59:56 +0000131 return true;
132 }
133
134 const StructType *ST = dyn_cast<StructType>(Ty);
Josh Magee62406fd2013-10-30 02:25:14 +0000135 if (!ST)
136 return false;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000137
Josh Magee4598b402013-10-29 21:16:16 +0000138 bool NeedsProtector = false;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000139 for (StructType::element_iterator I = ST->element_begin(),
Josh Magee62406fd2013-10-30 02:25:14 +0000140 E = ST->element_end();
141 I != E; ++I)
Josh Magee4598b402013-10-29 21:16:16 +0000142 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
143 // If the element is a protectable array and is large (>= SSPBufferSize)
144 // then we are done. If the protectable array is not large, then
145 // keep looking in case a subsequent element is a large array.
146 if (IsLarge)
147 return true;
148 NeedsProtector = true;
149 }
Bill Wendlinga67eda72012-08-17 20:59:56 +0000150
Josh Magee4598b402013-10-29 21:16:16 +0000151 return NeedsProtector;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000152}
153
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000154bool StackProtector::HasAddressTaken(const Instruction *AI) {
Stephen Hines36b56882014-04-23 16:57:46 -0700155 for (const User *U : AI->users()) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000156 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.
Stephen Hines37ed9c12014-12-01 14:51:49 -0800172 if (VisitedPHIs.insert(PN).second)
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000173 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 Magee4598b402013-10-29 21:16:16 +0000201 bool NeedsProtector = false;
Bill Wendling831737d2012-12-30 10:32:01 +0000202 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Josh Magee4598b402013-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 Wendlinge4957fb2013-01-23 06:43:53 +0000208 Strong = true;
209 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
210 Attribute::StackProtect))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000211 return false;
212
Bill Wendlingc3348a72008-11-18 05:32:11 +0000213 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
214 BasicBlock *BB = I;
215
Josh Magee62406fd2013-10-30 02:25:14 +0000216 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
217 ++II) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000218 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
Bill Wendlinge4957fb2013-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 Gottesmanc02dbeb2013-08-20 08:46:16 +0000224
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000225 if (const ConstantInt *CI =
Josh Magee62406fd2013-10-30 02:25:14 +0000226 dyn_cast<ConstantInt>(AI->getArraySize())) {
Josh Magee4598b402013-10-29 21:16:16 +0000227 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000228 // A call to alloca with size >= SSPBufferSize requires
229 // stack protectors.
Josh Magee4598b402013-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 Wendling0dcba2f2013-07-22 20:15:21 +0000237 } else {
238 // A call to alloca with a variable size requires protectors.
Josh Magee4598b402013-10-29 21:16:16 +0000239 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
240 NeedsProtector = true;
Bill Wendling0dcba2f2013-07-22 20:15:21 +0000241 }
Josh Magee4598b402013-10-29 21:16:16 +0000242 continue;
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000243 }
244
Josh Magee4598b402013-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 Wendlingc3348a72008-11-18 05:32:11 +0000252
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000253 if (Strong && HasAddressTaken(AI)) {
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000254 ++NumAddrTaken;
Josh Magee4598b402013-10-29 21:16:16 +0000255 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
256 NeedsProtector = true;
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000257 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000258 }
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000259 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000260 }
261
Josh Magee4598b402013-10-29 21:16:16 +0000262 return NeedsProtector;
Bill Wendlingc3348a72008-11-18 05:32:11 +0000263}
264
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000265static bool InstructionWillNotHaveChain(const Instruction *I) {
266 return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
Josh Magee62406fd2013-10-30 02:25:14 +0000267 isSafeToSpeculativelyExecute(I);
Michael Gottesman3480d1b2013-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 Gottesmanb99272a2013-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 Gottesman3480d1b2013-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
Stephen Hines36b56882014-04-23 16:57:46 -0700287 for (BasicBlock::reverse_iterator I = std::next(BB->rbegin()), E = BB->rend();
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000288 I != E && SearchCounter < MaxSearch; ++I) {
289 Instruction *Inst = &*I;
290
291 // Skip over debug intrinsics and do not allow them to affect our MaxSearch
292 // counter.
293 if (isa<DbgInfoIntrinsic>(Inst))
294 continue;
295
296 // If we find a call and the following conditions are satisifed, then we
297 // have found a tail call that satisfies at least the target independent
298 // requirements of a tail call:
299 //
300 // 1. The call site has the tail marker.
301 //
302 // 2. The call site either will not cause the creation of a chain or if a
303 // chain is necessary there are no instructions in between the callsite and
304 // the call which would create an interposing chain.
305 //
306 // 3. The return type of the function does not impede tail call
307 // optimization.
308 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
309 if (CI->isTailCall() &&
310 (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
311 returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
312 return CI;
313 }
314
315 // If we did not find a call see if we have an instruction that may create
316 // an interposing chain.
Josh Magee62406fd2013-10-30 02:25:14 +0000317 NoInterposingChain =
318 NoInterposingChain && InstructionWillNotHaveChain(Inst);
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000319
320 // Increment max search.
321 SearchCounter++;
322 }
323
Stephen Hinesdce4a402014-05-29 02:49:00 -0700324 return nullptr;
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000325}
326
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000327/// Insert code into the entry block that stores the __stack_chk_guard
328/// variable onto the stack:
329///
330/// entry:
331/// StackGuardSlot = alloca i8*
332/// StackGuard = load __stack_chk_guard
333/// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
334///
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000335/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
336/// node.
337static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000338 const TargetLoweringBase *TLI, const Triple &Trip,
339 AllocaInst *&AI, Value *&StackGuardVar) {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000340 bool SupportsSelectionDAGSP = false;
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000341 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
342 unsigned AddressSpace, Offset;
343 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
344 Constant *OffsetVal =
Josh Magee62406fd2013-10-30 02:25:14 +0000345 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000346
Josh Magee62406fd2013-10-30 02:25:14 +0000347 StackGuardVar = ConstantExpr::getIntToPtr(
348 OffsetVal, PointerType::get(PtrTy, AddressSpace));
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000349 } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
350 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
351 cast<GlobalValue>(StackGuardVar)
Josh Magee62406fd2013-10-30 02:25:14 +0000352 ->setVisibility(GlobalValue::HiddenVisibility);
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000353 } else {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000354 SupportsSelectionDAGSP = true;
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000355 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000356 }
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000357
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000358 IRBuilder<> B(&F->getEntryBlock().front());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700359 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000360 LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
361 B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
362 AI);
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000363
364 return SupportsSelectionDAGSP;
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000365}
366
Bill Wendling613f7742008-11-05 00:00:21 +0000367/// InsertStackProtectors - Insert code into the prologue and epilogue of the
368/// function.
369///
370/// - The prologue code loads and stores the stack guard onto the stack.
371/// - The epilogue checks the value stored in the prologue against the original
372/// value. It calls __stack_chk_fail if they differ.
373bool StackProtector::InsertStackProtectors() {
Michael Gottesman236e3892013-08-09 21:26:18 +0000374 bool HasPrologue = false;
Michael Gottesmand4f47882013-08-20 08:56:26 +0000375 bool SupportsSelectionDAGSP =
Josh Magee62406fd2013-10-30 02:25:14 +0000376 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700377 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
378 Value *StackGuardVar = nullptr; // The stack guard variable.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000379
Josh Magee62406fd2013-10-30 02:25:14 +0000380 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000381 BasicBlock *BB = I++;
Bill Wendlingc3348a72008-11-18 05:32:11 +0000382 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
Michael Gottesmanade30752013-08-20 08:56:28 +0000383 if (!RI)
384 continue;
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000385
Michael Gottesman236e3892013-08-09 21:26:18 +0000386 if (!HasPrologue) {
387 HasPrologue = true;
Josh Magee62406fd2013-10-30 02:25:14 +0000388 SupportsSelectionDAGSP &=
389 CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000390 }
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000391
Michael Gottesmand4f47882013-08-20 08:56:26 +0000392 if (SupportsSelectionDAGSP) {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000393 // Since we have a potential tail call, insert the special stack check
394 // intrinsic.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700395 Instruction *InsertionPt = nullptr;
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000396 if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
397 InsertionPt = CI;
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000398 } else {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000399 InsertionPt = RI;
400 // At this point we know that BB has a return statement so it *DOES*
401 // have a terminator.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700402 assert(InsertionPt != nullptr && "BB must have a terminator instruction at "
Josh Magee62406fd2013-10-30 02:25:14 +0000403 "this point.");
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000404 }
405
406 Function *Intrinsic =
Josh Magee62406fd2013-10-30 02:25:14 +0000407 Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000408 CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000409
410 } else {
Michael Gottesman47d6e072013-08-20 08:46:13 +0000411 // If we do not support SelectionDAG based tail calls, generate IR level
412 // tail calls.
413 //
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000414 // For each block with a return instruction, convert this:
415 //
416 // return:
417 // ...
418 // ret ...
419 //
420 // into this:
421 //
422 // return:
423 // ...
424 // %1 = load __stack_chk_guard
425 // %2 = load StackGuardSlot
426 // %3 = cmp i1 %1, %2
427 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
428 //
429 // SP_return:
430 // ret ...
431 //
432 // CallStackCheckFailBlk:
433 // call void @__stack_chk_fail()
434 // unreachable
435
436 // Create the FailBB. We duplicate the BB every time since the MI tail
437 // merge pass will merge together all of the various BB into one including
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000438 // fail BB generated by the stack protector pseudo instruction.
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000439 BasicBlock *FailBB = CreateFailBB();
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000440
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000441 // Split the basic block before the return instruction.
442 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000443
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000444 // Update the dominator tree if we need to.
445 if (DT && DT->isReachableFromEntry(BB)) {
446 DT->addNewBlock(NewBB, BB);
447 DT->addNewBlock(FailBB, BB);
448 }
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000449
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000450 // Remove default branch instruction to the new BB.
451 BB->getTerminator()->eraseFromParent();
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000452
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000453 // Move the newly created basic block to the point right after the old
454 // basic block so that it's in the "fall through" position.
455 NewBB->moveAfter(BB);
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000456
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000457 // Generate the stack protector instructions in the old basic block.
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000458 IRBuilder<> B(BB);
459 LoadInst *LI1 = B.CreateLoad(StackGuardVar);
460 LoadInst *LI2 = B.CreateLoad(AI);
461 Value *Cmp = B.CreateICmpEQ(LI1, LI2);
462 B.CreateCondBr(Cmp, NewBB, FailBB);
Bill Wendling1fb615f2008-11-06 23:55:49 +0000463 }
Bill Wendling2b58ce52008-11-04 02:10:20 +0000464 }
Bill Wendling613f7742008-11-05 00:00:21 +0000465
Bill Wendling1fb615f2008-11-06 23:55:49 +0000466 // Return if we didn't modify any basic blocks. I.e., there are no return
467 // statements in the function.
Michael Gottesman236e3892013-08-09 21:26:18 +0000468 if (!HasPrologue)
469 return false;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000470
Bill Wendling613f7742008-11-05 00:00:21 +0000471 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000472}
473
474/// CreateFailBB - Create a basic block to jump to when the stack protector
475/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000476BasicBlock *StackProtector::CreateFailBB() {
Rafael Espindola62ed8d32013-06-07 16:35:57 +0000477 LLVMContext &Context = F->getContext();
478 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000479 IRBuilder<> B(FailBB);
Rafael Espindola62ed8d32013-06-07 16:35:57 +0000480 if (Trip.getOS() == llvm::Triple::OpenBSD) {
481 Constant *StackChkFail = M->getOrInsertFunction(
482 "__stack_smash_handler", Type::getVoidTy(Context),
Stephen Hines37ed9c12014-12-01 14:51:49 -0800483 Type::getInt8PtrTy(Context), nullptr);
Rafael Espindola62ed8d32013-06-07 16:35:57 +0000484
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000485 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
Rafael Espindola62ed8d32013-06-07 16:35:57 +0000486 } else {
487 Constant *StackChkFail = M->getOrInsertFunction(
Stephen Hines37ed9c12014-12-01 14:51:49 -0800488 "__stack_chk_fail", Type::getVoidTy(Context), nullptr);
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000489 B.CreateCall(StackChkFail);
Rafael Espindola62ed8d32013-06-07 16:35:57 +0000490 }
Benjamin Kramer54cf1412013-09-09 17:38:01 +0000491 B.CreateUnreachable();
Bill Wendling613f7742008-11-05 00:00:21 +0000492 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000493}