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 User *U : AI->users()) {
286 const auto *I = cast<Instruction>(U);
287 // If this instruction accesses memory make sure it doesn't access beyond
288 // the bounds of the allocated object.
289 std::optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I);
290 if (MemLoc && MemLoc->Size.hasValue() &&
291 !TypeSize::isKnownGE(AllocSize, MemLoc->Size.getValue()))
292 return true;
293 switch (I->getOpcode()) {
294 case Instruction::Store:
295 if (AI == cast<StoreInst>(I)->getValueOperand())
296 return true;
297 break;
298 case Instruction::AtomicCmpXchg:
299 // cmpxchg conceptually includes both a load and store from the same
300 // location. So, like store, the value being stored is what matters.
301 if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
302 return true;
303 break;
304 case Instruction::AtomicRMW:
305 if (AI == cast<AtomicRMWInst>(I)->getValOperand())
306 return true;
307 break;
308 case Instruction::PtrToInt:
309 if (AI == cast<PtrToIntInst>(I)->getOperand(0))
310 return true;
311 break;
312 case Instruction::Call: {
313 // Ignore intrinsics that do not become real instructions.
314 // TODO: Narrow this to intrinsics that have store-like effects.
315 const auto *CI = cast<CallInst>(I);
316 if (!isa<PseudoProbeInst>(CI) && !CI->isLifetimeStartOrEnd())
317 return true;
318 break;
319 }
320 case Instruction::Invoke:
321 return true;
322 case Instruction::GetElementPtr: {
323 // If the GEP offset is out-of-bounds, or is non-constant and so has to be
324 // assumed to be potentially out-of-bounds, then any memory access that
325 // would use it could also be out-of-bounds meaning stack protection is
326 // required.
328 unsigned IndexSize = DL.getIndexTypeSizeInBits(I->getType());
329 APInt Offset(IndexSize, 0);
330 if (!GEP->accumulateConstantOffset(DL, Offset))
331 return true;
332 TypeSize OffsetSize = TypeSize::getFixed(Offset.getLimitedValue());
333 if (!TypeSize::isKnownGT(AllocSize, OffsetSize))
334 return true;
335 // Adjust AllocSize to be the space remaining after this offset.
336 // We can't subtract a fixed size from a scalable one, so in that case
337 // assume the scalable value is of minimum size.
338 TypeSize NewAllocSize =
339 TypeSize::getFixed(AllocSize.getKnownMinValue()) - OffsetSize;
340 if (HasAddressTaken(I, NewAllocSize, M, VisitedPHIs))
341 return true;
342 break;
343 }
344 case Instruction::BitCast:
345 case Instruction::Select:
346 case Instruction::AddrSpaceCast:
347 if (HasAddressTaken(I, AllocSize, M, VisitedPHIs))
348 return true;
349 break;
350 case Instruction::PHI: {
351 // Keep track of what PHI nodes we have already visited to ensure
352 // they are only visited once.
353 const auto *PN = cast<PHINode>(I);
354 auto [It, Inserted] = VisitedPHIs.try_emplace(PN, AllocSize);
355 if (!Inserted) {
356 if (TypeSize::isKnownGE(AllocSize, It->second.AllocSize))
357 break;
358
359 // Check again with smaller size.
360 if (It->second.NumDecreased == PhiInfo::MaxNumDecreased)
361 return true;
362
363 It->second.AllocSize = AllocSize;
364 ++It->second.NumDecreased;
365 }
366 if (HasAddressTaken(PN, AllocSize, M, VisitedPHIs))
367 return true;
368 break;
369 }
370 case Instruction::Load:
371 case Instruction::Ret:
372 // These instructions take an address operand, but have load-like or
373 // other innocuous behavior that should not trigger a stack protector.
374 break;
375 default:
376 // Conservatively return true for any instruction that takes an address
377 // operand, but is not handled above.
378 return true;
379 }
380 }
381 return false;
382}
383
384/// Search for the first call to the llvm.stackprotector intrinsic and return it
385/// if present.
387 for (const BasicBlock &BB : F)
388 for (const Instruction &I : BB)
389 if (const auto *II = dyn_cast<IntrinsicInst>(&I))
390 if (II->getIntrinsicID() == Intrinsic::stackprotector)
391 return II;
392 return nullptr;
393}
394
395/// Check whether or not this function needs a stack protector based
396/// upon the stack protector level.
397///
398/// We use two heuristics: a standard (ssp) and strong (sspstrong).
399/// The standard heuristic which will add a guard variable to functions that
400/// call alloca with a either a variable size or a size >= SSPBufferSize,
401/// functions with character buffers larger than SSPBufferSize, and functions
402/// with aggregates containing character buffers larger than SSPBufferSize. The
403/// strong heuristic will add a guard variables to functions that call alloca
404/// regardless of size, functions with any buffer regardless of type and size,
405/// functions with aggregates that contain any buffer regardless of type and
406/// size, and functions that contain stack-based variables that have had their
407/// address taken.
409 SSPLayoutMap *Layout) {
410 Module *M = F->getParent();
411 bool Strong = false;
412 bool NeedsProtector = false;
413
414 // The set of PHI nodes visited when determining if a variable's reference has
415 // been taken. This set is maintained to ensure we don't visit the same PHI
416 // node multiple times.
417 PhiMap VisitedPHIs;
418
419 unsigned SSPBufferSize = F->getFnAttributeAsParsedInteger(
420 "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
421
422 if (F->hasFnAttribute(Attribute::SafeStack))
423 return false;
424
425 // We are constructing the OptimizationRemarkEmitter on the fly rather than
426 // using the analysis pass to avoid building DominatorTree and LoopInfo which
427 // are not available this late in the IR pipeline.
429
430 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
431 if (!Layout)
432 return true;
433 ORE.emit([&]() {
434 return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
435 << "Stack protection applied to function "
436 << ore::NV("Function", F)
437 << " due to a function attribute or command-line switch";
438 });
439 NeedsProtector = true;
440 Strong = true; // Use the same heuristic as strong to determine SSPLayout
441 } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
442 Strong = true;
443 else if (!F->hasFnAttribute(Attribute::StackProtect))
444 return false;
445
446 for (const BasicBlock &BB : *F) {
447 for (const Instruction &I : BB) {
448 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
449 if (const MDNode *MD = AI->getMetadata("stack-protector")) {
450 const auto *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
451 if (CI->isZero())
452 continue;
453 }
454 if (AI->isArrayAllocation()) {
455 auto RemarkBuilder = [&]() {
456 return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
457 &I)
458 << "Stack protection applied to function "
459 << ore::NV("Function", F)
460 << " due to a call to alloca or use of a variable length "
461 "array";
462 };
463 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
464 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
465 // A call to alloca with size >= SSPBufferSize requires
466 // stack protectors.
467 if (!Layout)
468 return true;
469 Layout->insert(
470 std::make_pair(AI, MachineFrameInfo::SSPLK_LargeArray));
471 ORE.emit(RemarkBuilder);
472 NeedsProtector = true;
473 } else if (Strong) {
474 // Require protectors for all alloca calls in strong mode.
475 if (!Layout)
476 return true;
477 Layout->insert(
478 std::make_pair(AI, MachineFrameInfo::SSPLK_SmallArray));
479 ORE.emit(RemarkBuilder);
480 NeedsProtector = true;
481 }
482 } else {
483 // A call to alloca with a variable size requires protectors.
484 if (!Layout)
485 return true;
486 Layout->insert(
487 std::make_pair(AI, MachineFrameInfo::SSPLK_LargeArray));
488 ORE.emit(RemarkBuilder);
489 NeedsProtector = true;
490 }
491 continue;
492 }
493
494 bool IsLarge = false;
495 if (ContainsProtectableArray(AI->getAllocatedType(), M, SSPBufferSize,
496 IsLarge, Strong, false)) {
497 if (!Layout)
498 return true;
499 Layout->insert(std::make_pair(
502 ORE.emit([&]() {
503 return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
504 << "Stack protection applied to function "
505 << ore::NV("Function", F)
506 << " due to a stack allocated buffer or struct containing a "
507 "buffer";
508 });
509 NeedsProtector = true;
510 continue;
511 }
512
513 if (Strong) {
514 std::optional<TypeSize> AllocSize =
515 AI->getAllocationSize(M->getDataLayout());
516 if (!AllocSize || HasAddressTaken(AI, *AllocSize, M, VisitedPHIs)) {
517 ++NumAddrTaken;
518 if (!Layout)
519 return true;
520 Layout->insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
521 ORE.emit([&]() {
523 "StackProtectorAddressTaken", &I)
524 << "Stack protection applied to function "
525 << ore::NV("Function", F)
526 << " due to the address of a local variable being taken";
527 });
528 NeedsProtector = true;
529 }
530 }
531 // Clear any PHIs that we visited, to make sure we examine all uses of
532 // any subsequent allocas that we look at.
533 VisitedPHIs.clear();
534 }
535 }
536 }
537
538 return NeedsProtector;
539}
540
541/// Create a stack guard loading and populate whether SelectionDAG SSP is
542/// supported.
544 const LibcallLoweringInfo &Libcalls, Module *M,
545 IRBuilder<> &B,
546 bool *SupportsSelectionDAGSP = nullptr) {
547 Value *Guard = TLI.getIRStackGuard(B, Libcalls);
548 StringRef GuardMode = M->getStackProtectorGuard();
549 if ((GuardMode == "tls" || GuardMode.empty()) && Guard)
550 return B.CreateLoad(B.getPtrTy(), Guard, true, "StackGuard");
551
552 // Use SelectionDAG SSP handling, since there isn't an IR guard.
553 //
554 // This is more or less weird, since we optionally output whether we
555 // should perform a SelectionDAG SP here. The reason is that it's strictly
556 // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
557 // mutating. There is no way to get this bit without mutating the IR, so
558 // getting this bit has to happen in this right time.
559 //
560 // We could have define a new function TLI::supportsSelectionDAGSP(), but that
561 // will put more burden on the backends' overriding work, especially when it
562 // actually conveys the same information getIRStackGuard() already gives.
563 if (SupportsSelectionDAGSP)
564 *SupportsSelectionDAGSP = true;
565 TLI.insertSSPDeclarations(*M, Libcalls);
566 return B.CreateIntrinsic(Intrinsic::stackguard, {});
567}
568
569/// Insert code into the entry block that stores the stack guard
570/// variable onto the stack:
571///
572/// entry:
573/// StackGuardSlot = alloca i8*
574/// StackGuard = <stack guard>
575/// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
576///
577/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
578/// node.
579static bool CreatePrologue(Function *F, Module *M, Instruction *CheckLoc,
580 const TargetLoweringBase *TLI,
581 const LibcallLoweringInfo &Libcalls,
582 AllocaInst *&AI) {
583 bool SupportsSelectionDAGSP = false;
584 IRBuilder<> B(&F->getEntryBlock().front());
585 PointerType *PtrTy = PointerType::getUnqual(CheckLoc->getContext());
586 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
587
588 Value *GuardSlot =
589 getStackGuard(*TLI, Libcalls, M, B, &SupportsSelectionDAGSP);
590 B.CreateIntrinsic(Intrinsic::stackprotector, {GuardSlot, AI});
591 return SupportsSelectionDAGSP;
592}
593
595 const LibcallLoweringInfo &Libcalls, Function *F,
596 DomTreeUpdater *DTU, bool &HasPrologue,
597 bool &HasIRCheck) {
598 const CodeGenOptions &Opts = getCodeGenOptions(*F);
599 auto *M = F->getParent();
600
601 // If the target wants to XOR the frame pointer into the guard value, it's
602 // impossible to emit the check in IR, so the target *must* support stack
603 // protection in SDAG.
604 bool SupportsSelectionDAGSP =
605 TLI.useStackGuardMixFP() ||
606 (Opts.stack_protector_selectiondag &&
607 !TLI.getTargetMachine().Options.EnableFastISel);
608 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
609 BasicBlock *FailBB = nullptr;
610
612 // This is stack protector auto generated check BB, skip it.
613 if (&BB == FailBB)
614 continue;
615 Instruction *CheckLoc = dyn_cast<ReturnInst>(BB.getTerminator());
616 if (!CheckLoc && Opts.stack_protector_check_noreturn_call)
617 for (auto &Inst : BB) {
618 if (IntrinsicInst *IB = dyn_cast<IntrinsicInst>(&Inst);
619 IB && (IB->getIntrinsicID() == Intrinsic::eh_sjlj_callsite)) {
620 // eh_sjlj_callsite has to be in same BB as the
621 // bb terminator. Don't insert within this range.
622 CheckLoc = IB;
623 break;
624 }
625 if (auto *CB = dyn_cast<CallBase>(&Inst))
626 // Do stack check before noreturn calls that aren't nounwind (e.g:
627 // __cxa_throw).
628 if (CB->doesNotReturn() && !CB->doesNotThrow()) {
629 CheckLoc = CB;
630 break;
631 }
632 }
633
634 if (!CheckLoc)
635 continue;
636
637 // Generate prologue instrumentation if not already generated.
638 if (!HasPrologue) {
639 HasPrologue = true;
640 SupportsSelectionDAGSP &=
641 CreatePrologue(F, M, CheckLoc, &TLI, Libcalls, AI);
642 }
643
644 // SelectionDAG based code generation. Nothing else needs to be done here.
645 // The epilogue instrumentation is postponed to SelectionDAG.
646 if (SupportsSelectionDAGSP)
647 break;
648
649 // Find the stack guard slot if the prologue was not created by this pass
650 // itself via a previous call to CreatePrologue().
651 if (!AI) {
652 const CallInst *SPCall = findStackProtectorIntrinsic(*F);
653 assert(SPCall && "Call to llvm.stackprotector is missing");
654 AI = cast<AllocaInst>(SPCall->getArgOperand(1));
655 }
656
657 // Set HasIRCheck to true, so that SelectionDAG will not generate its own
658 // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
659 // instrumentation has already been generated.
660 HasIRCheck = true;
661
662 // If we're instrumenting a block with a tail call, the check has to be
663 // inserted before the call rather than between it and the return.
664 Instruction *Prev = CheckLoc->getPrevNode();
665 if (auto *CI = dyn_cast_if_present<CallInst>(Prev))
666 if (CI->isTailCall() && isInTailCallPosition(*CI, TLI.getTargetMachine()))
667 CheckLoc = Prev;
668
669 // Generate epilogue instrumentation. The epilogue intrumentation can be
670 // function-based or inlined depending on which mechanism the target is
671 // providing.
672 if (Function *GuardCheck = TLI.getSSPStackGuardCheck(*M, Libcalls)) {
673 // Generate the function-based epilogue instrumentation.
674 // The target provides a guard check function, generate a call to it.
675 IRBuilder<> B(CheckLoc);
676 LoadInst *Guard = B.CreateLoad(B.getPtrTy(), AI, true, "Guard");
677 CallInst *Call = B.CreateCall(GuardCheck, {Guard});
678 Call->setAttributes(GuardCheck->getAttributes());
679 Call->setCallingConv(GuardCheck->getCallingConv());
680 } else {
681 // Generate the epilogue with inline instrumentation.
682 // If we do not support SelectionDAG based calls, generate IR level
683 // calls.
684 //
685 // For each block with a return instruction, convert this:
686 //
687 // return:
688 // ...
689 // ret ...
690 //
691 // into this:
692 //
693 // return:
694 // ...
695 // %1 = <stack guard>
696 // %2 = load StackGuardSlot
697 // %3 = icmp ne i1 %1, %2
698 // br i1 %3, label %CallStackCheckFailBlk, label %SP_return
699 //
700 // SP_return:
701 // ret ...
702 //
703 // CallStackCheckFailBlk:
704 // call void @__stack_chk_fail()
705 // unreachable
706
707 // Create the FailBB. We duplicate the BB every time since the MI tail
708 // merge pass will merge together all of the various BB into one including
709 // fail BB generated by the stack protector pseudo instruction.
710 if (!FailBB)
711 FailBB = CreateFailBB(F, Libcalls);
712
713 IRBuilder<> B(CheckLoc);
714 Value *Guard = getStackGuard(TLI, Libcalls, M, B);
715 LoadInst *LI2 = B.CreateLoad(B.getPtrTy(), AI, true);
716 auto *Cmp = cast<ICmpInst>(B.CreateICmpNE(Guard, LI2));
717 auto SuccessProb =
719 auto FailureProb =
721 MDNode *Weights = MDBuilder(F->getContext())
722 .createBranchWeights(FailureProb.getNumerator(),
723 SuccessProb.getNumerator());
724
725 SplitBlockAndInsertIfThen(Cmp, CheckLoc,
726 /*Unreachable=*/false, Weights, DTU,
727 /*LI=*/nullptr, /*ThenBlock=*/FailBB);
728
729 auto *BI = cast<CondBrInst>(Cmp->getParent()->getTerminator());
730 BasicBlock *NewBB = BI->getSuccessor(1);
731 NewBB->setName("SP_return");
732 NewBB->moveAfter(&BB);
733
734 Cmp->setPredicate(Cmp->getInversePredicate());
735 BI->swapSuccessors();
736 }
737 }
738
739 // Return if we didn't modify any basic blocks. i.e., there are no return
740 // statements in the function.
741 return HasPrologue;
742}
743
745 auto *M = F->getParent();
746 LLVMContext &Context = F->getContext();
747 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
748 IRBuilder<> B(FailBB);
749 if (F->getSubprogram())
750 B.SetCurrentDebugLocation(
751 DILocation::get(Context, 0, 0, F->getSubprogram()));
752 bool IsSmashHandler = false;
753 RTLIB::LibcallImpl ChkFailImpl =
754 Libcalls.getLibcallImpl(RTLIB::STACKPROTECTOR_CHECK_FAIL);
755 if (ChkFailImpl == RTLIB::Unsupported) {
756 ChkFailImpl = Libcalls.getLibcallImpl(RTLIB::STACK_SMASH_HANDLER);
757 IsSmashHandler = true;
758 }
759
760 if (ChkFailImpl == RTLIB::Unsupported) {
761 Context.emitError("no libcall available for stack protector");
762 B.CreateUnreachable();
763 return FailBB;
764 }
765
766 FunctionCallee StackChkFail =
767 Libcalls.getRuntimeLibcallsInfo().getOrInsertLibcallDecl(*M, ChkFailImpl);
768
769 CallInst *Call;
770 if (IsSmashHandler) {
771 Call =
772 B.CreateCall(StackChkFail, B.CreateGlobalString(F->getName(), "SSH"));
773 } else {
774 Call = B.CreateCall(StackChkFail);
775 }
776
777 Call->setCallingConv(Libcalls.getLibcallImplCallingConv(ChkFailImpl));
778 Call->addFnAttr(Attribute::NoReturn);
779 B.CreateUnreachable();
780 return FailBB;
781}
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:171
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:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
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:237
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:64
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:133
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