LLVM  8.0.0svn
BoundsChecking.cpp
Go to the documentation of this file.
1 //===- BoundsChecking.cpp - Instrumentation for run-time bounds checking --===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/Twine.h"
17 #include "llvm/IR/BasicBlock.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/InstIterator.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/Value.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Debug.h"
34 #include <cstdint>
35 #include <vector>
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "bounds-checking"
40 
41 static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
42  cl::desc("Use one trap block per function"));
43 
44 STATISTIC(ChecksAdded, "Bounds checks added");
45 STATISTIC(ChecksSkipped, "Bounds checks skipped");
46 STATISTIC(ChecksUnable, "Bounds checks unable to add");
47 
49 
50 /// Gets the conditions under which memory accessing instructions will overflow.
51 ///
52 /// \p Ptr is the pointer that will be read/written, and \p InstVal is either
53 /// the result from the load or the value being stored. It is used to determine
54 /// the size of memory block that is touched.
55 ///
56 /// Returns the condition under which the access will overflow.
57 static Value *getBoundsCheckCond(Value *Ptr, Value *InstVal,
58  const DataLayout &DL, TargetLibraryInfo &TLI,
59  ObjectSizeOffsetEvaluator &ObjSizeEval,
60  BuilderTy &IRB, ScalarEvolution &SE) {
61  uint64_t NeededSize = DL.getTypeStoreSize(InstVal->getType());
62  LLVM_DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
63  << " bytes\n");
64 
65  SizeOffsetEvalType SizeOffset = ObjSizeEval.compute(Ptr);
66 
67  if (!ObjSizeEval.bothKnown(SizeOffset)) {
68  ++ChecksUnable;
69  return nullptr;
70  }
71 
72  Value *Size = SizeOffset.first;
73  Value *Offset = SizeOffset.second;
75 
76  Type *IntTy = DL.getIntPtrType(Ptr->getType());
77  Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
78 
79  auto SizeRange = SE.getUnsignedRange(SE.getSCEV(Size));
80  auto OffsetRange = SE.getUnsignedRange(SE.getSCEV(Offset));
81  auto NeededSizeRange = SE.getUnsignedRange(SE.getSCEV(NeededSizeVal));
82 
83  // three checks are required to ensure safety:
84  // . Offset >= 0 (since the offset is given from the base ptr)
85  // . Size >= Offset (unsigned)
86  // . Size - Offset >= NeededSize (unsigned)
87  //
88  // optimization: if Size >= 0 (signed), skip 1st check
89  // FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
90  Value *ObjSize = IRB.CreateSub(Size, Offset);
91  Value *Cmp2 = SizeRange.getUnsignedMin().uge(OffsetRange.getUnsignedMax())
93  : IRB.CreateICmpULT(Size, Offset);
94  Value *Cmp3 = SizeRange.sub(OffsetRange)
95  .getUnsignedMin()
96  .uge(NeededSizeRange.getUnsignedMax())
98  : IRB.CreateICmpULT(ObjSize, NeededSizeVal);
99  Value *Or = IRB.CreateOr(Cmp2, Cmp3);
100  if ((!SizeCI || SizeCI->getValue().slt(0)) &&
101  !SizeRange.getSignedMin().isNonNegative()) {
102  Value *Cmp1 = IRB.CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
103  Or = IRB.CreateOr(Cmp1, Or);
104  }
105 
106  return Or;
107 }
108 
109 /// Adds run-time bounds checks to memory accessing instructions.
110 ///
111 /// \p Or is the condition that should guard the trap.
112 ///
113 /// \p GetTrapBB is a callable that returns the trap BB to use on failure.
114 template <typename GetTrapBBT>
115 static void insertBoundsCheck(Value *Or, BuilderTy IRB, GetTrapBBT GetTrapBB) {
116  // check if the comparison is always false
117  ConstantInt *C = dyn_cast_or_null<ConstantInt>(Or);
118  if (C) {
119  ++ChecksSkipped;
120  // If non-zero, nothing to do.
121  if (!C->getZExtValue())
122  return;
123  }
124  ++ChecksAdded;
125 
126  BasicBlock::iterator SplitI = IRB.GetInsertPoint();
127  BasicBlock *OldBB = SplitI->getParent();
128  BasicBlock *Cont = OldBB->splitBasicBlock(SplitI);
129  OldBB->getTerminator()->eraseFromParent();
130 
131  if (C) {
132  // If we have a constant zero, unconditionally branch.
133  // FIXME: We should really handle this differently to bypass the splitting
134  // the block.
135  BranchInst::Create(GetTrapBB(IRB), OldBB);
136  return;
137  }
138 
139  // Create the conditional branch.
140  BranchInst::Create(GetTrapBB(IRB), Cont, Or, OldBB);
141 }
142 
144  ScalarEvolution &SE) {
145  const DataLayout &DL = F.getParent()->getDataLayout();
146  ObjectSizeOffsetEvaluator ObjSizeEval(DL, &TLI, F.getContext(),
147  /*RoundToAlign=*/true);
148 
149  // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
150  // touching instructions
152  for (Instruction &I : instructions(F)) {
153  Value *Or = nullptr;
154  BuilderTy IRB(I.getParent(), BasicBlock::iterator(&I), TargetFolder(DL));
155  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
156  Or = getBoundsCheckCond(LI->getPointerOperand(), LI, DL, TLI,
157  ObjSizeEval, IRB, SE);
158  } else if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
159  Or = getBoundsCheckCond(SI->getPointerOperand(), SI->getValueOperand(),
160  DL, TLI, ObjSizeEval, IRB, SE);
161  } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
162  Or = getBoundsCheckCond(AI->getPointerOperand(), AI->getCompareOperand(),
163  DL, TLI, ObjSizeEval, IRB, SE);
164  } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
165  Or = getBoundsCheckCond(AI->getPointerOperand(), AI->getValOperand(), DL,
166  TLI, ObjSizeEval, IRB, SE);
167  }
168  if (Or)
169  TrapInfo.push_back(std::make_pair(&I, Or));
170  }
171 
172  // Create a trapping basic block on demand using a callback. Depending on
173  // flags, this will either create a single block for the entire function or
174  // will create a fresh block every time it is called.
175  BasicBlock *TrapBB = nullptr;
176  auto GetTrapBB = [&TrapBB](BuilderTy &IRB) {
177  if (TrapBB && SingleTrapBB)
178  return TrapBB;
179 
180  Function *Fn = IRB.GetInsertBlock()->getParent();
181  // FIXME: This debug location doesn't make a lot of sense in the
182  // `SingleTrapBB` case.
183  auto DebugLoc = IRB.getCurrentDebugLocation();
185  TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
186  IRB.SetInsertPoint(TrapBB);
187 
188  auto *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
189  CallInst *TrapCall = IRB.CreateCall(F, {});
190  TrapCall->setDoesNotReturn();
191  TrapCall->setDoesNotThrow();
192  TrapCall->setDebugLoc(DebugLoc);
193  IRB.CreateUnreachable();
194 
195  return TrapBB;
196  };
197 
198  // Add the checks.
199  for (const auto &Entry : TrapInfo) {
200  Instruction *Inst = Entry.first;
201  BuilderTy IRB(Inst->getParent(), BasicBlock::iterator(Inst), TargetFolder(DL));
202  insertBoundsCheck(Entry.second, IRB, GetTrapBB);
203  }
204 
205  return !TrapInfo.empty();
206 }
207 
209  auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
210  auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
211 
212  if (!addBoundsChecking(F, TLI, SE))
213  return PreservedAnalyses::all();
214 
215  return PreservedAnalyses::none();
216 }
217 
218 namespace {
219 struct BoundsCheckingLegacyPass : public FunctionPass {
220  static char ID;
221 
222  BoundsCheckingLegacyPass() : FunctionPass(ID) {
224  }
225 
226  bool runOnFunction(Function &F) override {
227  auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
228  auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
229  return addBoundsChecking(F, TLI, SE);
230  }
231 
232  void getAnalysisUsage(AnalysisUsage &AU) const override {
235  }
236 };
237 } // namespace
238 
240 INITIALIZE_PASS_BEGIN(BoundsCheckingLegacyPass, "bounds-checking",
241  "Run-time bounds checking", false, false)
243 INITIALIZE_PASS_END(BoundsCheckingLegacyPass, "bounds-checking",
244  "Run-time bounds checking", false, false)
245 
247  return new BoundsCheckingLegacyPass();
248 }
uint64_t CallInst * C
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:68
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:585
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
INITIALIZE_PASS_BEGIN(BoundsCheckingLegacyPass, "bounds-checking", "Run-time bounds checking", false, false) INITIALIZE_PASS_END(BoundsCheckingLegacyPass
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:770
This class represents lattice values for constants.
Definition: AllocatorList.h:24
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1764
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:518
std::pair< Value *, Value * > SizeOffsetEvalType
The main scalar evolution driver.
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1780
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1204
This class represents a function call, abstracting a target machine&#39;s calling convention.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
STATISTIC(NumFunctions, "Total number of functions")
A debug info location.
Definition: DebugLoc.h:34
F(f)
An instruction for reading from memory.
Definition: Instructions.h:168
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:681
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:138
FunctionPass * createBoundsCheckingLegacyPass()
Legacy pass creation function for the above pass.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:365
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static cl::opt< bool > SingleTrapBB("bounds-checking-single-trap", cl::desc("Use one trap block per function"))
static void insertBoundsCheck(Value *Or, BuilderTy IRB, GetTrapBBT GetTrapBB)
Adds run-time bounds checks to memory accessing instructions.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
Evaluate the size and offset of an object pointed to by a Value*.
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:138
TargetFolder - Create constants with target dependent folding.
Definition: TargetFolder.h:32
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:991
An instruction for storing to memory.
Definition: Instructions.h:310
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:1021
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:157
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1142
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:742
static bool runOnFunction(Function &F, bool PostInlining)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:149
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool addBoundsChecking(Function &F, TargetLibraryInfo &TLI, ScalarEvolution &SE)
Represent the analysis usage information of a pass.
static Value * getBoundsCheckCond(Value *Ptr, Value *InstVal, const DataLayout &DL, TargetLibraryInfo &TLI, ObjectSizeOffsetEvaluator &ObjSizeEval, BuilderTy &IRB, ScalarEvolution &SE)
Gets the conditions under which memory accessing instructions will overflow.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
bounds checking
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:100
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:194
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Provides information about what library functions are available for the current target.
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:622
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:90
Analysis pass that exposes the ScalarEvolution for a function.
SizeOffsetEvalType compute(Value *V)
#define I(x, y, z)
Definition: MD5.cpp:58
void initializeBoundsCheckingLegacyPassPass(PassRegistry &)
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:323
uint32_t Size
Definition: Profile.cpp:47
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:410
void setDoesNotReturn()
Definition: InstrTypes.h:1402
Analysis pass providing the TargetLibraryInfo.
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
LLVM Value Representation.
Definition: Value.h:73
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:411
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:122
inst_range instructions(Function *F)
Definition: InstIterator.h:134
A container for analyses that lazily runs them and caches their results.
#define LLVM_DEBUG(X)
Definition: Debug.h:123
bool bothKnown(SizeOffsetEvalType SizeOffset)
const BasicBlock * getParent() const
Definition: Instruction.h:67