blob: d4c8369fa9d3bf309bf923add5de693ab7548e8d [file] [log] [blame]
Nuno Lopesa2f6cec2012-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
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/Transforms/Instrumentation.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth452a0072014-03-04 11:59:06 +000018#include "llvm/Analysis/TargetFolder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000019#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/IRBuilder.h"
Chandler Carruth83948572014-03-04 10:30:26 +000022#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Intrinsics.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000024#include "llvm/Pass.h"
Nuno Lopes288e86ff62012-05-31 22:58:48 +000025#include "llvm/Support/CommandLine.h"
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000026#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000027#include "llvm/Support/raw_ostream.h"
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000028using namespace llvm;
29
Chandler Carruth964daaa2014-04-22 02:55:47 +000030#define DEBUG_TYPE "bounds-checking"
31
Nuno Lopes0e967e02012-06-21 15:59:53 +000032static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
33 cl::desc("Use one trap block per function"));
Nuno Lopes288e86ff62012-05-31 22:58:48 +000034
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000035STATISTIC(ChecksAdded, "Bounds checks added");
36STATISTIC(ChecksSkipped, "Bounds checks skipped");
37STATISTIC(ChecksUnable, "Bounds checks unable to add");
38
Mehdi Aminiba9fba82016-03-13 21:05:13 +000039typedef IRBuilder<TargetFolder> BuilderTy;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000040
41namespace {
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000042 struct BoundsChecking : public FunctionPass {
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000043 static char ID;
44
Joey Gouly95198232012-11-23 10:47:35 +000045 BoundsChecking() : FunctionPass(ID) {
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000046 initializeBoundsCheckingPass(*PassRegistry::getPassRegistry());
47 }
48
Craig Topper3e4c6972014-03-05 09:10:37 +000049 bool runOnFunction(Function &F) override;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000050
Craig Topper3e4c6972014-03-05 09:10:37 +000051 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +000052 AU.addRequired<TargetLibraryInfoWrapperPass>();
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000053 }
Nuno Lopes59e9df72012-05-22 22:02:19 +000054
55 private:
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000056 const TargetLibraryInfo *TLI;
Nuno Lopes0e967e02012-06-21 15:59:53 +000057 ObjectSizeOffsetEvaluator *ObjSizeEval;
Nuno Lopes59e9df72012-05-22 22:02:19 +000058 BuilderTy *Builder;
Nuno Lopesde8c6fb2012-06-23 00:12:34 +000059 Instruction *Inst;
Nuno Lopes59e9df72012-05-22 22:02:19 +000060 BasicBlock *TrapBB;
Nuno Lopes59e9df72012-05-22 22:02:19 +000061
62 BasicBlock *getTrapBB();
Craig Topperf40110f2014-04-25 05:29:35 +000063 void emitBranchToTrap(Value *Cmp = nullptr);
Mehdi Aminia28d91d2015-03-10 02:37:25 +000064 bool instrument(Value *Ptr, Value *Val, const DataLayout &DL);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000065 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000066}
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000067
68char BoundsChecking::ID = 0;
Nuno Lopes1e8dffd2012-07-03 17:30:18 +000069INITIALIZE_PASS(BoundsChecking, "bounds-checking", "Run-time bounds checking",
70 false, false)
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000071
72
73/// getTrapBB - create a basic block that traps. All overflowing conditions
74/// branch to this block. There's only one trap block per function.
75BasicBlock *BoundsChecking::getTrapBB() {
Nuno Lopes0e967e02012-06-21 15:59:53 +000076 if (TrapBB && SingleTrapBB)
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000077 return TrapBB;
78
Nuno Lopesde8c6fb2012-06-23 00:12:34 +000079 Function *Fn = Inst->getParent()->getParent();
Benjamin Kramer6e931522013-09-30 15:40:17 +000080 IRBuilder<>::InsertPointGuard Guard(*Builder);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000081 TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
Benjamin Kramerf0047292013-09-30 15:52:50 +000082 Builder->SetInsertPoint(TrapBB);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000083
84 llvm::Value *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
David Blaikieff6409d2015-05-18 22:13:54 +000085 CallInst *TrapCall = Builder->CreateCall(F, {});
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000086 TrapCall->setDoesNotReturn();
87 TrapCall->setDoesNotThrow();
Nuno Lopesde8c6fb2012-06-23 00:12:34 +000088 TrapCall->setDebugLoc(Inst->getDebugLoc());
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000089 Builder->CreateUnreachable();
90
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000091 return TrapBB;
92}
93
94
Nuno Lopes10287d82012-05-23 16:24:52 +000095/// emitBranchToTrap - emit a branch instruction to a trap block.
96/// If Cmp is non-null, perform a jump only if its value evaluates to true.
97void BoundsChecking::emitBranchToTrap(Value *Cmp) {
Nuno Lopes0e967e02012-06-21 15:59:53 +000098 // check if the comparison is always false
99 ConstantInt *C = dyn_cast_or_null<ConstantInt>(Cmp);
100 if (C) {
101 ++ChecksSkipped;
102 if (!C->getZExtValue())
103 return;
104 else
Craig Topperf40110f2014-04-25 05:29:35 +0000105 Cmp = nullptr; // unconditional branch
Nuno Lopes0e967e02012-06-21 15:59:53 +0000106 }
Nuno Lopes5eec2672012-12-03 10:15:03 +0000107 ++ChecksAdded;
Nuno Lopes0e967e02012-06-21 15:59:53 +0000108
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000109 BasicBlock::iterator Inst = Builder->GetInsertPoint();
Nuno Lopes10287d82012-05-23 16:24:52 +0000110 BasicBlock *OldBB = Inst->getParent();
111 BasicBlock *Cont = OldBB->splitBasicBlock(Inst);
112 OldBB->getTerminator()->eraseFromParent();
113
Nuno Lopes10287d82012-05-23 16:24:52 +0000114 if (Cmp)
115 BranchInst::Create(getTrapBB(), Cont, Cmp, OldBB);
116 else
117 BranchInst::Create(getTrapBB(), OldBB);
118}
119
120
Nuno Lopes59e9df72012-05-22 22:02:19 +0000121/// instrument - adds run-time bounds checks to memory accessing instructions.
122/// Ptr is the pointer that will be read/written, and InstVal is either the
123/// result from the load or the value being stored. It is used to determine the
124/// size of memory block that is touched.
125/// Returns true if any change was made to the IR, false otherwise.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000126bool BoundsChecking::instrument(Value *Ptr, Value *InstVal,
127 const DataLayout &DL) {
128 uint64_t NeededSize = DL.getTypeStoreSize(InstVal->getType());
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000129 DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
130 << " bytes\n");
131
Nuno Lopes0e967e02012-06-21 15:59:53 +0000132 SizeOffsetEvalType SizeOffset = ObjSizeEval->compute(Ptr);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000133
Nuno Lopes0e967e02012-06-21 15:59:53 +0000134 if (!ObjSizeEval->bothKnown(SizeOffset)) {
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000135 ++ChecksUnable;
136 return false;
137 }
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000138
Nuno Lopes0e967e02012-06-21 15:59:53 +0000139 Value *Size = SizeOffset.first;
140 Value *Offset = SizeOffset.second;
Nuno Lopes1e8dffd2012-07-03 17:30:18 +0000141 ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
Nuno Lopes0e967e02012-06-21 15:59:53 +0000142
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000143 Type *IntTy = DL.getIntPtrType(Ptr->getType());
Nuno Lopes0e967e02012-06-21 15:59:53 +0000144 Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
145
Nuno Lopes7d000612012-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 Lopes1e8dffd2012-07-03 17:30:18 +0000150 //
151 // optimization: if Size >= 0 (signed), skip 1st check
Nuno Lopes7d000612012-05-31 22:45:40 +0000152 // FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
Nuno Lopes0e967e02012-06-21 15:59:53 +0000153 Value *ObjSize = Builder->CreateSub(Size, Offset);
Nuno Lopes0e967e02012-06-21 15:59:53 +0000154 Value *Cmp2 = Builder->CreateICmpULT(Size, Offset);
155 Value *Cmp3 = Builder->CreateICmpULT(ObjSize, NeededSizeVal);
Nuno Lopes1e8dffd2012-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 Lopes10287d82012-05-23 16:24:52 +0000161 emitBranchToTrap(Or);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000162
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000163 return true;
164}
165
166bool BoundsChecking::runOnFunction(Function &F) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000167 const DataLayout &DL = F.getParent()->getDataLayout();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000168 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000169
Craig Topperf40110f2014-04-25 05:29:35 +0000170 TrapBB = nullptr;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000171 BuilderTy TheBuilder(F.getContext(), TargetFolder(DL));
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000172 Builder = &TheBuilder;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000173 ObjectSizeOffsetEvaluator TheObjSizeEval(DL, TLI, F.getContext(),
Nuno Lopes340b0462013-10-24 09:17:24 +0000174 /*RoundToAlign=*/true);
Nuno Lopes0e967e02012-06-21 15:59:53 +0000175 ObjSizeEval = &TheObjSizeEval;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000176
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);
185 }
186
187 bool MadeChange = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000188 for (Instruction *i : WorkList) {
189 Inst = i;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000190
Nuno Lopesde8c6fb2012-06-23 00:12:34 +0000191 Builder->SetInsertPoint(Inst);
192 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000193 MadeChange |= instrument(LI->getPointerOperand(), LI, DL);
Nuno Lopesde8c6fb2012-06-23 00:12:34 +0000194 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000195 MadeChange |=
196 instrument(SI->getPointerOperand(), SI->getValueOperand(), DL);
Nuno Lopesde8c6fb2012-06-23 00:12:34 +0000197 } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000198 MadeChange |=
199 instrument(AI->getPointerOperand(), AI->getCompareOperand(), DL);
Nuno Lopesde8c6fb2012-06-23 00:12:34 +0000200 } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000201 MadeChange |=
202 instrument(AI->getPointerOperand(), AI->getValOperand(), DL);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000203 } else {
204 llvm_unreachable("unknown Instruction type");
205 }
206 }
207 return MadeChange;
208}
209
Joey Gouly95198232012-11-23 10:47:35 +0000210FunctionPass *llvm::createBoundsCheckingPass() {
211 return new BoundsChecking();
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000212}