1 //===- BoundsChecking.cpp - Instrumentation for run-time bounds checking --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a pass that instruments the code to perform run-time
11 // bounds checking on loads, stores, and other memory intrinsics.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "bounds-checking"
16 #include "llvm/Transforms/Instrumentation.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/Analysis/TargetFolder.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/InstIterator.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetLibraryInfo.h"
31 static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
32 cl::desc("Use one trap block per function"));
34 STATISTIC(ChecksAdded, "Bounds checks added");
35 STATISTIC(ChecksSkipped, "Bounds checks skipped");
36 STATISTIC(ChecksUnable, "Bounds checks unable to add");
38 typedef IRBuilder<true, TargetFolder> BuilderTy;
41 struct BoundsChecking : public FunctionPass {
44 BoundsChecking() : FunctionPass(ID) {
45 initializeBoundsCheckingPass(*PassRegistry::getPassRegistry());
48 bool runOnFunction(Function &F) override;
50 void getAnalysisUsage(AnalysisUsage &AU) const override {
51 AU.addRequired<DataLayoutPass>();
52 AU.addRequired<TargetLibraryInfo>();
57 const TargetLibraryInfo *TLI;
58 ObjectSizeOffsetEvaluator *ObjSizeEval;
63 BasicBlock *getTrapBB();
64 void emitBranchToTrap(Value *Cmp = 0);
65 bool instrument(Value *Ptr, Value *Val);
69 char BoundsChecking::ID = 0;
70 INITIALIZE_PASS(BoundsChecking, "bounds-checking", "Run-time bounds checking",
74 /// getTrapBB - create a basic block that traps. All overflowing conditions
75 /// branch to this block. There's only one trap block per function.
76 BasicBlock *BoundsChecking::getTrapBB() {
77 if (TrapBB && SingleTrapBB)
80 Function *Fn = Inst->getParent()->getParent();
81 IRBuilder<>::InsertPointGuard Guard(*Builder);
82 TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
83 Builder->SetInsertPoint(TrapBB);
85 llvm::Value *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
86 CallInst *TrapCall = Builder->CreateCall(F);
87 TrapCall->setDoesNotReturn();
88 TrapCall->setDoesNotThrow();
89 TrapCall->setDebugLoc(Inst->getDebugLoc());
90 Builder->CreateUnreachable();
96 /// emitBranchToTrap - emit a branch instruction to a trap block.
97 /// If Cmp is non-null, perform a jump only if its value evaluates to true.
98 void BoundsChecking::emitBranchToTrap(Value *Cmp) {
99 // check if the comparison is always false
100 ConstantInt *C = dyn_cast_or_null<ConstantInt>(Cmp);
103 if (!C->getZExtValue())
106 Cmp = 0; // unconditional branch
110 Instruction *Inst = Builder->GetInsertPoint();
111 BasicBlock *OldBB = Inst->getParent();
112 BasicBlock *Cont = OldBB->splitBasicBlock(Inst);
113 OldBB->getTerminator()->eraseFromParent();
116 BranchInst::Create(getTrapBB(), Cont, Cmp, OldBB);
118 BranchInst::Create(getTrapBB(), OldBB);
122 /// instrument - adds run-time bounds checks to memory accessing instructions.
123 /// Ptr is the pointer that will be read/written, and InstVal is either the
124 /// result from the load or the value being stored. It is used to determine the
125 /// size of memory block that is touched.
126 /// Returns true if any change was made to the IR, false otherwise.
127 bool BoundsChecking::instrument(Value *Ptr, Value *InstVal) {
128 uint64_t NeededSize = DL->getTypeStoreSize(InstVal->getType());
129 DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
132 SizeOffsetEvalType SizeOffset = ObjSizeEval->compute(Ptr);
134 if (!ObjSizeEval->bothKnown(SizeOffset)) {
139 Value *Size = SizeOffset.first;
140 Value *Offset = SizeOffset.second;
141 ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
143 Type *IntTy = DL->getIntPtrType(Ptr->getType());
144 Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
146 // three checks are required to ensure safety:
147 // . Offset >= 0 (since the offset is given from the base ptr)
148 // . Size >= Offset (unsigned)
149 // . Size - Offset >= NeededSize (unsigned)
151 // optimization: if Size >= 0 (signed), skip 1st check
152 // FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
153 Value *ObjSize = Builder->CreateSub(Size, Offset);
154 Value *Cmp2 = Builder->CreateICmpULT(Size, Offset);
155 Value *Cmp3 = Builder->CreateICmpULT(ObjSize, NeededSizeVal);
156 Value *Or = Builder->CreateOr(Cmp2, Cmp3);
157 if (!SizeCI || SizeCI->getValue().slt(0)) {
158 Value *Cmp1 = Builder->CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
159 Or = Builder->CreateOr(Cmp1, Or);
161 emitBranchToTrap(Or);
166 bool BoundsChecking::runOnFunction(Function &F) {
167 DL = &getAnalysis<DataLayoutPass>().getDataLayout();
168 TLI = &getAnalysis<TargetLibraryInfo>();
171 BuilderTy TheBuilder(F.getContext(), TargetFolder(DL));
172 Builder = &TheBuilder;
173 ObjectSizeOffsetEvaluator TheObjSizeEval(DL, TLI, F.getContext(),
174 /*RoundToAlign=*/true);
175 ObjSizeEval = &TheObjSizeEval;
177 // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
178 // touching instructions
179 std::vector<Instruction*> WorkList;
180 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) {
181 Instruction *I = &*i;
182 if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<AtomicCmpXchgInst>(I) ||
183 isa<AtomicRMWInst>(I))
184 WorkList.push_back(I);
187 bool MadeChange = false;
188 for (std::vector<Instruction*>::iterator i = WorkList.begin(),
189 e = WorkList.end(); i != e; ++i) {
192 Builder->SetInsertPoint(Inst);
193 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
194 MadeChange |= instrument(LI->getPointerOperand(), LI);
195 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
196 MadeChange |= instrument(SI->getPointerOperand(), SI->getValueOperand());
197 } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst)) {
198 MadeChange |= instrument(AI->getPointerOperand(),AI->getCompareOperand());
199 } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst)) {
200 MadeChange |= instrument(AI->getPointerOperand(), AI->getValOperand());
202 llvm_unreachable("unknown Instruction type");
208 FunctionPass *llvm::createBoundsCheckingPass() {
209 return new BoundsChecking();