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