blob: 6729dd20598ff06eef2963d0b835cde51d710c93 [file] [log] [blame]
Nuno Lopes5c525b52012-05-22 17:19:09 +00001//===- 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//
10// This file implements a pass that instruments the code to perform run-time
11// bounds checking on loads, stores, and other memory intrinsics.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "bounds-checking"
16#include "llvm/Transforms/Scalar.h"
17#include "llvm/ADT/Statistic.h"
Nuno Lopes7f584722012-06-21 15:59:53 +000018#include "llvm/Analysis/MemoryBuiltins.h"
Nuno Lopes1cbf2be2012-05-31 22:58:48 +000019#include "llvm/Support/CommandLine.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000020#include "llvm/Support/Debug.h"
21#include "llvm/Support/InstIterator.h"
22#include "llvm/Support/IRBuilder.h"
Nuno Lopes2f0a7482012-05-22 22:02:19 +000023#include "llvm/Support/raw_ostream.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000024#include "llvm/Support/TargetFolder.h"
25#include "llvm/Target/TargetData.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000026#include "llvm/Intrinsics.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000027#include "llvm/Pass.h"
28using namespace llvm;
29
Nuno Lopes7f584722012-06-21 15:59:53 +000030static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
31 cl::desc("Use one trap block per function"));
Nuno Lopes1cbf2be2012-05-31 22:58:48 +000032
Nuno Lopes5c525b52012-05-22 17:19:09 +000033STATISTIC(ChecksAdded, "Bounds checks added");
34STATISTIC(ChecksSkipped, "Bounds checks skipped");
35STATISTIC(ChecksUnable, "Bounds checks unable to add");
36
37typedef IRBuilder<true, TargetFolder> BuilderTy;
38
39namespace {
Nuno Lopes5c525b52012-05-22 17:19:09 +000040 struct BoundsChecking : public FunctionPass {
Nuno Lopes5c525b52012-05-22 17:19:09 +000041 static char ID;
42
43 BoundsChecking(unsigned _Penalty = 5) : FunctionPass(ID), Penalty(_Penalty){
44 initializeBoundsCheckingPass(*PassRegistry::getPassRegistry());
45 }
46
Nuno Lopes5c525b52012-05-22 17:19:09 +000047 virtual bool runOnFunction(Function &F);
48
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50 AU.addRequired<TargetData>();
51 }
Nuno Lopes2f0a7482012-05-22 22:02:19 +000052
53 private:
54 const TargetData *TD;
Nuno Lopes7f584722012-06-21 15:59:53 +000055 ObjectSizeOffsetEvaluator *ObjSizeEval;
Nuno Lopes2f0a7482012-05-22 22:02:19 +000056 BuilderTy *Builder;
57 Function *Fn;
58 BasicBlock *TrapBB;
59 unsigned Penalty;
60
61 BasicBlock *getTrapBB();
Nuno Lopes2b526302012-05-23 16:24:52 +000062 void emitBranchToTrap(Value *Cmp = 0);
Nuno Lopes0463cce2012-05-31 22:45:40 +000063 bool computeAllocSize(Value *Ptr, APInt &Offset, Value* &OffsetValue,
64 APInt &Size, Value* &SizeValue);
Nuno Lopes2f0a7482012-05-22 22:02:19 +000065 bool instrument(Value *Ptr, Value *Val);
Nuno Lopes5c525b52012-05-22 17:19:09 +000066 };
67}
68
69char BoundsChecking::ID = 0;
Nuno Lopes988a0892012-05-29 22:32:51 +000070INITIALIZE_PASS_BEGIN(BoundsChecking, "bounds-checking",
71 "Run-time bounds checking", false, false)
72INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
73INITIALIZE_PASS_END(BoundsChecking, "bounds-checking",
74 "Run-time bounds checking", false, false)
Nuno Lopes5c525b52012-05-22 17:19:09 +000075
76
77/// getTrapBB - create a basic block that traps. All overflowing conditions
78/// branch to this block. There's only one trap block per function.
79BasicBlock *BoundsChecking::getTrapBB() {
Nuno Lopes7f584722012-06-21 15:59:53 +000080 if (TrapBB && SingleTrapBB)
Nuno Lopes5c525b52012-05-22 17:19:09 +000081 return TrapBB;
82
83 BasicBlock::iterator PrevInsertPoint = Builder->GetInsertPoint();
84 TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
85 Builder->SetInsertPoint(TrapBB);
86
87 llvm::Value *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
88 CallInst *TrapCall = Builder->CreateCall(F);
89 TrapCall->setDoesNotReturn();
90 TrapCall->setDoesNotThrow();
91 Builder->CreateUnreachable();
92
93 Builder->SetInsertPoint(PrevInsertPoint);
94 return TrapBB;
95}
96
97
Nuno Lopes2b526302012-05-23 16:24:52 +000098/// emitBranchToTrap - emit a branch instruction to a trap block.
99/// If Cmp is non-null, perform a jump only if its value evaluates to true.
100void BoundsChecking::emitBranchToTrap(Value *Cmp) {
Nuno Lopes7f584722012-06-21 15:59:53 +0000101 // check if the comparison is always false
102 ConstantInt *C = dyn_cast_or_null<ConstantInt>(Cmp);
103 if (C) {
104 ++ChecksSkipped;
105 if (!C->getZExtValue())
106 return;
107 else
108 Cmp = 0; // unconditional branch
109 }
110
Nuno Lopes2b526302012-05-23 16:24:52 +0000111 Instruction *Inst = Builder->GetInsertPoint();
112 BasicBlock *OldBB = Inst->getParent();
113 BasicBlock *Cont = OldBB->splitBasicBlock(Inst);
114 OldBB->getTerminator()->eraseFromParent();
115
Nuno Lopes2b526302012-05-23 16:24:52 +0000116 if (Cmp)
117 BranchInst::Create(getTrapBB(), Cont, Cmp, OldBB);
118 else
119 BranchInst::Create(getTrapBB(), OldBB);
120}
121
122
Nuno Lopes2f0a7482012-05-22 22:02:19 +0000123/// instrument - adds run-time bounds checks to memory accessing instructions.
124/// Ptr is the pointer that will be read/written, and InstVal is either the
125/// result from the load or the value being stored. It is used to determine the
126/// size of memory block that is touched.
127/// Returns true if any change was made to the IR, false otherwise.
Nuno Lopes5c525b52012-05-22 17:19:09 +0000128bool BoundsChecking::instrument(Value *Ptr, Value *InstVal) {
129 uint64_t NeededSize = TD->getTypeStoreSize(InstVal->getType());
130 DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
131 << " bytes\n");
132
Nuno Lopes7f584722012-06-21 15:59:53 +0000133 SizeOffsetEvalType SizeOffset = ObjSizeEval->compute(Ptr);
Nuno Lopes5c525b52012-05-22 17:19:09 +0000134
Nuno Lopes7f584722012-06-21 15:59:53 +0000135 if (!ObjSizeEval->bothKnown(SizeOffset)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000136 ++ChecksUnable;
137 return false;
138 }
Nuno Lopes5c525b52012-05-22 17:19:09 +0000139
Nuno Lopes7f584722012-06-21 15:59:53 +0000140 Value *Size = SizeOffset.first;
141 Value *Offset = SizeOffset.second;
142
143 IntegerType *IntTy = TD->getIntPtrType(Fn->getContext());
144 Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
145
Nuno Lopes0463cce2012-05-31 22:45:40 +0000146 // 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)
Nuno Lopes0463cce2012-05-31 22:45:40 +0000150 // FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
Nuno Lopes7f584722012-06-21 15:59:53 +0000151 Value *ObjSize = Builder->CreateSub(Size, Offset);
152 Value *Cmp1 = Builder->CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
153 Value *Cmp2 = Builder->CreateICmpULT(Size, Offset);
154 Value *Cmp3 = Builder->CreateICmpULT(ObjSize, NeededSizeVal);
155 Value *Or = Builder->CreateOr(Cmp1, Builder->CreateOr(Cmp2, Cmp3));
Nuno Lopes2b526302012-05-23 16:24:52 +0000156 emitBranchToTrap(Or);
Nuno Lopes5c525b52012-05-22 17:19:09 +0000157
Nuno Lopes5c525b52012-05-22 17:19:09 +0000158 ++ChecksAdded;
159 return true;
160}
161
162bool BoundsChecking::runOnFunction(Function &F) {
163 TD = &getAnalysis<TargetData>();
164
165 TrapBB = 0;
166 Fn = &F;
167 BuilderTy TheBuilder(F.getContext(), TargetFolder(TD));
168 Builder = &TheBuilder;
Nuno Lopes7f584722012-06-21 15:59:53 +0000169 ObjectSizeOffsetEvaluator TheObjSizeEval(TD, F.getContext());
170 ObjSizeEval = &TheObjSizeEval;
Nuno Lopes5c525b52012-05-22 17:19:09 +0000171
172 // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
173 // touching instructions
174 std::vector<Instruction*> WorkList;
175 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) {
176 Instruction *I = &*i;
177 if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<AtomicCmpXchgInst>(I) ||
178 isa<AtomicRMWInst>(I))
179 WorkList.push_back(I);
180 }
181
182 bool MadeChange = false;
Nuno Lopes2f0a7482012-05-22 22:02:19 +0000183 for (std::vector<Instruction*>::iterator i = WorkList.begin(),
184 e = WorkList.end(); i != e; ++i) {
185 Instruction *I = *i;
Nuno Lopes5c525b52012-05-22 17:19:09 +0000186
187 Builder->SetInsertPoint(I);
188 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
189 MadeChange |= instrument(LI->getPointerOperand(), LI);
190 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
191 MadeChange |= instrument(SI->getPointerOperand(), SI->getValueOperand());
192 } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(I)) {
193 MadeChange |= instrument(AI->getPointerOperand(),AI->getCompareOperand());
194 } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(I)) {
195 MadeChange |= instrument(AI->getPointerOperand(), AI->getValOperand());
196 } else {
197 llvm_unreachable("unknown Instruction type");
198 }
199 }
200 return MadeChange;
201}
202
203FunctionPass *llvm::createBoundsCheckingPass(unsigned Penalty) {
204 return new BoundsChecking(Penalty);
205}