xref: /llvm-project/llvm/lib/CodeGen/StackProtector.cpp (revision c16a58b36caebbc34dfa0f788a019d041e5484df)
1 //===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass inserts stack protectors into functions which need them. A variable
10 // with a random value in it is stored onto the stack before the local variables
11 // are allocated. Upon exiting the block, the stored value is checked. If it's
12 // changed, then there was some sort of violation and the program aborts.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/CodeGen/StackProtector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/BranchProbabilityInfo.h"
20 #include "llvm/Analysis/EHPersonalities.h"
21 #include "llvm/Analysis/MemoryLocation.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/TargetLowering.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/Instruction.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/MDBuilder.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/User.h"
43 #include "llvm/InitializePasses.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include <optional>
51 #include <utility>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "stack-protector"
56 
57 STATISTIC(NumFunProtected, "Number of functions protected");
58 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
59                         " taken.");
60 
61 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
62                                           cl::init(true), cl::Hidden);
63 
64 char StackProtector::ID = 0;
65 
66 StackProtector::StackProtector() : FunctionPass(ID) {
67   initializeStackProtectorPass(*PassRegistry::getPassRegistry());
68 }
69 
70 INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
71                       "Insert stack protectors", false, true)
72 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
73 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
74 INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
75                     "Insert stack protectors", false, true)
76 
77 FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
78 
79 void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
80   AU.addRequired<TargetPassConfig>();
81   AU.addPreserved<DominatorTreeWrapperPass>();
82 }
83 
84 bool StackProtector::runOnFunction(Function &Fn) {
85   F = &Fn;
86   M = F->getParent();
87   if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
88     DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
89   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
90   Trip = TM->getTargetTriple();
91   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
92   HasPrologue = false;
93   HasIRCheck = false;
94 
95   SSPBufferSize = Fn.getFnAttributeAsParsedInteger(
96       "stack-protector-buffer-size", DefaultSSPBufferSize);
97   if (!RequiresStackProtector())
98     return false;
99 
100   // TODO(etienneb): Functions with funclets are not correctly supported now.
101   // Do nothing if this is funclet-based personality.
102   if (Fn.hasPersonalityFn()) {
103     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
104     if (isFuncletEHPersonality(Personality))
105       return false;
106   }
107 
108   ++NumFunProtected;
109   bool Changed = InsertStackProtectors();
110 #ifdef EXPENSIVE_CHECKS
111   assert((!DTU ||
112           DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full)) &&
113          "Failed to maintain validity of domtree!");
114 #endif
115   DTU.reset();
116   return Changed;
117 }
118 
119 /// \param [out] IsLarge is set to true if a protectable array is found and
120 /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
121 /// multiple arrays, this gets set if any of them is large.
122 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
123                                               bool Strong,
124                                               bool InStruct) const {
125   if (!Ty)
126     return false;
127   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
128     if (!AT->getElementType()->isIntegerTy(8)) {
129       // If we're on a non-Darwin platform or we're inside of a structure, don't
130       // add stack protectors unless the array is a character array.
131       // However, in strong mode any array, regardless of type and size,
132       // triggers a protector.
133       if (!Strong && (InStruct || !Trip.isOSDarwin()))
134         return false;
135     }
136 
137     // If an array has more than SSPBufferSize bytes of allocated space, then we
138     // emit stack protectors.
139     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
140       IsLarge = true;
141       return true;
142     }
143 
144     if (Strong)
145       // Require a protector for all arrays in strong mode
146       return true;
147   }
148 
149   const StructType *ST = dyn_cast<StructType>(Ty);
150   if (!ST)
151     return false;
152 
153   bool NeedsProtector = false;
154   for (Type *ET : ST->elements())
155     if (ContainsProtectableArray(ET, IsLarge, Strong, true)) {
156       // If the element is a protectable array and is large (>= SSPBufferSize)
157       // then we are done.  If the protectable array is not large, then
158       // keep looking in case a subsequent element is a large array.
159       if (IsLarge)
160         return true;
161       NeedsProtector = true;
162     }
163 
164   return NeedsProtector;
165 }
166 
167 bool StackProtector::HasAddressTaken(const Instruction *AI,
168                                      TypeSize AllocSize) {
169   const DataLayout &DL = M->getDataLayout();
170   for (const User *U : AI->users()) {
171     const auto *I = cast<Instruction>(U);
172     // If this instruction accesses memory make sure it doesn't access beyond
173     // the bounds of the allocated object.
174     std::optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I);
175     if (MemLoc && MemLoc->Size.hasValue() &&
176         !TypeSize::isKnownGE(AllocSize,
177                              TypeSize::getFixed(MemLoc->Size.getValue())))
178       return true;
179     switch (I->getOpcode()) {
180     case Instruction::Store:
181       if (AI == cast<StoreInst>(I)->getValueOperand())
182         return true;
183       break;
184     case Instruction::AtomicCmpXchg:
185       // cmpxchg conceptually includes both a load and store from the same
186       // location. So, like store, the value being stored is what matters.
187       if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
188         return true;
189       break;
190     case Instruction::PtrToInt:
191       if (AI == cast<PtrToIntInst>(I)->getOperand(0))
192         return true;
193       break;
194     case Instruction::Call: {
195       // Ignore intrinsics that do not become real instructions.
196       // TODO: Narrow this to intrinsics that have store-like effects.
197       const auto *CI = cast<CallInst>(I);
198       if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd())
199         return true;
200       break;
201     }
202     case Instruction::Invoke:
203       return true;
204     case Instruction::GetElementPtr: {
205       // If the GEP offset is out-of-bounds, or is non-constant and so has to be
206       // assumed to be potentially out-of-bounds, then any memory access that
207       // would use it could also be out-of-bounds meaning stack protection is
208       // required.
209       const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
210       unsigned IndexSize = DL.getIndexTypeSizeInBits(I->getType());
211       APInt Offset(IndexSize, 0);
212       if (!GEP->accumulateConstantOffset(DL, Offset))
213         return true;
214       TypeSize OffsetSize = TypeSize::Fixed(Offset.getLimitedValue());
215       if (!TypeSize::isKnownGT(AllocSize, OffsetSize))
216         return true;
217       // Adjust AllocSize to be the space remaining after this offset.
218       // We can't subtract a fixed size from a scalable one, so in that case
219       // assume the scalable value is of minimum size.
220       TypeSize NewAllocSize =
221           TypeSize::Fixed(AllocSize.getKnownMinValue()) - OffsetSize;
222       if (HasAddressTaken(I, NewAllocSize))
223         return true;
224       break;
225     }
226     case Instruction::BitCast:
227     case Instruction::Select:
228     case Instruction::AddrSpaceCast:
229       if (HasAddressTaken(I, AllocSize))
230         return true;
231       break;
232     case Instruction::PHI: {
233       // Keep track of what PHI nodes we have already visited to ensure
234       // they are only visited once.
235       const auto *PN = cast<PHINode>(I);
236       if (VisitedPHIs.insert(PN).second)
237         if (HasAddressTaken(PN, AllocSize))
238           return true;
239       break;
240     }
241     case Instruction::Load:
242     case Instruction::AtomicRMW:
243     case Instruction::Ret:
244       // These instructions take an address operand, but have load-like or
245       // other innocuous behavior that should not trigger a stack protector.
246       // atomicrmw conceptually has both load and store semantics, but the
247       // value being stored must be integer; so if a pointer is being stored,
248       // we'll catch it in the PtrToInt case above.
249       break;
250     default:
251       // Conservatively return true for any instruction that takes an address
252       // operand, but is not handled above.
253       return true;
254     }
255   }
256   return false;
257 }
258 
259 /// Search for the first call to the llvm.stackprotector intrinsic and return it
260 /// if present.
261 static const CallInst *findStackProtectorIntrinsic(Function &F) {
262   for (const BasicBlock &BB : F)
263     for (const Instruction &I : BB)
264       if (const auto *II = dyn_cast<IntrinsicInst>(&I))
265         if (II->getIntrinsicID() == Intrinsic::stackprotector)
266           return II;
267   return nullptr;
268 }
269 
270 /// Check whether or not this function needs a stack protector based
271 /// upon the stack protector level.
272 ///
273 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
274 /// The standard heuristic which will add a guard variable to functions that
275 /// call alloca with a either a variable size or a size >= SSPBufferSize,
276 /// functions with character buffers larger than SSPBufferSize, and functions
277 /// with aggregates containing character buffers larger than SSPBufferSize. The
278 /// strong heuristic will add a guard variables to functions that call alloca
279 /// regardless of size, functions with any buffer regardless of type and size,
280 /// functions with aggregates that contain any buffer regardless of type and
281 /// size, and functions that contain stack-based variables that have had their
282 /// address taken.
283 bool StackProtector::RequiresStackProtector() {
284   bool Strong = false;
285   bool NeedsProtector = false;
286 
287   if (F->hasFnAttribute(Attribute::SafeStack))
288     return false;
289 
290   // We are constructing the OptimizationRemarkEmitter on the fly rather than
291   // using the analysis pass to avoid building DominatorTree and LoopInfo which
292   // are not available this late in the IR pipeline.
293   OptimizationRemarkEmitter ORE(F);
294 
295   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
296     ORE.emit([&]() {
297       return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
298              << "Stack protection applied to function "
299              << ore::NV("Function", F)
300              << " due to a function attribute or command-line switch";
301     });
302     NeedsProtector = true;
303     Strong = true; // Use the same heuristic as strong to determine SSPLayout
304   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
305     Strong = true;
306   else if (!F->hasFnAttribute(Attribute::StackProtect))
307     return false;
308 
309   for (const BasicBlock &BB : *F) {
310     for (const Instruction &I : BB) {
311       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
312         if (AI->isArrayAllocation()) {
313           auto RemarkBuilder = [&]() {
314             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
315                                       &I)
316                    << "Stack protection applied to function "
317                    << ore::NV("Function", F)
318                    << " due to a call to alloca or use of a variable length "
319                       "array";
320           };
321           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
322             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
323               // A call to alloca with size >= SSPBufferSize requires
324               // stack protectors.
325               Layout.insert(std::make_pair(AI,
326                                            MachineFrameInfo::SSPLK_LargeArray));
327               ORE.emit(RemarkBuilder);
328               NeedsProtector = true;
329             } else if (Strong) {
330               // Require protectors for all alloca calls in strong mode.
331               Layout.insert(std::make_pair(AI,
332                                            MachineFrameInfo::SSPLK_SmallArray));
333               ORE.emit(RemarkBuilder);
334               NeedsProtector = true;
335             }
336           } else {
337             // A call to alloca with a variable size requires protectors.
338             Layout.insert(std::make_pair(AI,
339                                          MachineFrameInfo::SSPLK_LargeArray));
340             ORE.emit(RemarkBuilder);
341             NeedsProtector = true;
342           }
343           continue;
344         }
345 
346         bool IsLarge = false;
347         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
348           Layout.insert(std::make_pair(AI, IsLarge
349                                        ? MachineFrameInfo::SSPLK_LargeArray
350                                        : MachineFrameInfo::SSPLK_SmallArray));
351           ORE.emit([&]() {
352             return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
353                    << "Stack protection applied to function "
354                    << ore::NV("Function", F)
355                    << " due to a stack allocated buffer or struct containing a "
356                       "buffer";
357           });
358           NeedsProtector = true;
359           continue;
360         }
361 
362         if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize(
363                                               AI->getAllocatedType()))) {
364           ++NumAddrTaken;
365           Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
366           ORE.emit([&]() {
367             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
368                                       &I)
369                    << "Stack protection applied to function "
370                    << ore::NV("Function", F)
371                    << " due to the address of a local variable being taken";
372           });
373           NeedsProtector = true;
374         }
375         // Clear any PHIs that we visited, to make sure we examine all uses of
376         // any subsequent allocas that we look at.
377         VisitedPHIs.clear();
378       }
379     }
380   }
381 
382   return NeedsProtector;
383 }
384 
385 /// Create a stack guard loading and populate whether SelectionDAG SSP is
386 /// supported.
387 static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
388                             IRBuilder<> &B,
389                             bool *SupportsSelectionDAGSP = nullptr) {
390   Value *Guard = TLI->getIRStackGuard(B);
391   StringRef GuardMode = M->getStackProtectorGuard();
392   if ((GuardMode == "tls" || GuardMode.empty()) && Guard)
393     return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard");
394 
395   // Use SelectionDAG SSP handling, since there isn't an IR guard.
396   //
397   // This is more or less weird, since we optionally output whether we
398   // should perform a SelectionDAG SP here. The reason is that it's strictly
399   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
400   // mutating. There is no way to get this bit without mutating the IR, so
401   // getting this bit has to happen in this right time.
402   //
403   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
404   // will put more burden on the backends' overriding work, especially when it
405   // actually conveys the same information getIRStackGuard() already gives.
406   if (SupportsSelectionDAGSP)
407     *SupportsSelectionDAGSP = true;
408   TLI->insertSSPDeclarations(*M);
409   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
410 }
411 
412 /// Insert code into the entry block that stores the stack guard
413 /// variable onto the stack:
414 ///
415 ///   entry:
416 ///     StackGuardSlot = alloca i8*
417 ///     StackGuard = <stack guard>
418 ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
419 ///
420 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
421 /// node.
422 static bool CreatePrologue(Function *F, Module *M, Instruction *CheckLoc,
423                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
424   bool SupportsSelectionDAGSP = false;
425   IRBuilder<> B(&F->getEntryBlock().front());
426   PointerType *PtrTy = Type::getInt8PtrTy(CheckLoc->getContext());
427   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
428 
429   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
430   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
431                {GuardSlot, AI});
432   return SupportsSelectionDAGSP;
433 }
434 
435 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
436 /// function.
437 ///
438 ///  - The prologue code loads and stores the stack guard onto the stack.
439 ///  - The epilogue checks the value stored in the prologue against the original
440 ///    value. It calls __stack_chk_fail if they differ.
441 bool StackProtector::InsertStackProtectors() {
442   // If the target wants to XOR the frame pointer into the guard value, it's
443   // impossible to emit the check in IR, so the target *must* support stack
444   // protection in SDAG.
445   bool SupportsSelectionDAGSP =
446       TLI->useStackGuardXorFP() ||
447       (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
448   AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
449   BasicBlock *FailBB = nullptr;
450 
451   for (BasicBlock &BB : llvm::make_early_inc_range(*F)) {
452     // This is stack protector auto generated check BB, skip it.
453     if (&BB == FailBB)
454       continue;
455     Instruction *CheckLoc = dyn_cast<ReturnInst>(BB.getTerminator());
456     if (!CheckLoc) {
457       for (auto &Inst : BB) {
458         auto *CB = dyn_cast<CallBase>(&Inst);
459         if (!CB)
460           continue;
461         if (!CB->doesNotReturn())
462           continue;
463         // Do stack check before non-return calls (e.g: __cxa_throw)
464         CheckLoc = CB;
465         break;
466       }
467     }
468 
469     if (!CheckLoc)
470       continue;
471 
472     // Generate prologue instrumentation if not already generated.
473     if (!HasPrologue) {
474       HasPrologue = true;
475       SupportsSelectionDAGSP &= CreatePrologue(F, M, CheckLoc, TLI, AI);
476     }
477 
478     // SelectionDAG based code generation. Nothing else needs to be done here.
479     // The epilogue instrumentation is postponed to SelectionDAG.
480     if (SupportsSelectionDAGSP)
481       break;
482 
483     // Find the stack guard slot if the prologue was not created by this pass
484     // itself via a previous call to CreatePrologue().
485     if (!AI) {
486       const CallInst *SPCall = findStackProtectorIntrinsic(*F);
487       assert(SPCall && "Call to llvm.stackprotector is missing");
488       AI = cast<AllocaInst>(SPCall->getArgOperand(1));
489     }
490 
491     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
492     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
493     // instrumentation has already been generated.
494     HasIRCheck = true;
495 
496     // If we're instrumenting a block with a tail call, the check has to be
497     // inserted before the call rather than between it and the return. The
498     // verifier guarantees that a tail call is either directly before the
499     // return or with a single correct bitcast of the return value in between so
500     // we don't need to worry about many situations here.
501     Instruction *Prev = CheckLoc->getPrevNonDebugInstruction();
502     if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isTailCall())
503       CheckLoc = Prev;
504     else if (Prev) {
505       Prev = Prev->getPrevNonDebugInstruction();
506       if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isTailCall())
507         CheckLoc = Prev;
508     }
509 
510     // Generate epilogue instrumentation. The epilogue intrumentation can be
511     // function-based or inlined depending on which mechanism the target is
512     // providing.
513     if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
514       // Generate the function-based epilogue instrumentation.
515       // The target provides a guard check function, generate a call to it.
516       IRBuilder<> B(CheckLoc);
517       LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard");
518       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
519       Call->setAttributes(GuardCheck->getAttributes());
520       Call->setCallingConv(GuardCheck->getCallingConv());
521     } else {
522       // Generate the epilogue with inline instrumentation.
523       // If we do not support SelectionDAG based calls, generate IR level
524       // calls.
525       //
526       // For each block with a return instruction, convert this:
527       //
528       //   return:
529       //     ...
530       //     ret ...
531       //
532       // into this:
533       //
534       //   return:
535       //     ...
536       //     %1 = <stack guard>
537       //     %2 = load StackGuardSlot
538       //     %3 = icmp ne i1 %1, %2
539       //     br i1 %3, label %CallStackCheckFailBlk, label %SP_return
540       //
541       //   SP_return:
542       //     ret ...
543       //
544       //   CallStackCheckFailBlk:
545       //     call void @__stack_chk_fail()
546       //     unreachable
547 
548       // Create the FailBB. We duplicate the BB every time since the MI tail
549       // merge pass will merge together all of the various BB into one including
550       // fail BB generated by the stack protector pseudo instruction.
551       if (!FailBB)
552         FailBB = CreateFailBB();
553 
554       IRBuilder<> B(CheckLoc);
555       Value *Guard = getStackGuard(TLI, M, B);
556       LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
557       auto *Cmp = cast<ICmpInst>(B.CreateICmpNE(Guard, LI2));
558       auto SuccessProb =
559           BranchProbabilityInfo::getBranchProbStackProtector(true);
560       auto FailureProb =
561           BranchProbabilityInfo::getBranchProbStackProtector(false);
562       MDNode *Weights = MDBuilder(F->getContext())
563                             .createBranchWeights(FailureProb.getNumerator(),
564                                                  SuccessProb.getNumerator());
565 
566       SplitBlockAndInsertIfThen(Cmp, CheckLoc,
567                                 /*Unreachable=*/false, Weights,
568                                 DTU ? &*DTU : nullptr,
569                                 /*LI=*/nullptr, /*ThenBlock=*/FailBB);
570 
571       auto *BI = cast<BranchInst>(Cmp->getParent()->getTerminator());
572       BasicBlock *NewBB = BI->getSuccessor(1);
573       NewBB->setName("SP_return");
574       NewBB->moveAfter(&BB);
575 
576       Cmp->setPredicate(Cmp->getInversePredicate());
577       BI->swapSuccessors();
578     }
579   }
580 
581   // Return if we didn't modify any basic blocks. i.e., there are no return
582   // statements in the function.
583   return HasPrologue;
584 }
585 
586 /// CreateFailBB - Create a basic block to jump to when the stack protector
587 /// check fails.
588 BasicBlock *StackProtector::CreateFailBB() {
589   LLVMContext &Context = F->getContext();
590   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
591   IRBuilder<> B(FailBB);
592   if (F->getSubprogram())
593     B.SetCurrentDebugLocation(
594         DILocation::get(Context, 0, 0, F->getSubprogram()));
595   if (Trip.isOSOpenBSD()) {
596     FunctionCallee StackChkFail = M->getOrInsertFunction(
597         "__stack_smash_handler", Type::getVoidTy(Context),
598         Type::getInt8PtrTy(Context));
599 
600     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
601   } else {
602     FunctionCallee StackChkFail =
603         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
604 
605     B.CreateCall(StackChkFail, {});
606   }
607   B.CreateUnreachable();
608   return FailBB;
609 }
610 
611 bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
612   return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
613 }
614 
615 void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
616   if (Layout.empty())
617     return;
618 
619   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
620     if (MFI.isDeadObjectIndex(I))
621       continue;
622 
623     const AllocaInst *AI = MFI.getObjectAllocation(I);
624     if (!AI)
625       continue;
626 
627     SSPLayoutMap::const_iterator LI = Layout.find(AI);
628     if (LI == Layout.end())
629       continue;
630 
631     MFI.setObjectSSPLayout(I, LI->second);
632   }
633 }
634