LLVM  13.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 "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/Passes.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"
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 
68 }
69 
71  "Insert stack protectors", false, true)
75  "Insert stack protectors", false, true)
76 
78 
82 }
83 
85  F = &Fn;
86  M = F->getParent();
88  getAnalysisIfAvailable<DominatorTreeWrapperPass>();
89  DT = DTWP ? &DTWP->getDomTree() : nullptr;
90  TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
91  Trip = TM->getTargetTriple();
92  TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
93  HasPrologue = false;
94  HasIRCheck = false;
95 
96  Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
97  if (Attr.isStringAttribute() &&
98  Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
99  return false; // Invalid integer string
100 
101  if (!RequiresStackProtector())
102  return false;
103 
104  // TODO(etienneb): Functions with funclets are not correctly supported now.
105  // Do nothing if this is funclet-based personality.
106  if (Fn.hasPersonalityFn()) {
108  if (isFuncletEHPersonality(Personality))
109  return false;
110  }
111 
112  ++NumFunProtected;
113  return InsertStackProtectors();
114 }
115 
116 /// \param [out] IsLarge is set to true if a protectable array is found and
117 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
118 /// multiple arrays, this gets set if any of them is large.
119 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
120  bool Strong,
121  bool InStruct) const {
122  if (!Ty)
123  return false;
124  if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
125  if (!AT->getElementType()->isIntegerTy(8)) {
126  // If we're on a non-Darwin platform or we're inside of a structure, don't
127  // add stack protectors unless the array is a character array.
128  // However, in strong mode any array, regardless of type and size,
129  // triggers a protector.
130  if (!Strong && (InStruct || !Trip.isOSDarwin()))
131  return false;
132  }
133 
134  // If an array has more than SSPBufferSize bytes of allocated space, then we
135  // emit stack protectors.
136  if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
137  IsLarge = true;
138  return true;
139  }
140 
141  if (Strong)
142  // Require a protector for all arrays in strong mode
143  return true;
144  }
145 
146  const StructType *ST = dyn_cast<StructType>(Ty);
147  if (!ST)
148  return false;
149 
150  bool NeedsProtector = false;
151  for (StructType::element_iterator I = ST->element_begin(),
152  E = ST->element_end();
153  I != E; ++I)
154  if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
155  // If the element is a protectable array and is large (>= SSPBufferSize)
156  // then we are done. If the protectable array is not large, then
157  // keep looking in case a subsequent element is a large array.
158  if (IsLarge)
159  return true;
160  NeedsProtector = true;
161  }
162 
163  return NeedsProtector;
164 }
165 
166 bool StackProtector::HasAddressTaken(const Instruction *AI,
167  uint64_t AllocSize) {
168  const DataLayout &DL = M->getDataLayout();
169  for (const User *U : AI->users()) {
170  const auto *I = cast<Instruction>(U);
171  // If this instruction accesses memory make sure it doesn't access beyond
172  // the bounds of the allocated object.
174  if (MemLoc.hasValue() && MemLoc->Size.hasValue() &&
175  MemLoc->Size.getValue() > AllocSize)
176  return true;
177  switch (I->getOpcode()) {
178  case Instruction::Store:
179  if (AI == cast<StoreInst>(I)->getValueOperand())
180  return true;
181  break;
182  case Instruction::AtomicCmpXchg:
183  // cmpxchg conceptually includes both a load and store from the same
184  // location. So, like store, the value being stored is what matters.
185  if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
186  return true;
187  break;
188  case Instruction::PtrToInt:
189  if (AI == cast<PtrToIntInst>(I)->getOperand(0))
190  return true;
191  break;
192  case Instruction::Call: {
193  // Ignore intrinsics that do not become real instructions.
194  // TODO: Narrow this to intrinsics that have store-like effects.
195  const auto *CI = cast<CallInst>(I);
196  if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd())
197  return true;
198  break;
199  }
200  case Instruction::Invoke:
201  return true;
202  case Instruction::GetElementPtr: {
203  // If the GEP offset is out-of-bounds, or is non-constant and so has to be
204  // assumed to be potentially out-of-bounds, then any memory access that
205  // would use it could also be out-of-bounds meaning stack protection is
206  // required.
207  const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
208  unsigned TypeSize = DL.getIndexTypeSizeInBits(I->getType());
209  APInt Offset(TypeSize, 0);
210  APInt MaxOffset(TypeSize, AllocSize);
211  if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.ugt(MaxOffset))
212  return true;
213  // Adjust AllocSize to be the space remaining after this offset.
214  if (HasAddressTaken(I, AllocSize - Offset.getLimitedValue()))
215  return true;
216  break;
217  }
218  case Instruction::BitCast:
219  case Instruction::Select:
220  case Instruction::AddrSpaceCast:
221  if (HasAddressTaken(I, AllocSize))
222  return true;
223  break;
224  case Instruction::PHI: {
225  // Keep track of what PHI nodes we have already visited to ensure
226  // they are only visited once.
227  const auto *PN = cast<PHINode>(I);
228  if (VisitedPHIs.insert(PN).second)
229  if (HasAddressTaken(PN, AllocSize))
230  return true;
231  break;
232  }
233  case Instruction::Load:
234  case Instruction::AtomicRMW:
235  case Instruction::Ret:
236  // These instructions take an address operand, but have load-like or
237  // other innocuous behavior that should not trigger a stack protector.
238  // atomicrmw conceptually has both load and store semantics, but the
239  // value being stored must be integer; so if a pointer is being stored,
240  // we'll catch it in the PtrToInt case above.
241  break;
242  default:
243  // Conservatively return true for any instruction that takes an address
244  // operand, but is not handled above.
245  return true;
246  }
247  }
248  return false;
249 }
250 
251 /// Search for the first call to the llvm.stackprotector intrinsic and return it
252 /// if present.
254  for (const BasicBlock &BB : F)
255  for (const Instruction &I : BB)
256  if (const auto *II = dyn_cast<IntrinsicInst>(&I))
257  if (II->getIntrinsicID() == Intrinsic::stackprotector)
258  return II;
259  return nullptr;
260 }
261 
262 /// Check whether or not this function needs a stack protector based
263 /// upon the stack protector level.
264 ///
265 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
266 /// The standard heuristic which will add a guard variable to functions that
267 /// call alloca with a either a variable size or a size >= SSPBufferSize,
268 /// functions with character buffers larger than SSPBufferSize, and functions
269 /// with aggregates containing character buffers larger than SSPBufferSize. The
270 /// strong heuristic will add a guard variables to functions that call alloca
271 /// regardless of size, functions with any buffer regardless of type and size,
272 /// functions with aggregates that contain any buffer regardless of type and
273 /// size, and functions that contain stack-based variables that have had their
274 /// address taken.
275 bool StackProtector::RequiresStackProtector() {
276  bool Strong = false;
277  bool NeedsProtector = false;
278 
279  if (F->hasFnAttribute(Attribute::SafeStack))
280  return false;
281 
282  // We are constructing the OptimizationRemarkEmitter on the fly rather than
283  // using the analysis pass to avoid building DominatorTree and LoopInfo which
284  // are not available this late in the IR pipeline.
286 
287  if (F->hasFnAttribute(Attribute::StackProtectReq)) {
288  ORE.emit([&]() {
289  return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
290  << "Stack protection applied to function "
291  << ore::NV("Function", F)
292  << " due to a function attribute or command-line switch";
293  });
294  NeedsProtector = true;
295  Strong = true; // Use the same heuristic as strong to determine SSPLayout
296  } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
297  Strong = true;
298  else if (!F->hasFnAttribute(Attribute::StackProtect))
299  return false;
300 
301  for (const BasicBlock &BB : *F) {
302  for (const Instruction &I : BB) {
303  if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
304  if (AI->isArrayAllocation()) {
305  auto RemarkBuilder = [&]() {
306  return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
307  &I)
308  << "Stack protection applied to function "
309  << ore::NV("Function", F)
310  << " due to a call to alloca or use of a variable length "
311  "array";
312  };
313  if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
314  if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
315  // A call to alloca with size >= SSPBufferSize requires
316  // stack protectors.
317  Layout.insert(std::make_pair(AI,
319  ORE.emit(RemarkBuilder);
320  NeedsProtector = true;
321  } else if (Strong) {
322  // Require protectors for all alloca calls in strong mode.
323  Layout.insert(std::make_pair(AI,
325  ORE.emit(RemarkBuilder);
326  NeedsProtector = true;
327  }
328  } else {
329  // A call to alloca with a variable size requires protectors.
330  Layout.insert(std::make_pair(AI,
332  ORE.emit(RemarkBuilder);
333  NeedsProtector = true;
334  }
335  continue;
336  }
337 
338  bool IsLarge = false;
339  if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
340  Layout.insert(std::make_pair(AI, IsLarge
343  ORE.emit([&]() {
344  return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
345  << "Stack protection applied to function "
346  << ore::NV("Function", F)
347  << " due to a stack allocated buffer or struct containing a "
348  "buffer";
349  });
350  NeedsProtector = true;
351  continue;
352  }
353 
354  if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize(
355  AI->getAllocatedType()))) {
356  ++NumAddrTaken;
357  Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
358  ORE.emit([&]() {
359  return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
360  &I)
361  << "Stack protection applied to function "
362  << ore::NV("Function", F)
363  << " due to the address of a local variable being taken";
364  });
365  NeedsProtector = true;
366  }
367  // Clear any PHIs that we visited, to make sure we examine all uses of
368  // any subsequent allocas that we look at.
369  VisitedPHIs.clear();
370  }
371  }
372  }
373 
374  return NeedsProtector;
375 }
376 
377 /// Create a stack guard loading and populate whether SelectionDAG SSP is
378 /// supported.
380  IRBuilder<> &B,
381  bool *SupportsSelectionDAGSP = nullptr) {
382  Value *Guard = TLI->getIRStackGuard(B);
383  auto GuardMode = TLI->getTargetMachine().Options.StackProtectorGuard;
384  if ((GuardMode == llvm::StackProtectorGuards::TLS ||
385  GuardMode == llvm::StackProtectorGuards::None) && Guard)
386  return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard");
387 
388  // Use SelectionDAG SSP handling, since there isn't an IR guard.
389  //
390  // This is more or less weird, since we optionally output whether we
391  // should perform a SelectionDAG SP here. The reason is that it's strictly
392  // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
393  // mutating. There is no way to get this bit without mutating the IR, so
394  // getting this bit has to happen in this right time.
395  //
396  // We could have define a new function TLI::supportsSelectionDAGSP(), but that
397  // will put more burden on the backends' overriding work, especially when it
398  // actually conveys the same information getIRStackGuard() already gives.
399  if (SupportsSelectionDAGSP)
400  *SupportsSelectionDAGSP = true;
401  TLI->insertSSPDeclarations(*M);
402  return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
403 }
404 
405 /// Insert code into the entry block that stores the stack guard
406 /// variable onto the stack:
407 ///
408 /// entry:
409 /// StackGuardSlot = alloca i8*
410 /// StackGuard = <stack guard>
411 /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
412 ///
413 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
414 /// node.
415 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
416  const TargetLoweringBase *TLI, AllocaInst *&AI) {
417  bool SupportsSelectionDAGSP = false;
418  IRBuilder<> B(&F->getEntryBlock().front());
419  PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
420  AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
421 
422  Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
423  B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
424  {GuardSlot, AI});
425  return SupportsSelectionDAGSP;
426 }
427 
428 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
429 /// function.
430 ///
431 /// - The prologue code loads and stores the stack guard onto the stack.
432 /// - The epilogue checks the value stored in the prologue against the original
433 /// value. It calls __stack_chk_fail if they differ.
434 bool StackProtector::InsertStackProtectors() {
435  // If the target wants to XOR the frame pointer into the guard value, it's
436  // impossible to emit the check in IR, so the target *must* support stack
437  // protection in SDAG.
438  bool SupportsSelectionDAGSP =
439  TLI->useStackGuardXorFP() ||
442  AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
443 
444  for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
445  BasicBlock *BB = &*I++;
446  ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
447  if (!RI)
448  continue;
449 
450  // Generate prologue instrumentation if not already generated.
451  if (!HasPrologue) {
452  HasPrologue = true;
453  SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
454  }
455 
456  // SelectionDAG based code generation. Nothing else needs to be done here.
457  // The epilogue instrumentation is postponed to SelectionDAG.
458  if (SupportsSelectionDAGSP)
459  break;
460 
461  // Find the stack guard slot if the prologue was not created by this pass
462  // itself via a previous call to CreatePrologue().
463  if (!AI) {
464  const CallInst *SPCall = findStackProtectorIntrinsic(*F);
465  assert(SPCall && "Call to llvm.stackprotector is missing");
466  AI = cast<AllocaInst>(SPCall->getArgOperand(1));
467  }
468 
469  // Set HasIRCheck to true, so that SelectionDAG will not generate its own
470  // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
471  // instrumentation has already been generated.
472  HasIRCheck = true;
473 
474  // If we're instrumenting a block with a musttail call, the check has to be
475  // inserted before the call rather than between it and the return. The
476  // verifier guarantees that a musttail call is either directly before the
477  // return or with a single correct bitcast of the return value in between so
478  // we don't need to worry about many situations here.
479  Instruction *CheckLoc = RI;
481  if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall())
482  CheckLoc = Prev;
483  else if (Prev) {
484  Prev = Prev->getPrevNonDebugInstruction();
485  if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall())
486  CheckLoc = Prev;
487  }
488 
489  // Generate epilogue instrumentation. The epilogue intrumentation can be
490  // function-based or inlined depending on which mechanism the target is
491  // providing.
492  if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
493  // Generate the function-based epilogue instrumentation.
494  // The target provides a guard check function, generate a call to it.
495  IRBuilder<> B(CheckLoc);
496  LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard");
497  CallInst *Call = B.CreateCall(GuardCheck, {Guard});
498  Call->setAttributes(GuardCheck->getAttributes());
499  Call->setCallingConv(GuardCheck->getCallingConv());
500  } else {
501  // Generate the epilogue with inline instrumentation.
502  // If we do not support SelectionDAG based calls, generate IR level
503  // calls.
504  //
505  // For each block with a return instruction, convert this:
506  //
507  // return:
508  // ...
509  // ret ...
510  //
511  // into this:
512  //
513  // return:
514  // ...
515  // %1 = <stack guard>
516  // %2 = load StackGuardSlot
517  // %3 = cmp i1 %1, %2
518  // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
519  //
520  // SP_return:
521  // ret ...
522  //
523  // CallStackCheckFailBlk:
524  // call void @__stack_chk_fail()
525  // unreachable
526 
527  // Create the FailBB. We duplicate the BB every time since the MI tail
528  // merge pass will merge together all of the various BB into one including
529  // fail BB generated by the stack protector pseudo instruction.
530  BasicBlock *FailBB = CreateFailBB();
531 
532  // Split the basic block before the return instruction.
533  BasicBlock *NewBB =
534  BB->splitBasicBlock(CheckLoc->getIterator(), "SP_return");
535 
536  // Update the dominator tree if we need to.
537  if (DT && DT->isReachableFromEntry(BB)) {
538  DT->addNewBlock(NewBB, BB);
539  DT->addNewBlock(FailBB, BB);
540  }
541 
542  // Remove default branch instruction to the new BB.
543  BB->getTerminator()->eraseFromParent();
544 
545  // Move the newly created basic block to the point right after the old
546  // basic block so that it's in the "fall through" position.
547  NewBB->moveAfter(BB);
548 
549  // Generate the stack protector instructions in the old basic block.
550  IRBuilder<> B(BB);
551  Value *Guard = getStackGuard(TLI, M, B);
552  LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
553  Value *Cmp = B.CreateICmpEQ(Guard, LI2);
554  auto SuccessProb =
556  auto FailureProb =
558  MDNode *Weights = MDBuilder(F->getContext())
559  .createBranchWeights(SuccessProb.getNumerator(),
560  FailureProb.getNumerator());
561  B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
562  }
563  }
564 
565  // Return if we didn't modify any basic blocks. i.e., there are no return
566  // statements in the function.
567  return HasPrologue;
568 }
569 
570 /// CreateFailBB - Create a basic block to jump to when the stack protector
571 /// check fails.
572 BasicBlock *StackProtector::CreateFailBB() {
573  LLVMContext &Context = F->getContext();
574  BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
575  IRBuilder<> B(FailBB);
576  if (F->getSubprogram())
577  B.SetCurrentDebugLocation(
578  DILocation::get(Context, 0, 0, F->getSubprogram()));
579  if (Trip.isOSOpenBSD()) {
580  FunctionCallee StackChkFail = M->getOrInsertFunction(
581  "__stack_smash_handler", Type::getVoidTy(Context),
583 
584  B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
585  } else {
586  FunctionCallee StackChkFail =
587  M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
588 
589  B.CreateCall(StackChkFail, {});
590  }
591  B.CreateUnreachable();
592  return FailBB;
593 }
594 
596  return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
597 }
598 
600  if (Layout.empty())
601  return;
602 
603  for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
604  if (MFI.isDeadObjectIndex(I))
605  continue;
606 
607  const AllocaInst *AI = MFI.getObjectAllocation(I);
608  if (!AI)
609  continue;
610 
611  SSPLayoutMap::const_iterator LI = Layout.find(AI);
612  if (LI == Layout.end())
613  continue;
614 
615  MFI.setObjectSSPLayout(I, LI->second);
616  }
617 }
llvm::Instruction::getPrevNonDebugInstruction
const Instruction * getPrevNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the previous non-debug instruction in the same basic block as 'this',...
Definition: Instruction.cpp:707
StackProtector.h
llvm
Definition: AllocatorList.h:23
llvm::TargetLoweringBase
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
Definition: TargetLowering.h:188
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::ReturnInst
Return a value (possibly void), from a function.
Definition: Instructions.h:2923
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:112
llvm::Intrinsic::getDeclaration
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1295
llvm::Type::getInt8PtrTy
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:256
IntrinsicInst.h
llvm::Function
Definition: Function.h:61
llvm::Attribute
Definition: Attributes.h:52
Pass.h
llvm::StackProtector::copyToMachineFrameInfo
void copyToMachineFrameInfo(MachineFrameInfo &MFI) const
Definition: StackProtector.cpp:599
llvm::StructType::element_iterator
Type::subtype_iterator element_iterator
Definition: DerivedTypes.h:317
llvm::StackProtector::runOnFunction
bool runOnFunction(Function &Fn) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
Definition: StackProtector.cpp:84
Statistic.h
llvm::IRBuilder<>
OptimizationRemarkEmitter.h
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:140
INITIALIZE_PASS_BEGIN
INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE, "Insert stack protectors", false, true) INITIALIZE_PASS_END(StackProtector
llvm::DenseMapIterator
Definition: DenseMap.h:56
llvm::MemoryLocation::Size
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
Definition: MemoryLocation.h:226
EnableSelectionDAGSP
static cl::opt< bool > EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true), cl::Hidden)
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:46
Module.h
EHPersonalities.h
llvm::MachineFrameInfo::SSPLK_LargeArray
@ SSPLK_LargeArray
Array or nested array >= SSP-buffer-size.
Definition: MachineFrameInfo.h:114
llvm::Function::hasFnAttribute
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:345
llvm::Optional
Definition: APInt.h:34
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:81
llvm::Module::getOrInsertFunction
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
llvm::ore::NV
DiagnosticInfoOptimizationBase::Argument NV
Definition: OptimizationRemarkEmitter.h:128
isMustTailCall
static bool isMustTailCall(Value *V)
Definition: InstructionCombining.cpp:2838
llvm::MipsISD::Ret
@ Ret
Definition: MipsISelLowering.h:116
llvm::ArrayType
Class to represent array types.
Definition: DerivedTypes.h:359
llvm::MachineFrameInfo::getObjectIndexEnd
int getObjectIndexEnd() const
Return one past the maximum frame object index.
Definition: MachineFrameInfo.h:391
llvm::StackProtector::ID
static char ID
Definition: StackProtector.h:105
INITIALIZE_PASS_END
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Definition: RegBankSelect.cpp:69
llvm::MDNode::get
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1198
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
llvm::Optional::hasValue
constexpr bool hasValue() const
Definition: Optional.h:286
Context
LLVMContext & Context
Definition: NVVMIntrRange.cpp:66
llvm::classifyEHPersonality
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Definition: EHPersonalities.cpp:21
Instruction.h
CommandLine.h
TargetLowering.h
TargetMachine.h
llvm::PassRegistry::getPassRegistry
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Definition: PassRegistry.cpp:31
Constants.h
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::Triple::isOSDarwin
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (macOS, iOS, tvOS or watchOS).
Definition: Triple.h:484
llvm::User
Definition: User.h:44
llvm::MachineFrameInfo::setObjectSSPLayout
void setObjectSSPLayout(int ObjectIdx, SSPLayoutKind Kind)
Definition: MachineFrameInfo.h:552
Intrinsics.h
llvm::StackProtector
Definition: StackProtector.h:37
llvm::MDBuilder::createBranchWeights
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
Definition: MDBuilder.cpp:37
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
llvm::LocationSize::getValue
uint64_t getValue() const
Definition: MemoryLocation.h:158
false
Definition: StackSlotColoring.cpp:142
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::Instruction
Definition: Instruction.h:45
llvm::DominatorTreeWrapperPass
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:281
MDBuilder.h
llvm::STATISTIC
STATISTIC(NumFunctions, "Total number of functions")
llvm::Function::hasPersonalityFn
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:820
DebugLoc.h
SmallPtrSet.h
llvm::Attribute::isStringAttribute
bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
Definition: Attributes.cpp:268
llvm::TargetLoweringBase::insertSSPDeclarations
virtual void insertSSPDeclarations(Module &M) const
Inserts necessary declarations for SSP (stack protection) purpose.
Definition: TargetLoweringBase.cpp:1944
llvm::MCID::Call
@ Call
Definition: MCInstrDesc.h:154
llvm::Attribute::getValueAsString
StringRef getValueAsString() const
Return the attribute's value as a string.
Definition: Attributes.cpp:304
llvm::StringRef::getAsInteger
std::enable_if_t< std::numeric_limits< T >::is_signed, bool > getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:511
llvm::BranchProbabilityInfo::getBranchProbStackProtector
static BranchProbability getBranchProbStackProtector(bool IsLikely)
Definition: BranchProbabilityInfo.h:200
Type.h
llvm::MachineFrameInfo::isDeadObjectIndex
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
Definition: MachineFrameInfo.h:734
Passes.h
llvm::TargetPassConfig
Target-Independent Code Generator Pass Configuration Options.
Definition: TargetPassConfig.h:84
BasicBlock.h
llvm::cl::opt< bool >
llvm::TargetOptions::EnableGlobalISel
unsigned EnableGlobalISel
EnableGlobalISel - This flag enables global instruction selection.
Definition: TargetOptions.h:228
BranchProbabilityInfo.h
llvm::MemoryLocation::getOrNone
static Optional< MemoryLocation > getOrNone(const Instruction *Inst)
Definition: MemoryLocation.cpp:88
llvm::StackProtector::StackProtector
StackProtector()
Definition: StackProtector.cpp:66
llvm::LocationSize::hasValue
bool hasValue() const
Definition: MemoryLocation.h:155
llvm::GlobalValue::getParent
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:572
llvm::StackProtectorGuards::None
@ None
llvm::ARM_MB::ST
@ ST
Definition: ARMBaseInfo.h:73
llvm::StackProtector::getAnalysisUsage
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: StackProtector.cpp:79
INITIALIZE_PASS_DEPENDENCY
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
MemoryLocation.h
DebugInfo.h
llvm::Triple::isOSOpenBSD
bool isOSOpenBSD() const
Definition: Triple.h:506
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::GetElementPtrInst
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:905
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:440
llvm::PointerType
Class to represent pointers.
Definition: DerivedTypes.h:634
TargetPassConfig.h
llvm::DenseMapBase::find
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
llvm::TargetMachine::Options
TargetOptions Options
Definition: TargetMachine.h:115
IRBuilder.h
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::TargetMachine
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
llvm::DominatorTree::isReachableFromEntry
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:328
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
llvm::MDNode
Metadata node.
Definition: Metadata.h:897
llvm::TargetOptions::EnableFastISel
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
Definition: TargetOptions.h:225
llvm::TargetLoweringBase::useStackGuardXorFP
virtual bool useStackGuardXorFP() const
If this function returns true, stack protection checks should XOR the frame pointer (or whichever poi...
Definition: TargetLowering.h:1769
llvm::APInt
Class for arbitrary precision integers.
Definition: APInt.h:71
TargetOptions.h
llvm::SPII::Load
@ Load
Definition: SparcInstrInfo.h:32
llvm::StackProtector::shouldEmitSDCheck
bool shouldEmitSDCheck(const BasicBlock &BB) const
Definition: StackProtector.cpp:595
llvm::OptimizationRemarkEmitter
The optimization diagnostic interface.
Definition: OptimizationRemarkEmitter.h:33
llvm::BasicBlock::moveAfter
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
Definition: BasicBlock.cpp:138
DataLayout.h
llvm::StructType
Class to represent struct types.
Definition: DerivedTypes.h:212
llvm::AnalysisUsage::addPreserved
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Definition: PassAnalysisSupport.h:98
llvm::BasicBlock::Create
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:100
llvm::Value::getContext
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:953
llvm::ilist_node_impl::getIterator
self_iterator getIterator()
Definition: ilist_node.h:81
TargetSubtargetInfo.h
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition: AArch64SLSHardening.cpp:76
CreatePrologue
static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, const TargetLoweringBase *TLI, AllocaInst *&AI)
Insert code into the entry block that stores the stack guard variable onto the stack:
Definition: StackProtector.cpp:415
llvm::LoadInst
An instruction for reading from memory.
Definition: Instructions.h:174
llvm::DenseMapBase::insert
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:207
llvm::EHPersonality
EHPersonality
Definition: EHPersonalities.h:22
llvm::DominatorTreeBase::addNewBlock
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
Definition: GenericDomTree.h:619
llvm::SPII::Store
@ Store
Definition: SparcInstrInfo.h:33
llvm::DenseMapBase::empty
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:97
llvm::MCID::Select
@ Select
Definition: MCInstrDesc.h:163
llvm::TargetLoweringBase::getTargetMachine
const TargetMachine & getTargetMachine() const
Definition: TargetLowering.h:335
Attributes.h
llvm::TargetLoweringBase::getSSPStackGuardCheck
virtual Function * getSSPStackGuardCheck(const Module &M) const
If the target has a standard stack protection check function that performs validation and error handl...
Definition: TargetLoweringBase.cpp:1961
llvm::DenseMapBase::end
iterator end()
Definition: DenseMap.h:83
llvm::X86::FirstMacroFusionInstKind::Cmp
@ Cmp
llvm::Function::getFnAttribute
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:355
llvm::StackProtectorGuards::TLS
@ TLS
llvm::TypeSize
Definition: TypeSize.h:417
Casting.h
Function.h
llvm::DominatorTreeWrapperPass::getDomTree
DominatorTree & getDomTree()
Definition: Dominators.h:289
llvm::Function::getPersonalityFn
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1709
protectors
Insert stack protectors
Definition: StackProtector.cpp:75
llvm::MDBuilder
Definition: MDBuilder.h:35
llvm::Type::getVoidTy
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:187
llvm::MachineFrameInfo
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
Definition: MachineFrameInfo.h:107
llvm::OptimizationRemark
Diagnostic information for applied optimization remarks.
Definition: DiagnosticInfo.h:684
Instructions.h
llvm::TargetSubtargetInfo::getTargetLowering
virtual const TargetLowering * getTargetLowering() const
Definition: TargetSubtargetInfo.h:96
llvm::TargetMachine::getSubtargetImpl
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
Definition: TargetMachine.h:130
User.h
llvm::MachineFrameInfo::SSPLK_AddrOf
@ SSPLK_AddrOf
The address of this allocation is exposed and triggered protection.
Definition: MachineFrameInfo.h:118
Dominators.h
llvm::CallBase::getArgOperand
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1341
llvm::TargetMachine::getTargetTriple
const Triple & getTargetTriple() const
Definition: TargetMachine.h:123
llvm::MachineFrameInfo::SSPLK_SmallArray
@ SSPLK_SmallArray
Array or nested array < SSP-buffer-size.
Definition: MachineFrameInfo.h:116
stack
S is passed via registers r2 But gcc stores them to the stack
Definition: README.txt:189
DEBUG_TYPE
#define DEBUG_TYPE
Definition: StackProtector.cpp:55
llvm::FunctionCallee
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:164
llvm::Module::getDataLayout
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:397
DerivedTypes.h
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
getStackGuard
static Value * getStackGuard(const TargetLoweringBase *TLI, Module *M, IRBuilder<> &B, bool *SupportsSelectionDAGSP=nullptr)
Create a stack guard loading and populate whether SelectionDAG SSP is supported.
Definition: StackProtector.cpp:379
llvm::CallInst
This class represents a function call, abstracting a target machine's calling convention.
Definition: Instructions.h:1450
BB
Common register allocation spilling lr str ldr sxth r3 ldr mla r4 can lr mov lr str ldr sxth r3 mla r4 and then merge mul and lr str ldr sxth r3 mla r4 It also increase the likelihood the store may become dead bb27 Successors according to LLVM BB
Definition: README.txt:39
GEP
Hexagon Common GEP
Definition: HexagonCommonGEP.cpp:171
llvm::AnalysisUsage::addRequired
AnalysisUsage & addRequired()
Definition: PassAnalysisSupport.h:75
llvm::initializeStackProtectorPass
void initializeStackProtectorPass(PassRegistry &)
llvm::AllocaInst
an instruction to allocate memory on the stack
Definition: Instructions.h:61
findStackProtectorIntrinsic
static const CallInst * findStackProtectorIntrinsic(Function &F)
Search for the first call to the llvm.stackprotector intrinsic and return it if present.
Definition: StackProtector.cpp:253
true
basic Basic Alias true
Definition: BasicAliasAnalysis.cpp:1789
InitializePasses.h
llvm::Value
LLVM Value Representation.
Definition: Value.h:75
llvm::Value::users
iterator_range< user_iterator > users()
Definition: Value.h:434
llvm::TargetOptions::StackProtectorGuard
StackProtectorGuards StackProtectorGuard
Stack protector guard mode to use, e.g. tls, global.
Definition: TargetOptions.h:338
llvm::isFuncletEHPersonality
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
Definition: EHPersonalities.h:65
llvm::createStackProtectorPass
FunctionPass * createStackProtectorPass()
createStackProtectorPass - This pass adds stack protectors to functions.
Definition: StackProtector.cpp:77
llvm::Function::iterator
BasicBlockListType::iterator iterator
Definition: Function.h:66
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:38
llvm::TargetLoweringBase::getIRStackGuard
virtual Value * getIRStackGuard(IRBuilder<> &IRB) const
If the target has a standard location for the stack protector guard, returns the address of that loca...
Definition: TargetLoweringBase.cpp:1930
llvm::MachineFrameInfo::getObjectAllocation
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
Definition: MachineFrameInfo.h:496
llvm::DataLayout::getTypeAllocSize
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:498