LLVM  10.0.0
SafeStack.cpp
Go to the documentation of this file.
1 //===- SafeStack.cpp - Safe Stack 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 splits the stack into the safe stack (kept as-is for LLVM backend)
10 // and the unsafe stack (explicitly allocated and managed through the runtime
11 // support library).
12 //
13 // http://clang.llvm.org/docs/SafeStack.html
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "SafeStackColoring.h"
18 #include "SafeStackLayout.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/LoopInfo.h"
34 #include "llvm/IR/Argument.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/ConstantRange.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DIBuilder.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/IRBuilder.h"
45 #include "llvm/IR/InstIterator.h"
46 #include "llvm/IR/Instruction.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/MDBuilder.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/Type.h"
53 #include "llvm/IR/Use.h"
54 #include "llvm/IR/User.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/InitializePasses.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/Debug.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstdint>
70 #include <string>
71 #include <utility>
72 
73 using namespace llvm;
74 using namespace llvm::safestack;
75 
76 #define DEBUG_TYPE "safe-stack"
77 
78 namespace llvm {
79 
80 STATISTIC(NumFunctions, "Total number of functions");
81 STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
82 STATISTIC(NumUnsafeStackRestorePointsFunctions,
83  "Number of functions that use setjmp or exceptions");
84 
85 STATISTIC(NumAllocas, "Total number of allocas");
86 STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
87 STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
88 STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
89 STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
90 
91 } // namespace llvm
92 
93 /// Use __safestack_pointer_address even if the platform has a faster way of
94 /// access safe stack pointer.
95 static cl::opt<bool>
96  SafeStackUsePointerAddress("safestack-use-pointer-address",
97  cl::init(false), cl::Hidden);
98 
99 
100 namespace {
101 
102 /// Rewrite an SCEV expression for a memory access address to an expression that
103 /// represents offset from the given alloca.
104 ///
105 /// The implementation simply replaces all mentions of the alloca with zero.
106 class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
107  const Value *AllocaPtr;
108 
109 public:
110  AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
111  : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
112 
113  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
114  if (Expr->getValue() == AllocaPtr)
115  return SE.getZero(Expr->getType());
116  return Expr;
117  }
118 };
119 
120 /// The SafeStack pass splits the stack of each function into the safe
121 /// stack, which is only accessed through memory safe dereferences (as
122 /// determined statically), and the unsafe stack, which contains all
123 /// local variables that are accessed in ways that we can't prove to
124 /// be safe.
125 class SafeStack {
126  Function &F;
127  const TargetLoweringBase &TL;
128  const DataLayout &DL;
129  ScalarEvolution &SE;
130 
131  Type *StackPtrTy;
132  Type *IntPtrTy;
133  Type *Int32Ty;
134  Type *Int8Ty;
135 
136  Value *UnsafeStackPtr = nullptr;
137 
138  /// Unsafe stack alignment. Each stack frame must ensure that the stack is
139  /// aligned to this value. We need to re-align the unsafe stack if the
140  /// alignment of any object on the stack exceeds this value.
141  ///
142  /// 16 seems like a reasonable upper bound on the alignment of objects that we
143  /// might expect to appear on the stack on most common targets.
144  enum { StackAlignment = 16 };
145 
146  /// Return the value of the stack canary.
148 
149  /// Load stack guard from the frame and check if it has changed.
150  void checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
151  AllocaInst *StackGuardSlot, Value *StackGuard);
152 
153  /// Find all static allocas, dynamic allocas, return instructions and
154  /// stack restore points (exception unwind blocks and setjmp calls) in the
155  /// given function and append them to the respective vectors.
156  void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
157  SmallVectorImpl<AllocaInst *> &DynamicAllocas,
158  SmallVectorImpl<Argument *> &ByValArguments,
160  SmallVectorImpl<Instruction *> &StackRestorePoints);
161 
162  /// Calculate the allocation size of a given alloca. Returns 0 if the
163  /// size can not be statically determined.
164  uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
165 
166  /// Allocate space for all static allocas in \p StaticAllocas,
167  /// replace allocas with pointers into the unsafe stack and generate code to
168  /// restore the stack pointer before all return instructions in \p Returns.
169  ///
170  /// \returns A pointer to the top of the unsafe stack after all unsafe static
171  /// allocas are allocated.
172  Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
173  ArrayRef<AllocaInst *> StaticAllocas,
174  ArrayRef<Argument *> ByValArguments,
175  ArrayRef<ReturnInst *> Returns,
176  Instruction *BasePointer,
177  AllocaInst *StackGuardSlot);
178 
179  /// Generate code to restore the stack after all stack restore points
180  /// in \p StackRestorePoints.
181  ///
182  /// \returns A local variable in which to maintain the dynamic top of the
183  /// unsafe stack if needed.
184  AllocaInst *
185  createStackRestorePoints(IRBuilder<> &IRB, Function &F,
186  ArrayRef<Instruction *> StackRestorePoints,
187  Value *StaticTop, bool NeedDynamicTop);
188 
189  /// Replace all allocas in \p DynamicAllocas with code to allocate
190  /// space dynamically on the unsafe stack and store the dynamic unsafe stack
191  /// top to \p DynamicTop if non-null.
192  void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
193  AllocaInst *DynamicTop,
194  ArrayRef<AllocaInst *> DynamicAllocas);
195 
196  bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
197 
198  bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
199  const Value *AllocaPtr, uint64_t AllocaSize);
200  bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
201  uint64_t AllocaSize);
202 
203  bool ShouldInlinePointerAddress(CallSite &CS);
204  void TryInlinePointerAddress();
205 
206 public:
207  SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL,
208  ScalarEvolution &SE)
209  : F(F), TL(TL), DL(DL), SE(SE),
210  StackPtrTy(Type::getInt8PtrTy(F.getContext())),
211  IntPtrTy(DL.getIntPtrType(F.getContext())),
213  Int8Ty(Type::getInt8Ty(F.getContext())) {}
214 
215  // Run the transformation on the associated function.
216  // Returns whether the function was changed.
217  bool run();
218 };
219 
220 uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
221  uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType());
222  if (AI->isArrayAllocation()) {
223  auto C = dyn_cast<ConstantInt>(AI->getArraySize());
224  if (!C)
225  return 0;
226  Size *= C->getZExtValue();
227  }
228  return Size;
229 }
230 
231 bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
232  const Value *AllocaPtr, uint64_t AllocaSize) {
233  AllocaOffsetRewriter Rewriter(SE, AllocaPtr);
234  const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
235 
236  uint64_t BitWidth = SE.getTypeSizeInBits(Expr->getType());
237  ConstantRange AccessStartRange = SE.getUnsignedRange(Expr);
238  ConstantRange SizeRange =
239  ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
240  ConstantRange AccessRange = AccessStartRange.add(SizeRange);
241  ConstantRange AllocaRange =
242  ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
243  bool Safe = AllocaRange.contains(AccessRange);
244 
245  LLVM_DEBUG(
246  dbgs() << "[SafeStack] "
247  << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
248  << *AllocaPtr << "\n"
249  << " Access " << *Addr << "\n"
250  << " SCEV " << *Expr
251  << " U: " << SE.getUnsignedRange(Expr)
252  << ", S: " << SE.getSignedRange(Expr) << "\n"
253  << " Range " << AccessRange << "\n"
254  << " AllocaRange " << AllocaRange << "\n"
255  << " " << (Safe ? "safe" : "unsafe") << "\n");
256 
257  return Safe;
258 }
259 
260 bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
261  const Value *AllocaPtr,
262  uint64_t AllocaSize) {
263  if (auto MTI = dyn_cast<MemTransferInst>(MI)) {
264  if (MTI->getRawSource() != U && MTI->getRawDest() != U)
265  return true;
266  } else {
267  if (MI->getRawDest() != U)
268  return true;
269  }
270 
271  const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
272  // Non-constant size => unsafe. FIXME: try SCEV getRange.
273  if (!Len) return false;
274  return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
275 }
276 
277 /// Check whether a given allocation must be put on the safe
278 /// stack or not. The function analyzes all uses of AI and checks whether it is
279 /// only accessed in a memory safe way (as decided statically).
280 bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
281  // Go through all uses of this alloca and check whether all accesses to the
282  // allocated object are statically known to be memory safe and, hence, the
283  // object can be placed on the safe stack.
286  WorkList.push_back(AllocaPtr);
287 
288  // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
289  while (!WorkList.empty()) {
290  const Value *V = WorkList.pop_back_val();
291  for (const Use &UI : V->uses()) {
292  auto I = cast<const Instruction>(UI.getUser());
293  assert(V == UI.get());
294 
295  switch (I->getOpcode()) {
296  case Instruction::Load:
297  if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr,
298  AllocaSize))
299  return false;
300  break;
301 
302  case Instruction::VAArg:
303  // "va-arg" from a pointer is safe.
304  break;
305  case Instruction::Store:
306  if (V == I->getOperand(0)) {
307  // Stored the pointer - conservatively assume it may be unsafe.
308  LLVM_DEBUG(dbgs()
309  << "[SafeStack] Unsafe alloca: " << *AllocaPtr
310  << "\n store of address: " << *I << "\n");
311  return false;
312  }
313 
314  if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()),
315  AllocaPtr, AllocaSize))
316  return false;
317  break;
318 
319  case Instruction::Ret:
320  // Information leak.
321  return false;
322 
323  case Instruction::Call:
324  case Instruction::Invoke: {
325  ImmutableCallSite CS(I);
326 
327  if (I->isLifetimeStartOrEnd())
328  continue;
329 
330  if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
331  if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
332  LLVM_DEBUG(dbgs()
333  << "[SafeStack] Unsafe alloca: " << *AllocaPtr
334  << "\n unsafe memintrinsic: " << *I << "\n");
335  return false;
336  }
337  continue;
338  }
339 
340  // LLVM 'nocapture' attribute is only set for arguments whose address
341  // is not stored, passed around, or used in any other non-trivial way.
342  // We assume that passing a pointer to an object as a 'nocapture
343  // readnone' argument is safe.
344  // FIXME: a more precise solution would require an interprocedural
345  // analysis here, which would look at all uses of an argument inside
346  // the function being called.
348  for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
349  if (A->get() == V)
350  if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
351  CS.doesNotAccessMemory()))) {
352  LLVM_DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
353  << "\n unsafe call: " << *I << "\n");
354  return false;
355  }
356  continue;
357  }
358 
359  default:
360  if (Visited.insert(I).second)
361  WorkList.push_back(cast<const Instruction>(I));
362  }
363  }
364  }
365 
366  // All uses of the alloca are safe, we can place it on the safe stack.
367  return true;
368 }
369 
371  Value *StackGuardVar = TL.getIRStackGuard(IRB);
372  if (!StackGuardVar)
373  StackGuardVar =
374  F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
375  return IRB.CreateLoad(StackPtrTy, StackGuardVar, "StackGuard");
376 }
377 
378 void SafeStack::findInsts(Function &F,
379  SmallVectorImpl<AllocaInst *> &StaticAllocas,
380  SmallVectorImpl<AllocaInst *> &DynamicAllocas,
381  SmallVectorImpl<Argument *> &ByValArguments,
383  SmallVectorImpl<Instruction *> &StackRestorePoints) {
384  for (Instruction &I : instructions(&F)) {
385  if (auto AI = dyn_cast<AllocaInst>(&I)) {
386  ++NumAllocas;
387 
388  uint64_t Size = getStaticAllocaAllocationSize(AI);
389  if (IsSafeStackAlloca(AI, Size))
390  continue;
391 
392  if (AI->isStaticAlloca()) {
393  ++NumUnsafeStaticAllocas;
394  StaticAllocas.push_back(AI);
395  } else {
396  ++NumUnsafeDynamicAllocas;
397  DynamicAllocas.push_back(AI);
398  }
399  } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
400  Returns.push_back(RI);
401  } else if (auto CI = dyn_cast<CallInst>(&I)) {
402  // setjmps require stack restore.
403  if (CI->getCalledFunction() && CI->canReturnTwice())
404  StackRestorePoints.push_back(CI);
405  } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
406  // Exception landing pads require stack restore.
407  StackRestorePoints.push_back(LP);
408  } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
409  if (II->getIntrinsicID() == Intrinsic::gcroot)
411  "gcroot intrinsic not compatible with safestack attribute");
412  }
413  }
414  for (Argument &Arg : F.args()) {
415  if (!Arg.hasByValAttr())
416  continue;
417  uint64_t Size =
418  DL.getTypeStoreSize(Arg.getType()->getPointerElementType());
419  if (IsSafeStackAlloca(&Arg, Size))
420  continue;
421 
422  ++NumUnsafeByValArguments;
423  ByValArguments.push_back(&Arg);
424  }
425 }
426 
427 AllocaInst *
428 SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
429  ArrayRef<Instruction *> StackRestorePoints,
430  Value *StaticTop, bool NeedDynamicTop) {
431  assert(StaticTop && "The stack top isn't set.");
432 
433  if (StackRestorePoints.empty())
434  return nullptr;
435 
436  // We need the current value of the shadow stack pointer to restore
437  // after longjmp or exception catching.
438 
439  // FIXME: On some platforms this could be handled by the longjmp/exception
440  // runtime itself.
441 
442  AllocaInst *DynamicTop = nullptr;
443  if (NeedDynamicTop) {
444  // If we also have dynamic alloca's, the stack pointer value changes
445  // throughout the function. For now we store it in an alloca.
446  DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
447  "unsafe_stack_dynamic_ptr");
448  IRB.CreateStore(StaticTop, DynamicTop);
449  }
450 
451  // Restore current stack pointer after longjmp/exception catch.
452  for (Instruction *I : StackRestorePoints) {
453  ++NumUnsafeStackRestorePoints;
454 
455  IRB.SetInsertPoint(I->getNextNode());
456  Value *CurrentTop =
457  DynamicTop ? IRB.CreateLoad(StackPtrTy, DynamicTop) : StaticTop;
458  IRB.CreateStore(CurrentTop, UnsafeStackPtr);
459  }
460 
461  return DynamicTop;
462 }
463 
464 void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
465  AllocaInst *StackGuardSlot, Value *StackGuard) {
466  Value *V = IRB.CreateLoad(StackPtrTy, StackGuardSlot);
467  Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
468 
470  auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
471  MDNode *Weights = MDBuilder(F.getContext())
472  .createBranchWeights(SuccessProb.getNumerator(),
473  FailureProb.getNumerator());
474  Instruction *CheckTerm =
475  SplitBlockAndInsertIfThen(Cmp, &RI,
476  /* Unreachable */ true, Weights);
477  IRBuilder<> IRBFail(CheckTerm);
478  // FIXME: respect -fsanitize-trap / -ftrap-function here?
479  FunctionCallee StackChkFail =
480  F.getParent()->getOrInsertFunction("__stack_chk_fail", IRB.getVoidTy());
481  IRBFail.CreateCall(StackChkFail, {});
482 }
483 
484 /// We explicitly compute and set the unsafe stack layout for all unsafe
485 /// static alloca instructions. We save the unsafe "base pointer" in the
486 /// prologue into a local variable and restore it in the epilogue.
487 Value *SafeStack::moveStaticAllocasToUnsafeStack(
488  IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
489  ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns,
490  Instruction *BasePointer, AllocaInst *StackGuardSlot) {
491  if (StaticAllocas.empty() && ByValArguments.empty())
492  return BasePointer;
493 
494  DIBuilder DIB(*F.getParent());
495 
496  StackColoring SSC(F, StaticAllocas);
497  SSC.run();
498  SSC.removeAllMarkers();
499 
500  // Unsafe stack always grows down.
501  StackLayout SSL(StackAlignment);
502  if (StackGuardSlot) {
503  Type *Ty = StackGuardSlot->getAllocatedType();
504  unsigned Align =
505  std::max(DL.getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
506  SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
507  Align, SSC.getFullLiveRange());
508  }
509 
510  for (Argument *Arg : ByValArguments) {
511  Type *Ty = Arg->getType()->getPointerElementType();
512  uint64_t Size = DL.getTypeStoreSize(Ty);
513  if (Size == 0)
514  Size = 1; // Don't create zero-sized stack objects.
515 
516  // Ensure the object is properly aligned.
517  unsigned Align = std::max((unsigned)DL.getPrefTypeAlignment(Ty),
518  Arg->getParamAlignment());
519  SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
520  }
521 
522  for (AllocaInst *AI : StaticAllocas) {
523  Type *Ty = AI->getAllocatedType();
524  uint64_t Size = getStaticAllocaAllocationSize(AI);
525  if (Size == 0)
526  Size = 1; // Don't create zero-sized stack objects.
527 
528  // Ensure the object is properly aligned.
529  unsigned Align =
530  std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment());
531 
532  SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI));
533  }
534 
535  SSL.computeLayout();
536  unsigned FrameAlignment = SSL.getFrameAlignment();
537 
538  // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
539  // (AlignmentSkew).
540  if (FrameAlignment > StackAlignment) {
541  // Re-align the base pointer according to the max requested alignment.
542  assert(isPowerOf2_32(FrameAlignment));
543  IRB.SetInsertPoint(BasePointer->getNextNode());
544  BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
545  IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
546  ConstantInt::get(IntPtrTy, ~uint64_t(FrameAlignment - 1))),
547  StackPtrTy));
548  }
549 
550  IRB.SetInsertPoint(BasePointer->getNextNode());
551 
552  if (StackGuardSlot) {
553  unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
554  Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
555  ConstantInt::get(Int32Ty, -Offset));
556  Value *NewAI =
557  IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
558 
559  // Replace alloc with the new location.
560  StackGuardSlot->replaceAllUsesWith(NewAI);
561  StackGuardSlot->eraseFromParent();
562  }
563 
564  for (Argument *Arg : ByValArguments) {
565  unsigned Offset = SSL.getObjectOffset(Arg);
567  Type *Ty = Arg->getType()->getPointerElementType();
568 
569  uint64_t Size = DL.getTypeStoreSize(Ty);
570  if (Size == 0)
571  Size = 1; // Don't create zero-sized stack objects.
572 
573  Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
574  ConstantInt::get(Int32Ty, -Offset));
575  Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
576  Arg->getName() + ".unsafe-byval");
577 
578  // Replace alloc with the new location.
579  replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
581  Arg->replaceAllUsesWith(NewArg);
582  IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
583  IRB.CreateMemCpy(Off, Align, Arg, Arg->getParamAlign(), Size);
584  }
585 
586  // Allocate space for every unsafe static AllocaInst on the unsafe stack.
587  for (AllocaInst *AI : StaticAllocas) {
588  IRB.SetInsertPoint(AI);
589  unsigned Offset = SSL.getObjectOffset(AI);
590 
592  -Offset);
593  replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
594 
595  // Replace uses of the alloca with the new location.
596  // Insert address calculation close to each use to work around PR27844.
597  std::string Name = std::string(AI->getName()) + ".unsafe";
598  while (!AI->use_empty()) {
599  Use &U = *AI->use_begin();
600  Instruction *User = cast<Instruction>(U.getUser());
601 
602  Instruction *InsertBefore;
603  if (auto *PHI = dyn_cast<PHINode>(User))
604  InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
605  else
606  InsertBefore = User;
607 
608  IRBuilder<> IRBUser(InsertBefore);
609  Value *Off = IRBUser.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
610  ConstantInt::get(Int32Ty, -Offset));
611  Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
612 
613  if (auto *PHI = dyn_cast<PHINode>(User))
614  // PHI nodes may have multiple incoming edges from the same BB (why??),
615  // all must be updated at once with the same incoming value.
616  PHI->setIncomingValueForBlock(PHI->getIncomingBlock(U), Replacement);
617  else
618  U.set(Replacement);
619  }
620 
621  AI->eraseFromParent();
622  }
623 
624  // Re-align BasePointer so that our callees would see it aligned as
625  // expected.
626  // FIXME: no need to update BasePointer in leaf functions.
627  unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
628 
629  // Update shadow stack pointer in the function epilogue.
630  IRB.SetInsertPoint(BasePointer->getNextNode());
631 
632  Value *StaticTop =
633  IRB.CreateGEP(Int8Ty, BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
634  "unsafe_stack_static_top");
635  IRB.CreateStore(StaticTop, UnsafeStackPtr);
636  return StaticTop;
637 }
638 
639 void SafeStack::moveDynamicAllocasToUnsafeStack(
640  Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
641  ArrayRef<AllocaInst *> DynamicAllocas) {
642  DIBuilder DIB(*F.getParent());
643 
644  for (AllocaInst *AI : DynamicAllocas) {
645  IRBuilder<> IRB(AI);
646 
647  // Compute the new SP value (after AI).
648  Value *ArraySize = AI->getArraySize();
649  if (ArraySize->getType() != IntPtrTy)
650  ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
651 
652  Type *Ty = AI->getAllocatedType();
653  uint64_t TySize = DL.getTypeAllocSize(Ty);
654  Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
655 
656  Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(StackPtrTy, UnsafeStackPtr),
657  IntPtrTy);
658  SP = IRB.CreateSub(SP, Size);
659 
660  // Align the SP value to satisfy the AllocaInst, type and stack alignments.
661  unsigned Align = std::max(
662  std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()),
663  (unsigned)StackAlignment);
664 
665  assert(isPowerOf2_32(Align));
666  Value *NewTop = IRB.CreateIntToPtr(
667  IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
668  StackPtrTy);
669 
670  // Save the stack pointer.
671  IRB.CreateStore(NewTop, UnsafeStackPtr);
672  if (DynamicTop)
673  IRB.CreateStore(NewTop, DynamicTop);
674 
675  Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
676  if (AI->hasName() && isa<Instruction>(NewAI))
677  NewAI->takeName(AI);
678 
680  AI->replaceAllUsesWith(NewAI);
681  AI->eraseFromParent();
682  }
683 
684  if (!DynamicAllocas.empty()) {
685  // Now go through the instructions again, replacing stacksave/stackrestore.
686  for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
687  Instruction *I = &*(It++);
688  auto II = dyn_cast<IntrinsicInst>(I);
689  if (!II)
690  continue;
691 
692  if (II->getIntrinsicID() == Intrinsic::stacksave) {
693  IRBuilder<> IRB(II);
694  Instruction *LI = IRB.CreateLoad(StackPtrTy, UnsafeStackPtr);
695  LI->takeName(II);
696  II->replaceAllUsesWith(LI);
697  II->eraseFromParent();
698  } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
699  IRBuilder<> IRB(II);
700  Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
701  SI->takeName(II);
702  assert(II->use_empty());
703  II->eraseFromParent();
704  }
705  }
706  }
707 }
708 
709 bool SafeStack::ShouldInlinePointerAddress(CallSite &CS) {
711  if (CS.hasFnAttr(Attribute::AlwaysInline) && isInlineViable(*Callee))
712  return true;
713  if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
714  CS.isNoInline())
715  return false;
716  return true;
717 }
718 
719 void SafeStack::TryInlinePointerAddress() {
720  if (!isa<CallInst>(UnsafeStackPtr))
721  return;
722 
723  if(F.hasOptNone())
724  return;
725 
726  CallSite CS(UnsafeStackPtr);
728  if (!Callee || Callee->isDeclaration())
729  return;
730 
731  if (!ShouldInlinePointerAddress(CS))
732  return;
733 
734  InlineFunctionInfo IFI;
735  InlineFunction(CS, IFI);
736 }
737 
738 bool SafeStack::run() {
739  assert(F.hasFnAttribute(Attribute::SafeStack) &&
740  "Can't run SafeStack on a function without the attribute");
741  assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
742 
743  ++NumFunctions;
744 
745  SmallVector<AllocaInst *, 16> StaticAllocas;
746  SmallVector<AllocaInst *, 4> DynamicAllocas;
747  SmallVector<Argument *, 4> ByValArguments;
749 
750  // Collect all points where stack gets unwound and needs to be restored
751  // This is only necessary because the runtime (setjmp and unwind code) is
752  // not aware of the unsafe stack and won't unwind/restore it properly.
753  // To work around this problem without changing the runtime, we insert
754  // instrumentation to restore the unsafe stack pointer when necessary.
755  SmallVector<Instruction *, 4> StackRestorePoints;
756 
757  // Find all static and dynamic alloca instructions that must be moved to the
758  // unsafe stack, all return instructions and stack restore points.
759  findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
760  StackRestorePoints);
761 
762  if (StaticAllocas.empty() && DynamicAllocas.empty() &&
763  ByValArguments.empty() && StackRestorePoints.empty())
764  return false; // Nothing to do in this function.
765 
766  if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
767  !ByValArguments.empty())
768  ++NumUnsafeStackFunctions; // This function has the unsafe stack.
769 
770  if (!StackRestorePoints.empty())
771  ++NumUnsafeStackRestorePointsFunctions;
772 
773  IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
774  // Calls must always have a debug location, or else inlining breaks. So
775  // we explicitly set a artificial debug location here.
776  if (DISubprogram *SP = F.getSubprogram())
777  IRB.SetCurrentDebugLocation(DebugLoc::get(SP->getScopeLine(), 0, SP));
778  if (SafeStackUsePointerAddress) {
780  "__safestack_pointer_address", StackPtrTy->getPointerTo(0));
781  UnsafeStackPtr = IRB.CreateCall(Fn);
782  } else {
783  UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
784  }
785 
786  // Load the current stack pointer (we'll also use it as a base pointer).
787  // FIXME: use a dedicated register for it ?
788  Instruction *BasePointer =
789  IRB.CreateLoad(StackPtrTy, UnsafeStackPtr, false, "unsafe_stack_ptr");
790  assert(BasePointer->getType() == StackPtrTy);
791 
792  AllocaInst *StackGuardSlot = nullptr;
793  // FIXME: implement weaker forms of stack protector.
794  if (F.hasFnAttribute(Attribute::StackProtect) ||
795  F.hasFnAttribute(Attribute::StackProtectStrong) ||
796  F.hasFnAttribute(Attribute::StackProtectReq)) {
797  Value *StackGuard = getStackGuard(IRB, F);
798  StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
799  IRB.CreateStore(StackGuard, StackGuardSlot);
800 
801  for (ReturnInst *RI : Returns) {
802  IRBuilder<> IRBRet(RI);
803  checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
804  }
805  }
806 
807  // The top of the unsafe stack after all unsafe static allocas are
808  // allocated.
809  Value *StaticTop =
810  moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
811  Returns, BasePointer, StackGuardSlot);
812 
813  // Safe stack object that stores the current unsafe stack top. It is updated
814  // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
815  // This is only needed if we need to restore stack pointer after longjmp
816  // or exceptions, and we have dynamic allocations.
817  // FIXME: a better alternative might be to store the unsafe stack pointer
818  // before setjmp / invoke instructions.
819  AllocaInst *DynamicTop = createStackRestorePoints(
820  IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
821 
822  // Handle dynamic allocas.
823  moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
824  DynamicAllocas);
825 
826  // Restore the unsafe stack pointer before each return.
827  for (ReturnInst *RI : Returns) {
828  IRB.SetInsertPoint(RI);
829  IRB.CreateStore(BasePointer, UnsafeStackPtr);
830  }
831 
832  TryInlinePointerAddress();
833 
834  LLVM_DEBUG(dbgs() << "[SafeStack] safestack applied\n");
835  return true;
836 }
837 
838 class SafeStackLegacyPass : public FunctionPass {
839  const TargetMachine *TM = nullptr;
840 
841 public:
842  static char ID; // Pass identification, replacement for typeid..
843 
844  SafeStackLegacyPass() : FunctionPass(ID) {
846  }
847 
848  void getAnalysisUsage(AnalysisUsage &AU) const override {
852  }
853 
854  bool runOnFunction(Function &F) override {
855  LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
856 
857  if (!F.hasFnAttribute(Attribute::SafeStack)) {
858  LLVM_DEBUG(dbgs() << "[SafeStack] safestack is not requested"
859  " for this function\n");
860  return false;
861  }
862 
863  if (F.isDeclaration()) {
864  LLVM_DEBUG(dbgs() << "[SafeStack] function definition"
865  " is not available\n");
866  return false;
867  }
868 
869  TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
870  auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
871  if (!TL)
872  report_fatal_error("TargetLowering instance is required");
873 
874  auto *DL = &F.getParent()->getDataLayout();
875  auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
876  auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
877 
878  // Compute DT and LI only for functions that have the attribute.
879  // This is only useful because the legacy pass manager doesn't let us
880  // compute analyzes lazily.
881  // In the backend pipeline, nothing preserves DT before SafeStack, so we
882  // would otherwise always compute it wastefully, even if there is no
883  // function with the safestack attribute.
884  DominatorTree DT(F);
885  LoopInfo LI(DT);
886 
887  ScalarEvolution SE(F, TLI, ACT, DT, LI);
888 
889  return SafeStack(F, *TL, *DL, SE).run();
890  }
891 };
892 
893 } // end anonymous namespace
894 
895 char SafeStackLegacyPass::ID = 0;
896 
897 INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE,
898  "Safe Stack instrumentation pass", false, false)
900 INITIALIZE_PASS_END(SafeStackLegacyPass, DEBUG_TYPE,
901  "Safe Stack instrumentation pass", false, false)
902 
903 FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }
IterTy arg_end() const
Definition: CallSite.h:588
uint64_t CallInst * C
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Safe Stack instrumentation pass
Definition: SafeStack.cpp:900
iterator_range< use_iterator > uses()
Definition: Value.h:375
#define DEBUG_TYPE
Definition: SafeStack.cpp:76
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:21
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void addObject(const Value *V, unsigned Size, unsigned Alignment, const StackColoring::LiveRange &Range)
Add an object to the stack frame.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1656
void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, int Offset=0)
Replaces multiple llvm.dbg.value instructions when the alloca it describes is replaced with a new val...
Definition: Local.cpp:1599
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2250
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
IterTy arg_begin() const
Definition: CallSite.h:584
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool hasOptNone() const
Do not optimize this function (-O0).
Definition: Function.h:627
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:1669
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
unsigned getFrameSize()
Returns the size of the entire frame.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:170
Compute live ranges of allocas.
The main scalar evolution driver.
An immutable pass that tracks lazily created AssumptionCache objects.
virtual const TargetLowering * getTargetLowering() const
bool isInterposable() const
Return true if this global&#39;s definition can be substituted with an arbitrary definition at link time...
Definition: GlobalValue.h:429
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:872
F(f)
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it&#39;s an indirect...
Definition: CallSite.h:111
This defines the Use class.
This class captures the data input to the InlineFunction call, and records the auxiliary results prod...
Definition: Cloning.h:173
Value * getLength() const
INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE, "Safe Stack instrumentation pass", false, false) INITIALIZE_PASS_END(SafeStackLegacyPass
bool doesNotCapture(unsigned OpNo) const
Determine whether this data operand is not captured.
Definition: CallSite.h:602
static cl::opt< bool > SafeStackUsePointerAddress("safestack-use-pointer-address", cl::init(false), cl::Hidden)
Use __safestack_pointer_address even if the platform has a faster way of access safe stack pointer...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
inst_iterator inst_begin(Function *F)
Definition: InstIterator.h:131
unsigned getObjectOffset(const Value *V)
Returns the offset to the object start in the stack frame.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:112
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:96
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
FunctionPass * createSafeStackPass()
This pass splits the stack into a safe stack and an unsafe stack to protect against stack-based overf...
Definition: SafeStack.cpp:903
This file contains the simple types necessary to represent the attributes associated with functions a...
bool doesNotAccessMemory() const
Determine if the call does not access memory.
Definition: CallSite.h:459
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
Target-Independent Code Generator Pass Configuration Options.
This file implements a class to represent arbitrary precision integral constant values and operations...
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:428
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1698
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2096
Subprogram description.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Definition: Use.cpp:40
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2101
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Definition: IRBuilder.h:535
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1228
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:156
bool replaceDbgDeclare(Value *Address, Value *NewAddress, Instruction *InsertBefore, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces llvm.dbg.declare instruction when the address it describes is replaced with a new value...
Definition: Local.cpp:1549
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:430
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:292
iterator begin()
Definition: Function.h:691
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:132
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:769
static bool runOnFunction(Function &F, bool PostInlining)
xray instrumentation
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void set(Value *Val)
Definition: Value.h:730
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:465
bool hasName() const
Definition: Value.h:252
bool isNoInline() const
Return true if the call should not be inlined.
Definition: CallSite.h:451
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1525
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
Compute the layout of an unsafe stack frame.
Represent the analysis usage information of a pass.
InlineResult isInlineViable(Function &Callee)
Minimal filter to detect invalid constructs for inlining.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:282
ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:223
InlineResult InlineFunction(CallBase *CB, InlineFunctionInfo &IFI, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true)
This function inlines the called function into the basic block of the caller.
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:92
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:224
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1245
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:40
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:105
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1808
This is the common base class for memset/memcpy/memmove.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
Type * getType() const
Return the LLVM type of this SCEV expression.
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:390
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
Definition: Alignment.h:117
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2170
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Module.h This file contains the declarations for the Module class.
This class represents a range of values.
Definition: ConstantRange.h:47
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:704
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
User::const_op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
Definition: CallSite.h:220
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target&#39;s TargetSubtargetInf...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
unsigned getObjectAlignment(const Value *V)
Returns the alignment of the object.
Class for arbitrary precision integers.
Definition: APInt.h:69
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if this function has the given attribute.
Definition: CallSite.h:370
amdgpu Simplify well known AMD library false FunctionCallee Callee
void initializeSafeStackLegacyPassPass(PassRegistry &)
void computeLayout()
Run the layout computation for all previously added objects.
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2147
unsigned getFrameAlignment()
Returns the alignment of the frame.
Virtual Register Rewriter
Definition: VirtRegMap.cpp:220
use_iterator use_begin()
Definition: Value.h:359
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:163
Constant * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
Definition: Module.cpp:204
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:180
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
Establish a view to a call site for examination.
Definition: CallSite.h:697
#define I(x, y, z)
Definition: MD5.cpp:58
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
uint32_t Size
Definition: Profile.cpp:46
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2419
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1361
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2091
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:231
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces llvm.dbg.declare instruction when the alloca it describes is replaced with a new value...
Definition: Local.cpp:1569
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
Definition: Function.h:698
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:74
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
IRTranslator LLVM IR MI
inst_iterator inst_end(Function *F)
Definition: InstIterator.h:132
inst_range instructions(Function *F)
Definition: InstIterator.h:133
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
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.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:178
Value * getRawDest() const
bool use_empty() const
Definition: Value.h:343
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
This visitor recursively visits a SCEV expression and re-writes it.
static BranchProbability getBranchProbStackProtector(bool IsLikely)
iterator_range< arg_iterator > args()
Definition: Function.h:730
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:153
IntegerType * Int32Ty
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
This file describes how to lower LLVM code to machine code.
an instruction to allocate memory on the stack
Definition: Instructions.h:59