LLVM  10.0.0svn
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"
22 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/DebugLoc.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Intrinsics.h"
40 #include "llvm/IR/MDBuilder.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/IR/User.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/Casting.h"
49 #include <utility>
50 
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "stack-protector"
54 
55 STATISTIC(NumFunProtected, "Number of functions protected");
56 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
57  " taken.");
58 
59 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
60  cl::init(true), cl::Hidden);
61 
62 char StackProtector::ID = 0;
63 
65  "Insert stack protectors", false, true)
68  "Insert stack protectors", false, true)
69 
70 FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
71 
75 }
76 
78  F = &Fn;
79  M = F->getParent();
81  getAnalysisIfAvailable<DominatorTreeWrapperPass>();
82  DT = DTWP ? &DTWP->getDomTree() : nullptr;
83  TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
84  Trip = TM->getTargetTriple();
85  TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
86  HasPrologue = false;
87  HasIRCheck = false;
88 
89  Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
90  if (Attr.isStringAttribute() &&
91  Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
92  return false; // Invalid integer string
93 
94  if (!RequiresStackProtector())
95  return false;
96 
97  // TODO(etienneb): Functions with funclets are not correctly supported now.
98  // Do nothing if this is funclet-based personality.
99  if (Fn.hasPersonalityFn()) {
101  if (isFuncletEHPersonality(Personality))
102  return false;
103  }
104 
105  ++NumFunProtected;
106  return InsertStackProtectors();
107 }
108 
109 /// \param [out] IsLarge is set to true if a protectable array is found and
110 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
111 /// multiple arrays, this gets set if any of them is large.
112 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
113  bool Strong,
114  bool InStruct) const {
115  if (!Ty)
116  return false;
117  if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
118  if (!AT->getElementType()->isIntegerTy(8)) {
119  // If we're on a non-Darwin platform or we're inside of a structure, don't
120  // add stack protectors unless the array is a character array.
121  // However, in strong mode any array, regardless of type and size,
122  // triggers a protector.
123  if (!Strong && (InStruct || !Trip.isOSDarwin()))
124  return false;
125  }
126 
127  // If an array has more than SSPBufferSize bytes of allocated space, then we
128  // emit stack protectors.
129  if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
130  IsLarge = true;
131  return true;
132  }
133 
134  if (Strong)
135  // Require a protector for all arrays in strong mode
136  return true;
137  }
138 
139  const StructType *ST = dyn_cast<StructType>(Ty);
140  if (!ST)
141  return false;
142 
143  bool NeedsProtector = false;
145  E = ST->element_end();
146  I != E; ++I)
147  if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
148  // If the element is a protectable array and is large (>= SSPBufferSize)
149  // then we are done. If the protectable array is not large, then
150  // keep looking in case a subsequent element is a large array.
151  if (IsLarge)
152  return true;
153  NeedsProtector = true;
154  }
155 
156  return NeedsProtector;
157 }
158 
159 bool StackProtector::HasAddressTaken(const Instruction *AI) {
160  for (const User *U : AI->users()) {
161  const auto *I = cast<Instruction>(U);
162  switch (I->getOpcode()) {
163  case Instruction::Store:
164  if (AI == cast<StoreInst>(I)->getValueOperand())
165  return true;
166  break;
167  case Instruction::AtomicCmpXchg:
168  // cmpxchg conceptually includes both a load and store from the same
169  // location. So, like store, the value being stored is what matters.
170  if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
171  return true;
172  break;
173  case Instruction::PtrToInt:
174  if (AI == cast<PtrToIntInst>(I)->getOperand(0))
175  return true;
176  break;
177  case Instruction::Call: {
178  // Ignore intrinsics that do not become real instructions.
179  // TODO: Narrow this to intrinsics that have store-like effects.
180  const auto *CI = cast<CallInst>(I);
181  if (!isa<DbgInfoIntrinsic>(CI) && !CI->isLifetimeStartOrEnd())
182  return true;
183  break;
184  }
185  case Instruction::Invoke:
186  return true;
187  case Instruction::BitCast:
188  case Instruction::GetElementPtr:
189  case Instruction::Select:
190  case Instruction::AddrSpaceCast:
191  if (HasAddressTaken(I))
192  return true;
193  break;
194  case Instruction::PHI: {
195  // Keep track of what PHI nodes we have already visited to ensure
196  // they are only visited once.
197  const auto *PN = cast<PHINode>(I);
198  if (VisitedPHIs.insert(PN).second)
199  if (HasAddressTaken(PN))
200  return true;
201  break;
202  }
203  case Instruction::Load:
204  case Instruction::AtomicRMW:
205  case Instruction::Ret:
206  // These instructions take an address operand, but have load-like or
207  // other innocuous behavior that should not trigger a stack protector.
208  // atomicrmw conceptually has both load and store semantics, but the
209  // value being stored must be integer; so if a pointer is being stored,
210  // we'll catch it in the PtrToInt case above.
211  break;
212  default:
213  // Conservatively return true for any instruction that takes an address
214  // operand, but is not handled above.
215  return true;
216  }
217  }
218  return false;
219 }
220 
221 /// Search for the first call to the llvm.stackprotector intrinsic and return it
222 /// if present.
224  for (const BasicBlock &BB : F)
225  for (const Instruction &I : BB)
226  if (const CallInst *CI = dyn_cast<CallInst>(&I))
227  if (CI->getCalledFunction() ==
228  Intrinsic::getDeclaration(F.getParent(), Intrinsic::stackprotector))
229  return CI;
230  return nullptr;
231 }
232 
233 /// Check whether or not this function needs a stack protector based
234 /// upon the stack protector level.
235 ///
236 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
237 /// The standard heuristic which will add a guard variable to functions that
238 /// call alloca with a either a variable size or a size >= SSPBufferSize,
239 /// functions with character buffers larger than SSPBufferSize, and functions
240 /// with aggregates containing character buffers larger than SSPBufferSize. The
241 /// strong heuristic will add a guard variables to functions that call alloca
242 /// regardless of size, functions with any buffer regardless of type and size,
243 /// functions with aggregates that contain any buffer regardless of type and
244 /// size, and functions that contain stack-based variables that have had their
245 /// address taken.
246 bool StackProtector::RequiresStackProtector() {
247  bool Strong = false;
248  bool NeedsProtector = false;
249  HasPrologue = findStackProtectorIntrinsic(*F);
250 
251  if (F->hasFnAttribute(Attribute::SafeStack))
252  return false;
253 
254  // We are constructing the OptimizationRemarkEmitter on the fly rather than
255  // using the analysis pass to avoid building DominatorTree and LoopInfo which
256  // are not available this late in the IR pipeline.
258 
259  if (F->hasFnAttribute(Attribute::StackProtectReq)) {
260  ORE.emit([&]() {
261  return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
262  << "Stack protection applied to function "
263  << ore::NV("Function", F)
264  << " due to a function attribute or command-line switch";
265  });
266  NeedsProtector = true;
267  Strong = true; // Use the same heuristic as strong to determine SSPLayout
268  } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
269  Strong = true;
270  else if (HasPrologue)
271  NeedsProtector = true;
272  else if (!F->hasFnAttribute(Attribute::StackProtect))
273  return false;
274 
275  for (const BasicBlock &BB : *F) {
276  for (const Instruction &I : BB) {
277  if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
278  if (AI->isArrayAllocation()) {
279  auto RemarkBuilder = [&]() {
280  return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
281  &I)
282  << "Stack protection applied to function "
283  << ore::NV("Function", F)
284  << " due to a call to alloca or use of a variable length "
285  "array";
286  };
287  if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
288  if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
289  // A call to alloca with size >= SSPBufferSize requires
290  // stack protectors.
291  Layout.insert(std::make_pair(AI,
293  ORE.emit(RemarkBuilder);
294  NeedsProtector = true;
295  } else if (Strong) {
296  // Require protectors for all alloca calls in strong mode.
297  Layout.insert(std::make_pair(AI,
299  ORE.emit(RemarkBuilder);
300  NeedsProtector = true;
301  }
302  } else {
303  // A call to alloca with a variable size requires protectors.
304  Layout.insert(std::make_pair(AI,
306  ORE.emit(RemarkBuilder);
307  NeedsProtector = true;
308  }
309  continue;
310  }
311 
312  bool IsLarge = false;
313  if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
314  Layout.insert(std::make_pair(AI, IsLarge
317  ORE.emit([&]() {
318  return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
319  << "Stack protection applied to function "
320  << ore::NV("Function", F)
321  << " due to a stack allocated buffer or struct containing a "
322  "buffer";
323  });
324  NeedsProtector = true;
325  continue;
326  }
327 
328  if (Strong && HasAddressTaken(AI)) {
329  ++NumAddrTaken;
330  Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
331  ORE.emit([&]() {
332  return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
333  &I)
334  << "Stack protection applied to function "
335  << ore::NV("Function", F)
336  << " due to the address of a local variable being taken";
337  });
338  NeedsProtector = true;
339  }
340  }
341  }
342  }
343 
344  return NeedsProtector;
345 }
346 
347 /// Create a stack guard loading and populate whether SelectionDAG SSP is
348 /// supported.
350  IRBuilder<> &B,
351  bool *SupportsSelectionDAGSP = nullptr) {
352  if (Value *Guard = TLI->getIRStackGuard(B))
353  return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard");
354 
355  // Use SelectionDAG SSP handling, since there isn't an IR guard.
356  //
357  // This is more or less weird, since we optionally output whether we
358  // should perform a SelectionDAG SP here. The reason is that it's strictly
359  // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
360  // mutating. There is no way to get this bit without mutating the IR, so
361  // getting this bit has to happen in this right time.
362  //
363  // We could have define a new function TLI::supportsSelectionDAGSP(), but that
364  // will put more burden on the backends' overriding work, especially when it
365  // actually conveys the same information getIRStackGuard() already gives.
366  if (SupportsSelectionDAGSP)
367  *SupportsSelectionDAGSP = true;
368  TLI->insertSSPDeclarations(*M);
369  return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
370 }
371 
372 /// Insert code into the entry block that stores the stack guard
373 /// variable onto the stack:
374 ///
375 /// entry:
376 /// StackGuardSlot = alloca i8*
377 /// StackGuard = <stack guard>
378 /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
379 ///
380 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
381 /// node.
382 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
383  const TargetLoweringBase *TLI, AllocaInst *&AI) {
384  bool SupportsSelectionDAGSP = false;
385  IRBuilder<> B(&F->getEntryBlock().front());
386  PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
387  AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
388 
389  Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
390  B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
391  {GuardSlot, AI});
392  return SupportsSelectionDAGSP;
393 }
394 
395 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
396 /// function.
397 ///
398 /// - The prologue code loads and stores the stack guard onto the stack.
399 /// - The epilogue checks the value stored in the prologue against the original
400 /// value. It calls __stack_chk_fail if they differ.
401 bool StackProtector::InsertStackProtectors() {
402  // If the target wants to XOR the frame pointer into the guard value, it's
403  // impossible to emit the check in IR, so the target *must* support stack
404  // protection in SDAG.
405  bool SupportsSelectionDAGSP =
406  TLI->useStackGuardXorFP() ||
409  AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
410 
411  for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
412  BasicBlock *BB = &*I++;
414  if (!RI)
415  continue;
416 
417  // Generate prologue instrumentation if not already generated.
418  if (!HasPrologue) {
419  HasPrologue = true;
420  SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
421  }
422 
423  // SelectionDAG based code generation. Nothing else needs to be done here.
424  // The epilogue instrumentation is postponed to SelectionDAG.
425  if (SupportsSelectionDAGSP)
426  break;
427 
428  // Find the stack guard slot if the prologue was not created by this pass
429  // itself via a previous call to CreatePrologue().
430  if (!AI) {
431  const CallInst *SPCall = findStackProtectorIntrinsic(*F);
432  assert(SPCall && "Call to llvm.stackprotector is missing");
433  AI = cast<AllocaInst>(SPCall->getArgOperand(1));
434  }
435 
436  // Set HasIRCheck to true, so that SelectionDAG will not generate its own
437  // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
438  // instrumentation has already been generated.
439  HasIRCheck = true;
440 
441  // Generate epilogue instrumentation. The epilogue intrumentation can be
442  // function-based or inlined depending on which mechanism the target is
443  // providing.
444  if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
445  // Generate the function-based epilogue instrumentation.
446  // The target provides a guard check function, generate a call to it.
447  IRBuilder<> B(RI);
448  LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard");
449  CallInst *Call = B.CreateCall(GuardCheck, {Guard});
450  Call->setAttributes(GuardCheck->getAttributes());
451  Call->setCallingConv(GuardCheck->getCallingConv());
452  } else {
453  // Generate the epilogue with inline instrumentation.
454  // If we do not support SelectionDAG based tail calls, generate IR level
455  // tail calls.
456  //
457  // For each block with a return instruction, convert this:
458  //
459  // return:
460  // ...
461  // ret ...
462  //
463  // into this:
464  //
465  // return:
466  // ...
467  // %1 = <stack guard>
468  // %2 = load StackGuardSlot
469  // %3 = cmp i1 %1, %2
470  // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
471  //
472  // SP_return:
473  // ret ...
474  //
475  // CallStackCheckFailBlk:
476  // call void @__stack_chk_fail()
477  // unreachable
478 
479  // Create the FailBB. We duplicate the BB every time since the MI tail
480  // merge pass will merge together all of the various BB into one including
481  // fail BB generated by the stack protector pseudo instruction.
482  BasicBlock *FailBB = CreateFailBB();
483 
484  // Split the basic block before the return instruction.
485  BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
486 
487  // Update the dominator tree if we need to.
488  if (DT && DT->isReachableFromEntry(BB)) {
489  DT->addNewBlock(NewBB, BB);
490  DT->addNewBlock(FailBB, BB);
491  }
492 
493  // Remove default branch instruction to the new BB.
495 
496  // Move the newly created basic block to the point right after the old
497  // basic block so that it's in the "fall through" position.
498  NewBB->moveAfter(BB);
499 
500  // Generate the stack protector instructions in the old basic block.
501  IRBuilder<> B(BB);
502  Value *Guard = getStackGuard(TLI, M, B);
503  LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
504  Value *Cmp = B.CreateICmpEQ(Guard, LI2);
505  auto SuccessProb =
507  auto FailureProb =
509  MDNode *Weights = MDBuilder(F->getContext())
510  .createBranchWeights(SuccessProb.getNumerator(),
511  FailureProb.getNumerator());
512  B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
513  }
514  }
515 
516  // Return if we didn't modify any basic blocks. i.e., there are no return
517  // statements in the function.
518  return HasPrologue;
519 }
520 
521 /// CreateFailBB - Create a basic block to jump to when the stack protector
522 /// check fails.
523 BasicBlock *StackProtector::CreateFailBB() {
525  BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
526  IRBuilder<> B(FailBB);
528  if (Trip.isOSOpenBSD()) {
529  FunctionCallee StackChkFail = M->getOrInsertFunction(
530  "__stack_smash_handler", Type::getVoidTy(Context),
531  Type::getInt8PtrTy(Context));
532 
533  B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
534  } else {
535  FunctionCallee StackChkFail =
536  M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
537 
538  B.CreateCall(StackChkFail, {});
539  }
540  B.CreateUnreachable();
541  return FailBB;
542 }
543 
545  return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
546 }
547 
549  if (Layout.empty())
550  return;
551 
552  for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
553  if (MFI.isDeadObjectIndex(I))
554  continue;
555 
556  const AllocaInst *AI = MFI.getObjectAllocation(I);
557  if (!AI)
558  continue;
559 
560  SSPLayoutMap::const_iterator LI = Layout.find(AI);
561  if (LI == Layout.end())
562  continue;
563 
564  MFI.setObjectSSPLayout(I, LI->second);
565  }
566 }
Return a value (possibly void), from a function.
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
Definition: Triple.h:481
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional &#39;br Cond, TrueDest, FalseDest&#39; instruction.
Definition: IRBuilder.h:890
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:21
LLVMContext & Context
DiagnosticInfoOptimizationBase::Argument NV
This class represents lattice values for constants.
Definition: AllocatorList.h:23
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ty, Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool...
Definition: IRBuilder.h:1575
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
iterator end()
Definition: Function.h:687
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:170
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
This class represents a function call, abstracting a target machine&#39;s calling convention.
virtual const TargetLowering * getTargetLowering() const
void copyToMachineFrameInfo(MachineFrameInfo &MFI) const
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:743
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:323
STATISTIC(NumFunctions, "Total number of functions")
Metadata node.
Definition: Metadata.h:863
block Block Frequency true
An instruction for reading from memory.
Definition: Instructions.h:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:144
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:299
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: ...
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1241
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:195
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
Definition: Attributes.cpp:191
Class to represent struct types.
Definition: DerivedTypes.h:238
static cl::opt< bool > EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true), cl::Hidden)
The address of this allocation is exposed and triggered protection.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:779
This file contains the simple types necessary to represent the attributes associated with functions a...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
DominatorTree & getDomTree()
Definition: Dominators.h:269
Target-Independent Code Generator Pass Configuration Options.
Class to represent array types.
Definition: DerivedTypes.h:408
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:737
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:156
iterator begin()
Definition: Function.h:685
Type::subtype_iterator element_iterator
Definition: DerivedTypes.h:338
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:1093
Value * getOperand(unsigned i) const
Definition: User.h:169
Class to represent pointers.
Definition: DerivedTypes.h:579
bool runOnFunction(Function &Fn) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
#define DEBUG_TYPE
void setObjectSSPLayout(int ObjectIdx, SSPLayoutKind Kind)
Array or nested array >= SSP-buffer-size.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
unsigned EnableGlobalISel
EnableGlobalISel - This flag enables global instruction selection.
const BasicBlock & getEntryBlock() const
Definition: Function.h:669
virtual Value * getIRStackGuard(IRBuilder<> &IRB) const
If the target has a standard location for the stack protector guard, returns the address of that loca...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
UnreachableInst * CreateUnreachable()
Definition: IRBuilder.h:1050
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1522
bool isOSOpenBSD() const
Definition: Triple.h:497
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
Definition: BasicBlock.h:285
Diagnostic information for applied optimization remarks.
element_iterator element_end() const
Definition: DerivedTypes.h:341
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:165
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1348
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
const Triple & getTargetTriple() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:99
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2101
self_iterator getIterator()
Definition: ilist_node.h:81
FunctionPass * createStackProtectorPass()
createStackProtectorPass - This pass adds stack protectors to functions.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:205
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:224
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:421
virtual bool useStackGuardXorFP() const
If this function returns true, stack protection checks should XOR the frame pointer (or whichever poi...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:492
static const CallInst * findStackProtectorIntrinsic(Function &F)
Search for the first call to the llvm.stackprotector intrinsic and return it if present.
Iterator for intrusive lists based on ilist_node.
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:134
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file. ...
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
Insert stack protectors
Module.h This file contains the declarations for the Module class.
virtual Function * getSSPStackGuardCheck(const Module &M) const
If the target has a standard stack protection check function that performs validation and error handl...
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target&#39;s TargetSubtargetInf...
Constant * CreateGlobalStringPtr(StringRef Str, const Twine &Name="", unsigned AddressSpace=0)
Same as CreateGlobalString, but return a pointer with "i8*" type instead of a pointer to array of i8...
Definition: IRBuilder.h:1860
iterator_range< user_iterator > users()
Definition: Value.h:420
element_iterator element_begin() const
Definition: DerivedTypes.h:340
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE, "Insert stack protectors", false, true) INITIALIZE_PASS_END(StackProtector
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:220
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
TargetOptions Options
#define I(x, y, z)
Definition: MD5.cpp:58
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
iterator end()
Definition: DenseMap.h:82
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
Definition: InstrTypes.h:1370
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2239
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:414
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:96
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:74
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1465
Array or nested array < SSP-buffer-size.
virtual void insertSSPDeclarations(Module &M) const
Inserts necessary declarations for SSP (stack protection) purpose.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:333
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:259
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.
bool shouldEmitSDCheck(const BasicBlock &BB) const
The optimization diagnostic interface.
static BranchProbability getBranchProbStackProtector(bool IsLikely)
This file describes how to lower LLVM code to machine code.
an instruction to allocate memory on the stack
Definition: Instructions.h:59