LLVM 24.0.0git
StackProtector.cpp
Go to the documentation of this file.
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
17#include "CodeGenOptions.h"
19#include "llvm/ADT/Statistic.h"
24#include "llvm/CodeGen/Passes.h"
28#include "llvm/IR/Attributes.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Dominators.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/IRBuilder.h"
37#include "llvm/IR/Instruction.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"
46#include "llvm/Pass.h"
51#include <optional>
52
53using namespace llvm;
54
55#define DEBUG_TYPE "stack-protector"
56
57STATISTIC(NumFunProtected, "Number of functions protected");
58STATISTIC(NumAddrTaken, "Number of local variables that have their address"
59 " taken.");
60
61/// InsertStackProtectors - Insert code into the prologue and epilogue of the
62/// function.
63///
64/// - The prologue code loads and stores the stack guard onto the stack.
65/// - The epilogue checks the value stored in the prologue against the original
66/// value. It calls __stack_chk_fail if they differ.
68 const LibcallLoweringInfo &Libcalls,
70 bool &HasPrologue, bool &HasIRCheck);
71
72/// CreateFailBB - Create a basic block to jump to when the stack protector
73/// check fails.
75 const LibcallLoweringInfo &Libcalls);
76
78 return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
79}
80
82 if (Layout.empty())
83 return;
84
85 for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
86 if (MFI.isDeadObjectIndex(I))
87 continue;
88
89 const AllocaInst *AI = MFI.getObjectAllocation(I);
90 if (!AI)
91 continue;
92
93 SSPLayoutMap::const_iterator LI = Layout.find(AI);
94 if (LI == Layout.end())
95 continue;
96
97 MFI.setObjectSSPLayout(I, LI->second);
98 }
99}
100
103
104 SSPLayoutInfo Info;
105 Info.RequireStackProtector =
107 return Info;
108}
109
110AnalysisKey SSPLayoutAnalysis::Key;
111
114 auto &Info = FAM.getResult<SSPLayoutAnalysis>(F);
115 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
116 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
117
118 if (!Info.RequireStackProtector)
119 return PreservedAnalyses::all();
120
121 // TODO(etienneb): Functions with funclets are not correctly supported now.
122 // Do nothing if this is funclet-based personality.
123 if (F.hasPersonalityFn()) {
124 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
125 if (isFuncletEHPersonality(Personality))
126 return PreservedAnalyses::all();
127 }
128
129 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
130 const ModuleLibcallLoweringInfo *LibcallLowering =
131 MAMProxy.getCachedResult<LibcallLoweringModuleAnalysis>(*F.getParent());
132
133 if (!LibcallLowering) {
134 F.getContext().emitError("'" + LibcallLoweringModuleAnalysis::name() +
135 "' analysis required");
136 return PreservedAnalyses::all();
137 }
138
139 const TargetSubtargetInfo *STI = TM->getSubtargetImpl(F);
140 const TargetLowering *TLI = STI->getTargetLowering();
141 const LibcallLoweringInfo &Libcalls =
142 getLibcallLowering(*LibcallLowering, *STI);
143
144 ++NumFunProtected;
145 bool Changed = InsertStackProtectors(*TLI, Libcalls, &F, DT ? &DTU : nullptr,
146 Info.HasPrologue, Info.HasIRCheck);
147#ifdef EXPENSIVE_CHECKS
148 assert((!DT ||
149 DTU.getDomTree().verify(DominatorTree::VerificationLevel::Full)) &&
150 "Failed to maintain validity of domtree!");
151#endif
152
153 if (!Changed)
154 return PreservedAnalyses::all();
158 return PA;
159}
160
161char StackProtector::ID = 0;
162
164
166 "Insert stack protectors", false, true)
171 "Insert stack protectors", false, true)
172
174
180
182 F = &Fn;
183 M = F->getParent();
185 DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
187 LayoutInfo.HasPrologue = false;
188 LayoutInfo.HasIRCheck = false;
189
190 if (!requiresStackProtector(F, &LayoutInfo.Layout))
191 return false;
192
193 // TODO(etienneb): Functions with funclets are not correctly supported now.
194 // Do nothing if this is funclet-based personality.
195 if (Fn.hasPersonalityFn()) {
197 if (isFuncletEHPersonality(Personality))
198 return false;
199 }
200
201 const TargetSubtargetInfo *Subtarget = TM->getSubtargetImpl(Fn);
202 const LibcallLoweringInfo &Libcalls =
203 getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(*M,
204 *Subtarget);
205
206 const TargetLowering *TLI = Subtarget->getTargetLowering();
207
208 ++NumFunProtected;
209 bool Changed =
210 InsertStackProtectors(*TLI, Libcalls, F, DTU ? &*DTU : nullptr,
211 LayoutInfo.HasPrologue, LayoutInfo.HasIRCheck);
212#ifdef EXPENSIVE_CHECKS
213 assert((!DTU ||
214 DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full)) &&
215 "Failed to maintain validity of domtree!");
216#endif
217 DTU.reset();
218 return Changed;
219}
220
221/// \param [out] IsLarge is set to true if a protectable array is found and
222/// it is "large" ( >= ssp-buffer-size). In the case of a structure with
223/// multiple arrays, this gets set if any of them is large.
224static bool ContainsProtectableArray(Type *Ty, Module *M, unsigned SSPBufferSize,
225 bool &IsLarge, bool Strong,
226 bool InStruct) {
227 if (!Ty)
228 return false;
229 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
230 if (!AT->getElementType()->isIntegerTy(8)) {
231 // If we're on a non-Darwin platform or we're inside of a structure, don't
232 // add stack protectors unless the array is a character array.
233 // However, in strong mode any array, regardless of type and size,
234 // triggers a protector.
235 if (!Strong && (InStruct || !M->getTargetTriple().isOSDarwin()))
236 return false;
237 }
238
239 // If an array has more than SSPBufferSize bytes of allocated space, then we
240 // emit stack protectors.
241 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
242 IsLarge = true;
243 return true;
244 }
245
246 if (Strong)
247 // Require a protector for all arrays in strong mode
248 return true;
249 }
250
251 const StructType *ST = dyn_cast<StructType>(Ty);
252 if (!ST)
253 return false;
254
255 bool NeedsProtector = false;
256 for (Type *ET : ST->elements())
257 if (ContainsProtectableArray(ET, M, SSPBufferSize, IsLarge, Strong, true)) {
258 // If the element is a protectable array and is large (>= SSPBufferSize)
259 // then we are done. If the protectable array is not large, then
260 // keep looking in case a subsequent element is a large array.
261 if (IsLarge)
262 return true;
263 NeedsProtector = true;
264 }
265
266 return NeedsProtector;
267}
268
269/// Maximum remaining allocation size observed for a phi node, and how often
270/// the allocation size has already been decreased. We only allow a limited
271/// number of decreases.
272struct PhiInfo {
274 unsigned NumDecreased = 0;
275 static constexpr unsigned MaxNumDecreased = 3;
277};
279
280/// Check whether a stack allocation has its address taken.
281static bool HasAddressTaken(const Instruction *AI, TypeSize AllocSize,
282 Module *M,
283 PhiMap &VisitedPHIs) {
284 const DataLayout &DL = M->getDataLayout();
285 for (const Instruction *I : AI->users()) {
286 // If this instruction accesses memory make sure it doesn't access beyond
287 // the bounds of the allocated object.
288 std::optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I);
289 if (MemLoc && MemLoc->Size.hasValue() &&
290 !TypeSize::isKnownGE(AllocSize, MemLoc->Size.getValue()))
291 return true;
292 switch (I->getOpcode()) {
293 case Instruction::Store:
294 if (AI == cast<StoreInst>(I)->getValueOperand())
295 return true;
296 break;
297 case Instruction::AtomicCmpXchg:
298 // cmpxchg conceptually includes both a load and store from the same
299 // location. So, like store, the value being stored is what matters.
300 if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
301 return true;
302 break;
303 case Instruction::AtomicRMW:
304 if (AI == cast<AtomicRMWInst>(I)->getValOperand())
305 return true;
306 break;
307 case Instruction::PtrToInt:
308 if (AI == cast<PtrToIntInst>(I)->getOperand(0))
309 return true;
310 break;
311 case Instruction::Call: {
312 // Ignore intrinsics that do not become real instructions.
313 // TODO: Narrow this to intrinsics that have store-like effects.
314 const auto *CI = cast<CallInst>(I);
315 if (!isa<PseudoProbeInst>(CI) && !CI->isLifetimeStartOrEnd())
316 return true;
317 break;
318 }
319 case Instruction::Invoke:
320 return true;
321 case Instruction::GetElementPtr: {
322 // If the GEP offset is out-of-bounds, or is non-constant and so has to be
323 // assumed to be potentially out-of-bounds, then any memory access that
324 // would use it could also be out-of-bounds meaning stack protection is
325 // required.
327 unsigned IndexSize = DL.getIndexTypeSizeInBits(I->getType());
328 APInt Offset(IndexSize, 0);
329 if (!GEP->accumulateConstantOffset(DL, Offset))
330 return true;
331 TypeSize OffsetSize = TypeSize::getFixed(Offset.getLimitedValue());
332 if (!TypeSize::isKnownGT(AllocSize, OffsetSize))
333 return true;
334 // Adjust AllocSize to be the space remaining after this offset.
335 // We can't subtract a fixed size from a scalable one, so in that case
336 // assume the scalable value is of minimum size.
337 TypeSize NewAllocSize =
338 TypeSize::getFixed(AllocSize.getKnownMinValue()) - OffsetSize;
339 if (HasAddressTaken(I, NewAllocSize, M, VisitedPHIs))
340 return true;
341 break;
342 }
343 case Instruction::BitCast:
344 case Instruction::Select:
345 case Instruction::AddrSpaceCast:
346 if (HasAddressTaken(I, AllocSize, M, VisitedPHIs))
347 return true;
348 break;
349 case Instruction::PHI: {
350 // Keep track of what PHI nodes we have already visited to ensure
351 // they are only visited once.
352 const auto *PN = cast<PHINode>(I);
353 auto [It, Inserted] = VisitedPHIs.try_emplace(PN, AllocSize);
354 if (!Inserted) {
355 if (TypeSize::isKnownGE(AllocSize, It->second.AllocSize))
356 break;
357
358 // Check again with smaller size.
359 if (It->second.NumDecreased == PhiInfo::MaxNumDecreased)
360 return true;
361
362 It->second.AllocSize = AllocSize;
363 ++It->second.NumDecreased;
364 }
365 if (HasAddressTaken(PN, AllocSize, M, VisitedPHIs))
366 return true;
367 break;
368 }
369 case Instruction::Load:
370 case Instruction::Ret:
371 // These instructions take an address operand, but have load-like or
372 // other innocuous behavior that should not trigger a stack protector.
373 break;
374 default:
375 // Conservatively return true for any instruction that takes an address
376 // operand, but is not handled above.
377 return true;
378 }
379 }
380 return false;
381}
382
383/// Search for the first call to the llvm.stackprotector intrinsic and return it
384/// if present.
386 for (const BasicBlock &BB : F)
387 for (const Instruction &I : BB)
388 if (const auto *II = dyn_cast<IntrinsicInst>(&I))
389 if (II->getIntrinsicID() == Intrinsic::stackprotector)
390 return II;
391 return nullptr;
392}
393
394/// Check whether or not this function needs a stack protector based
395/// upon the stack protector level.
396///
397/// We use two heuristics: a standard (ssp) and strong (sspstrong).
398/// The standard heuristic which will add a guard variable to functions that
399/// call alloca with a either a variable size or a size >= SSPBufferSize,
400/// functions with character buffers larger than SSPBufferSize, and functions
401/// with aggregates containing character buffers larger than SSPBufferSize. The
402/// strong heuristic will add a guard variables to functions that call alloca
403/// regardless of size, functions with any buffer regardless of type and size,
404/// functions with aggregates that contain any buffer regardless of type and
405/// size, and functions that contain stack-based variables that have had their
406/// address taken.
408 SSPLayoutMap *Layout) {
409 Module *M = F->getParent();
410 bool Strong = false;
411 bool NeedsProtector = false;
412
413 // The set of PHI nodes visited when determining if a variable's reference has
414 // been taken. This set is maintained to ensure we don't visit the same PHI
415 // node multiple times.
416 PhiMap VisitedPHIs;
417
418 unsigned SSPBufferSize = F->getFnAttributeAsParsedInteger(
419 "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
420
421 if (F->hasFnAttribute(Attribute::SafeStack))
422 return false;
423
424 // We are constructing the OptimizationRemarkEmitter on the fly rather than
425 // using the analysis pass to avoid building DominatorTree and LoopInfo which
426 // are not available this late in the IR pipeline.
428
429 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
430 if (!Layout)
431 return true;
432 ORE.emit([&]() {
433 return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
434 << "Stack protection applied to function "
435 << ore::NV("Function", F)
436 << " due to a function attribute or command-line switch";
437 });
438 NeedsProtector = true;
439 Strong = true; // Use the same heuristic as strong to determine SSPLayout
440 } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
441 Strong = true;
442 else if (!F->hasFnAttribute(Attribute::StackProtect))
443 return false;
444
445 for (const BasicBlock &BB : *F) {
446 for (const Instruction &I : BB) {
447 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
448 if (const MDNode *MD = AI->getMetadata("stack-protector")) {
449 const auto *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
450 if (CI->isZero())
451 continue;
452 }
453 if (AI->isArrayAllocation()) {
454 auto RemarkBuilder = [&]() {
455 return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
456 &I)
457 << "Stack protection applied to function "
458 << ore::NV("Function", F)
459 << " due to a call to alloca or use of a variable length "
460 "array";
461 };
462 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
463 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
464 // A call to alloca with size >= SSPBufferSize requires
465 // stack protectors.
466 if (!Layout)
467 return true;
468 Layout->insert(
469 std::make_pair(AI, MachineFrameInfo::SSPLK_LargeArray));
470 ORE.emit(RemarkBuilder);
471 NeedsProtector = true;
472 } else if (Strong) {
473 // Require protectors for all alloca calls in strong mode.
474 if (!Layout)
475 return true;
476 Layout->insert(
477 std::make_pair(AI, MachineFrameInfo::SSPLK_SmallArray));
478 ORE.emit(RemarkBuilder);
479 NeedsProtector = true;
480 }
481 } else {
482 // A call to alloca with a variable size requires protectors.
483 if (!Layout)
484 return true;
485 Layout->insert(
486 std::make_pair(AI, MachineFrameInfo::SSPLK_LargeArray));
487 ORE.emit(RemarkBuilder);
488 NeedsProtector = true;
489 }
490 continue;
491 }
492
493 bool IsLarge = false;
494 if (ContainsProtectableArray(AI->getAllocatedType(), M, SSPBufferSize,
495 IsLarge, Strong, false)) {
496 if (!Layout)
497 return true;
498 Layout->insert(std::make_pair(
501 ORE.emit([&]() {
502 return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
503 << "Stack protection applied to function "
504 << ore::NV("Function", F)
505 << " due to a stack allocated buffer or struct containing a "
506 "buffer";
507 });
508 NeedsProtector = true;
509 continue;
510 }
511
512 if (Strong) {
513 std::optional<TypeSize> AllocSize =
514 AI->getAllocationSize(M->getDataLayout());
515 if (!AllocSize || HasAddressTaken(AI, *AllocSize, M, VisitedPHIs)) {
516 ++NumAddrTaken;
517 if (!Layout)
518 return true;
519 Layout->insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
520 ORE.emit([&]() {
522 "StackProtectorAddressTaken", &I)
523 << "Stack protection applied to function "
524 << ore::NV("Function", F)
525 << " due to the address of a local variable being taken";
526 });
527 NeedsProtector = true;
528 }
529 }
530 // Clear any PHIs that we visited, to make sure we examine all uses of
531 // any subsequent allocas that we look at.
532 VisitedPHIs.clear();
533 }
534 }
535 }
536
537 return NeedsProtector;
538}
539
540/// Create a stack guard loading and populate whether SelectionDAG SSP is
541/// supported.
543 const LibcallLoweringInfo &Libcalls, Module *M,
544 IRBuilder<> &B,
545 bool *SupportsSelectionDAGSP = nullptr) {
546 Value *Guard = TLI.getIRStackGuard(B, Libcalls);
547 StringRef GuardMode = M->getStackProtectorGuard();
548 if ((GuardMode == "tls" || GuardMode.empty()) && Guard)
549 return B.CreateLoad(B.getPtrTy(), Guard, true, "StackGuard");
550
551 // Use SelectionDAG SSP handling, since there isn't an IR guard.
552 //
553 // This is more or less weird, since we optionally output whether we
554 // should perform a SelectionDAG SP here. The reason is that it's strictly
555 // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
556 // mutating. There is no way to get this bit without mutating the IR, so
557 // getting this bit has to happen in this right time.
558 //
559 // We could have define a new function TLI::supportsSelectionDAGSP(), but that
560 // will put more burden on the backends' overriding work, especially when it
561 // actually conveys the same information getIRStackGuard() already gives.
562 if (SupportsSelectionDAGSP)
563 *SupportsSelectionDAGSP = true;
564 TLI.insertSSPDeclarations(*M, Libcalls);
565 return B.CreateIntrinsic(Intrinsic::stackguard, {});
566}
567
568/// Insert code into the entry block that stores the stack guard
569/// variable onto the stack:
570///
571/// entry:
572/// StackGuardSlot = alloca i8*
573/// StackGuard = <stack guard>
574/// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
575///
576/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
577/// node.
578static bool CreatePrologue(Function *F, Module *M, Instruction *CheckLoc,
579 const TargetLoweringBase *TLI,
580 const LibcallLoweringInfo &Libcalls,
581 AllocaInst *&AI) {
582 bool SupportsSelectionDAGSP = false;
583 IRBuilder<> B(&F->getEntryBlock().front());
584 PointerType *PtrTy = PointerType::getUnqual(CheckLoc->getContext());
585 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
586
587 Value *GuardSlot =
588 getStackGuard(*TLI, Libcalls, M, B, &SupportsSelectionDAGSP);
589 B.CreateIntrinsic(Intrinsic::stackprotector, {GuardSlot, AI});
590 return SupportsSelectionDAGSP;
591}
592
594 const LibcallLoweringInfo &Libcalls, Function *F,
595 DomTreeUpdater *DTU, bool &HasPrologue,
596 bool &HasIRCheck) {
597 const CodeGenOptions &Opts = getCodeGenOptions(*F);
598 auto *M = F->getParent();
599
600 // If the target wants to XOR the frame pointer into the guard value, it's
601 // impossible to emit the check in IR, so the target *must* support stack
602 // protection in SDAG.
603 bool SupportsSelectionDAGSP =
604 TLI.useStackGuardMixFP() ||
605 (Opts.stack_protector_selectiondag &&
606 !TLI.getTargetMachine().Options.EnableFastISel);
607 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
608 BasicBlock *FailBB = nullptr;
609
611 // This is stack protector auto generated check BB, skip it.
612 if (&BB == FailBB)
613 continue;
614 Instruction *CheckLoc = dyn_cast<ReturnInst>(BB.getTerminator());
615 if (!CheckLoc && Opts.stack_protector_check_noreturn_call)
616 for (auto &Inst : BB) {
617 if (IntrinsicInst *IB = dyn_cast<IntrinsicInst>(&Inst);
618 IB && (IB->getIntrinsicID() == Intrinsic::eh_sjlj_callsite)) {
619 // eh_sjlj_callsite has to be in same BB as the
620 // bb terminator. Don't insert within this range.
621 CheckLoc = IB;
622 break;
623 }
624 if (auto *CB = dyn_cast<CallBase>(&Inst))
625 // Do stack check before noreturn calls that aren't nounwind (e.g:
626 // __cxa_throw).
627 if (CB->doesNotReturn() && !CB->doesNotThrow()) {
628 CheckLoc = CB;
629 break;
630 }
631 }
632
633 if (!CheckLoc)
634 continue;
635
636 // Generate prologue instrumentation if not already generated.
637 if (!HasPrologue) {
638 HasPrologue = true;
639 SupportsSelectionDAGSP &=
640 CreatePrologue(F, M, CheckLoc, &TLI, Libcalls, AI);
641 }
642
643 // SelectionDAG based code generation. Nothing else needs to be done here.
644 // The epilogue instrumentation is postponed to SelectionDAG.
645 if (SupportsSelectionDAGSP)
646 break;
647
648 // Find the stack guard slot if the prologue was not created by this pass
649 // itself via a previous call to CreatePrologue().
650 if (!AI) {
651 const CallInst *SPCall = findStackProtectorIntrinsic(*F);
652 assert(SPCall && "Call to llvm.stackprotector is missing");
653 AI = cast<AllocaInst>(SPCall->getArgOperand(1));
654 }
655
656 // Set HasIRCheck to true, so that SelectionDAG will not generate its own
657 // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
658 // instrumentation has already been generated.
659 HasIRCheck = true;
660
661 // If we're instrumenting a block with a tail call, the check has to be
662 // inserted before the call rather than between it and the return.
663 Instruction *Prev = CheckLoc->getPrevNode();
664 if (auto *CI = dyn_cast_if_present<CallInst>(Prev))
665 if (CI->isTailCall() && isInTailCallPosition(*CI, TLI.getTargetMachine()))
666 CheckLoc = Prev;
667
668 // Generate epilogue instrumentation. The epilogue intrumentation can be
669 // function-based or inlined depending on which mechanism the target is
670 // providing.
671 if (Function *GuardCheck = TLI.getSSPStackGuardCheck(*M, Libcalls)) {
672 // Generate the function-based epilogue instrumentation.
673 // The target provides a guard check function, generate a call to it.
674 IRBuilder<> B(CheckLoc);
675 LoadInst *Guard = B.CreateLoad(B.getPtrTy(), AI, true, "Guard");
676 CallInst *Call = B.CreateCall(GuardCheck, {Guard});
677 Call->setAttributes(GuardCheck->getAttributes());
678 Call->setCallingConv(GuardCheck->getCallingConv());
679 } else {
680 // Generate the epilogue with inline instrumentation.
681 // If we do not support SelectionDAG based calls, generate IR level
682 // calls.
683 //
684 // For each block with a return instruction, convert this:
685 //
686 // return:
687 // ...
688 // ret ...
689 //
690 // into this:
691 //
692 // return:
693 // ...
694 // %1 = <stack guard>
695 // %2 = load StackGuardSlot
696 // %3 = icmp ne i1 %1, %2
697 // br i1 %3, label %CallStackCheckFailBlk, label %SP_return
698 //
699 // SP_return:
700 // ret ...
701 //
702 // CallStackCheckFailBlk:
703 // call void @__stack_chk_fail()
704 // unreachable
705
706 // Create the FailBB. We duplicate the BB every time since the MI tail
707 // merge pass will merge together all of the various BB into one including
708 // fail BB generated by the stack protector pseudo instruction.
709 if (!FailBB)
710 FailBB = CreateFailBB(F, Libcalls);
711
712 IRBuilder<> B(CheckLoc);
713 Value *Guard = getStackGuard(TLI, Libcalls, M, B);
714 LoadInst *LI2 = B.CreateLoad(B.getPtrTy(), AI, true);
715 auto *Cmp = cast<ICmpInst>(B.CreateICmpNE(Guard, LI2));
716 auto SuccessProb =
718 auto FailureProb =
720 MDNode *Weights = MDBuilder(F->getContext())
721 .createBranchWeights(FailureProb.getNumerator(),
722 SuccessProb.getNumerator());
723
724 SplitBlockAndInsertIfThen(Cmp, CheckLoc,
725 /*Unreachable=*/false, Weights, DTU,
726 /*LI=*/nullptr, /*ThenBlock=*/FailBB);
727
728 auto *BI = cast<CondBrInst>(Cmp->getParent()->getTerminator());
729 BasicBlock *NewBB = BI->getSuccessor(1);
730 NewBB->setName("SP_return");
731 NewBB->moveAfter(&BB);
732
733 Cmp->setPredicate(Cmp->getInversePredicate());
734 BI->swapSuccessors();
735 }
736 }
737
738 // Return if we didn't modify any basic blocks. i.e., there are no return
739 // statements in the function.
740 return HasPrologue;
741}
742
744 auto *M = F->getParent();
745 LLVMContext &Context = F->getContext();
746 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
747 IRBuilder<> B(FailBB);
748 if (F->getSubprogram())
749 B.SetCurrentDebugLocation(
750 DILocation::get(Context, 0, 0, F->getSubprogram()));
751 bool IsSmashHandler = false;
752 RTLIB::LibcallImpl ChkFailImpl =
753 Libcalls.getLibcallImpl(RTLIB::STACKPROTECTOR_CHECK_FAIL);
754 if (ChkFailImpl == RTLIB::Unsupported) {
755 ChkFailImpl = Libcalls.getLibcallImpl(RTLIB::STACK_SMASH_HANDLER);
756 IsSmashHandler = true;
757 }
758
759 if (ChkFailImpl == RTLIB::Unsupported) {
760 Context.emitError("no libcall available for stack protector");
761 B.CreateUnreachable();
762 return FailBB;
763 }
764
765 FunctionCallee StackChkFail =
766 Libcalls.getRuntimeLibcallsInfo().getOrInsertLibcallDecl(*M, ChkFailImpl);
767
768 CallInst *Call;
769 if (IsSmashHandler) {
770 Call =
771 B.CreateCall(StackChkFail, B.CreateGlobalString(F->getName(), "SSH"));
772 } else {
773 Call = B.CreateCall(StackChkFail);
774 }
775
776 Call->setCallingConv(Libcalls.getLibcallImplCallingConv(ChkFailImpl));
777 Call->addFnAttr(Attribute::NoReturn);
778 B.CreateUnreachable();
779 return FailBB;
780}
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the SmallVector class.
static bool CreatePrologue(Function *F, Module *M, Instruction *CheckLoc, const TargetLoweringBase *TLI, const LibcallLoweringInfo &Libcalls, AllocaInst *&AI)
Insert code into the entry block that stores the stack guard variable onto the stack:
static Value * getStackGuard(const TargetLoweringBase &TLI, const LibcallLoweringInfo &Libcalls, Module *M, IRBuilder<> &B, bool *SupportsSelectionDAGSP=nullptr)
Create a stack guard loading and populate whether SelectionDAG SSP is supported.
static bool HasAddressTaken(const Instruction *AI, TypeSize AllocSize, Module *M, PhiMap &VisitedPHIs)
Check whether a stack allocation has its address taken.
static bool InsertStackProtectors(const TargetLowering &TLI, const LibcallLoweringInfo &Libcalls, Function *F, DomTreeUpdater *DTU, bool &HasPrologue, bool &HasIRCheck)
InsertStackProtectors - Insert code into the prologue and epilogue of the function.
SmallDenseMap< const PHINode *, PhiInfo, 16 > PhiMap
static bool ContainsProtectableArray(Type *Ty, Module *M, unsigned SSPBufferSize, bool &IsLarge, bool Strong, bool InStruct)
static BasicBlock * CreateFailBB(Function *F, const LibcallLoweringInfo &Libcalls)
CreateFailBB - Create a basic block to jump to when the stack protector check fails.
static const CallInst * findStackProtectorIntrinsic(Function &F)
Search for the first call to the llvm.stackprotector intrinsic and return it if present.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
Class for arbitrary precision integers.
Definition APInt.h:78
an instruction to allocate memory on the stack
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
static BranchProbability getBranchProbStackProtector(bool IsLikely)
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:679
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
FunctionPass(char &pid)
Definition Pass.h:314
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:899
Constant * getPersonalityFn() const
Get the personality function associated with this function.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Module * getParent()
Get the module that this global value is contained inside of...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
iterator_range< user_iterator > users()
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Tracks which library functions to use for a particular subtarget or function.
const RTLIB::RuntimeLibcallsInfo & getRuntimeLibcallsInfo() const
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
An instruction for reading from memory.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1087
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
@ SSPLK_SmallArray
Array or nested array < SSP-buffer-size.
@ SSPLK_LargeArray
Array or nested array >= SSP-buffer-size.
@ SSPLK_AddrOf
The address of this allocation is exposed and triggered protection.
void setObjectSSPLayout(int ObjectIdx, SSPLayoutKind Kind)
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
Records a mapping from an opaque lowering context to its LibcallLoweringInfo.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
static LLVM_ABI bool requiresStackProtector(Function *F, SSPLayoutMap *Layout=nullptr)
Check whether or not F needs a stack protector based upon the stack protector level.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &FAM)
LLVM_ABI void copyToMachineFrameInfo(MachineFrameInfo &MFI) const
LLVM_ABI bool shouldEmitSDCheck(const BasicBlock &BB) const
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static bool requiresStackProtector(Function *F, SSPLayoutMap *Layout=nullptr)
Check whether or not F needs a stack protector based upon the stack protector level.
bool runOnFunction(Function &Fn) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Class to represent struct types.
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
Target-Independent Code Generator Pass Configuration Options.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetLowering * getTargetLowering() const
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:224
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:238
CallInst * Call
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:708
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI FunctionPass * createStackProtectorPass()
createStackProtectorPass - This pass adds stack protectors to functions.
LLVM_ABI const LibcallLoweringInfo & getLibcallLowering(const ModuleLibcallLoweringInfo &ModuleInfo, const TargetSubtargetInfo &Subtarget)
Resolve the LibcallLoweringInfo for Subtarget from the module-level ModuleInfo, applying the subtarge...
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:709
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
PhiInfo(TypeSize AllocSize)
unsigned NumDecreased
static constexpr unsigned MaxNumDecreased
TypeSize AllocSize
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
LLVM_ABI FunctionCallee getOrInsertLibcallDecl(Module &M, RTLIB::LibcallImpl LibcallImpl) const