blob: 09e0f1445126560375e36c65d8757ff3297db9ff [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"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000016#include "llvm/IRBuilder.h"
17#include "llvm/Intrinsics.h"
18#include "llvm/Pass.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000019#include "llvm/ADT/Statistic.h"
Nuno Lopes7f584722012-06-21 15:59:53 +000020#include "llvm/Analysis/MemoryBuiltins.h"
Nuno Lopes1cbf2be2012-05-31 22:58:48 +000021#include "llvm/Support/CommandLine.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000022#include "llvm/Support/Debug.h"
23#include "llvm/Support/InstIterator.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000024#include "llvm/Support/TargetFolder.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000025#include "llvm/Support/raw_ostream.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000026#include "llvm/Target/TargetData.h"
Nuno Lopes78435f62012-07-20 22:39:33 +000027#include "llvm/Transforms/Instrumentation.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000028using 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;
Nuno Lopes512be1f2012-06-23 00:12:34 +000057 Instruction *Inst;
Nuno Lopes2f0a7482012-05-22 22:02:19 +000058 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 Lopes42d80c72012-07-03 17:30:18 +000070INITIALIZE_PASS(BoundsChecking, "bounds-checking", "Run-time bounds checking",
71 false, false)
Nuno Lopes5c525b52012-05-22 17:19:09 +000072
73
74/// getTrapBB - create a basic block that traps. All overflowing conditions
75/// branch to this block. There's only one trap block per function.
76BasicBlock *BoundsChecking::getTrapBB() {
Nuno Lopes7f584722012-06-21 15:59:53 +000077 if (TrapBB && SingleTrapBB)
Nuno Lopes5c525b52012-05-22 17:19:09 +000078 return TrapBB;
79
Nuno Lopes512be1f2012-06-23 00:12:34 +000080 Function *Fn = Inst->getParent()->getParent();
Nuno Lopes5c525b52012-05-22 17:19:09 +000081 BasicBlock::iterator PrevInsertPoint = Builder->GetInsertPoint();
82 TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
83 Builder->SetInsertPoint(TrapBB);
84
85 llvm::Value *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
86 CallInst *TrapCall = Builder->CreateCall(F);
87 TrapCall->setDoesNotReturn();
88 TrapCall->setDoesNotThrow();
Nuno Lopes512be1f2012-06-23 00:12:34 +000089 TrapCall->setDebugLoc(Inst->getDebugLoc());
Nuno Lopes5c525b52012-05-22 17:19:09 +000090 Builder->CreateUnreachable();
91
92 Builder->SetInsertPoint(PrevInsertPoint);
93 return TrapBB;
94}
95
96
Nuno Lopes2b526302012-05-23 16:24:52 +000097/// emitBranchToTrap - emit a branch instruction to a trap block.
98/// If Cmp is non-null, perform a jump only if its value evaluates to true.
99void BoundsChecking::emitBranchToTrap(Value *Cmp) {
Nuno Lopes7f584722012-06-21 15:59:53 +0000100 // check if the comparison is always false
101 ConstantInt *C = dyn_cast_or_null<ConstantInt>(Cmp);
102 if (C) {
103 ++ChecksSkipped;
104 if (!C->getZExtValue())
105 return;
106 else
107 Cmp = 0; // unconditional branch
108 }
109
Nuno Lopes2b526302012-05-23 16:24:52 +0000110 Instruction *Inst = Builder->GetInsertPoint();
111 BasicBlock *OldBB = Inst->getParent();
112 BasicBlock *Cont = OldBB->splitBasicBlock(Inst);
113 OldBB->getTerminator()->eraseFromParent();
114
Nuno Lopes2b526302012-05-23 16:24:52 +0000115 if (Cmp)
116 BranchInst::Create(getTrapBB(), Cont, Cmp, OldBB);
117 else
118 BranchInst::Create(getTrapBB(), OldBB);
119}
120
121
Nuno Lopes2f0a7482012-05-22 22:02:19 +0000122/// 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.
Nuno Lopes5c525b52012-05-22 17:19:09 +0000127bool BoundsChecking::instrument(Value *Ptr, Value *InstVal) {
128 uint64_t NeededSize = TD->getTypeStoreSize(InstVal->getType());
129 DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
130 << " bytes\n");
131
Nuno Lopes7f584722012-06-21 15:59:53 +0000132 SizeOffsetEvalType SizeOffset = ObjSizeEval->compute(Ptr);
Nuno Lopes5c525b52012-05-22 17:19:09 +0000133
Nuno Lopes7f584722012-06-21 15:59:53 +0000134 if (!ObjSizeEval->bothKnown(SizeOffset)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000135 ++ChecksUnable;
136 return false;
137 }
Nuno Lopes5c525b52012-05-22 17:19:09 +0000138
Nuno Lopes7f584722012-06-21 15:59:53 +0000139 Value *Size = SizeOffset.first;
140 Value *Offset = SizeOffset.second;
Nuno Lopes42d80c72012-07-03 17:30:18 +0000141 ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
Nuno Lopes7f584722012-06-21 15:59:53 +0000142
Nuno Lopes512be1f2012-06-23 00:12:34 +0000143 IntegerType *IntTy = TD->getIntPtrType(Inst->getContext());
Nuno Lopes7f584722012-06-21 15:59:53 +0000144 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 Lopes42d80c72012-07-03 17:30:18 +0000150 //
151 // optimization: if Size >= 0 (signed), skip 1st check
Nuno Lopes0463cce2012-05-31 22:45:40 +0000152 // FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
Nuno Lopes7f584722012-06-21 15:59:53 +0000153 Value *ObjSize = Builder->CreateSub(Size, Offset);
Nuno Lopes7f584722012-06-21 15:59:53 +0000154 Value *Cmp2 = Builder->CreateICmpULT(Size, Offset);
155 Value *Cmp3 = Builder->CreateICmpULT(ObjSize, NeededSizeVal);
Nuno Lopes42d80c72012-07-03 17:30:18 +0000156 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);
160 }
Nuno Lopes2b526302012-05-23 16:24:52 +0000161 emitBranchToTrap(Or);
Nuno Lopes5c525b52012-05-22 17:19:09 +0000162
Nuno Lopes5c525b52012-05-22 17:19:09 +0000163 ++ChecksAdded;
164 return true;
165}
166
167bool BoundsChecking::runOnFunction(Function &F) {
168 TD = &getAnalysis<TargetData>();
169
170 TrapBB = 0;
Nuno Lopes5c525b52012-05-22 17:19:09 +0000171 BuilderTy TheBuilder(F.getContext(), TargetFolder(TD));
172 Builder = &TheBuilder;
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000173 ObjectSizeOffsetEvaluator TheObjSizeEval(TD, F.getContext());
Nuno Lopes7f584722012-06-21 15:59:53 +0000174 ObjSizeEval = &TheObjSizeEval;
Nuno Lopes5c525b52012-05-22 17:19:09 +0000175
176 // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
177 // touching instructions
178 std::vector<Instruction*> WorkList;
179 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) {
180 Instruction *I = &*i;
181 if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<AtomicCmpXchgInst>(I) ||
182 isa<AtomicRMWInst>(I))
183 WorkList.push_back(I);
184 }
185
186 bool MadeChange = false;
Nuno Lopes2f0a7482012-05-22 22:02:19 +0000187 for (std::vector<Instruction*>::iterator i = WorkList.begin(),
188 e = WorkList.end(); i != e; ++i) {
Nuno Lopes512be1f2012-06-23 00:12:34 +0000189 Inst = *i;
Nuno Lopes5c525b52012-05-22 17:19:09 +0000190
Nuno Lopes512be1f2012-06-23 00:12:34 +0000191 Builder->SetInsertPoint(Inst);
192 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000193 MadeChange |= instrument(LI->getPointerOperand(), LI);
Nuno Lopes512be1f2012-06-23 00:12:34 +0000194 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000195 MadeChange |= instrument(SI->getPointerOperand(), SI->getValueOperand());
Nuno Lopes512be1f2012-06-23 00:12:34 +0000196 } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000197 MadeChange |= instrument(AI->getPointerOperand(),AI->getCompareOperand());
Nuno Lopes512be1f2012-06-23 00:12:34 +0000198 } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000199 MadeChange |= instrument(AI->getPointerOperand(), AI->getValOperand());
200 } else {
201 llvm_unreachable("unknown Instruction type");
202 }
203 }
204 return MadeChange;
205}
206
207FunctionPass *llvm::createBoundsCheckingPass(unsigned Penalty) {
208 return new BoundsChecking(Penalty);
209}