blob: 5c48f39800139e16b2f6ed6599700b79efecaff6 [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/ADT/Statistic.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000016#include "llvm/ADT/Twine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#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"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000020#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000023#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/IRBuilder.h"
Chandler Carruth83948572014-03-04 10:30:26 +000025#include "llvm/IR/InstIterator.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000026#include "llvm/IR/InstrTypes.h"
27#include "llvm/IR/Instruction.h"
28#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Intrinsics.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000030#include "llvm/IR/Value.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000031#include "llvm/Pass.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000032#include "llvm/Support/Casting.h"
Nuno Lopes288e86ff62012-05-31 22:58:48 +000033#include "llvm/Support/CommandLine.h"
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000034#include "llvm/Support/Debug.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000035#include "llvm/Support/ErrorHandling.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000036#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000037#include "llvm/Transforms/Instrumentation.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000038#include <cstdint>
39#include <vector>
40
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000041using namespace llvm;
42
Chandler Carruth964daaa2014-04-22 02:55:47 +000043#define DEBUG_TYPE "bounds-checking"
44
Nuno Lopes0e967e02012-06-21 15:59:53 +000045static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
46 cl::desc("Use one trap block per function"));
Nuno Lopes288e86ff62012-05-31 22:58:48 +000047
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000048STATISTIC(ChecksAdded, "Bounds checks added");
49STATISTIC(ChecksSkipped, "Bounds checks skipped");
50STATISTIC(ChecksUnable, "Bounds checks unable to add");
51
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000052using BuilderTy = IRBuilder<TargetFolder>;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000053
54namespace {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000055
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000056 struct BoundsChecking : public FunctionPass {
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000057 static char ID;
58
Joey Gouly95198232012-11-23 10:47:35 +000059 BoundsChecking() : FunctionPass(ID) {
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000060 initializeBoundsCheckingPass(*PassRegistry::getPassRegistry());
61 }
62
Craig Topper3e4c6972014-03-05 09:10:37 +000063 bool runOnFunction(Function &F) override;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000064
Craig Topper3e4c6972014-03-05 09:10:37 +000065 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +000066 AU.addRequired<TargetLibraryInfoWrapperPass>();
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000067 }
68 };
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000069
70} // end anonymous namespace
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000071
72char BoundsChecking::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000073
Nuno Lopes1e8dffd2012-07-03 17:30:18 +000074INITIALIZE_PASS(BoundsChecking, "bounds-checking", "Run-time bounds checking",
75 false, false)
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000076
Chandler Carruth1594fee2017-11-14 01:13:59 +000077/// Adds run-time bounds checks to memory accessing instructions.
78///
79/// \p Ptr is the pointer that will be read/written, and \p InstVal is either
80/// the result from the load or the value being stored. It is used to determine
81/// the size of memory block that is touched.
82///
83/// \p GetTrapBB is a callable that returns the trap BB to use on failure.
84///
Nuno Lopes59e9df72012-05-22 22:02:19 +000085/// Returns true if any change was made to the IR, false otherwise.
Chandler Carruth1594fee2017-11-14 01:13:59 +000086template <typename GetTrapBBT>
87static bool instrumentMemAccess(Value *Ptr, Value *InstVal,
88 const DataLayout &DL, TargetLibraryInfo &TLI,
89 ObjectSizeOffsetEvaluator &ObjSizeEval,
90 BuilderTy &IRB,
91 GetTrapBBT GetTrapBB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000092 uint64_t NeededSize = DL.getTypeStoreSize(InstVal->getType());
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000093 DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
94 << " bytes\n");
95
Chandler Carruth1594fee2017-11-14 01:13:59 +000096 SizeOffsetEvalType SizeOffset = ObjSizeEval.compute(Ptr);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000097
Chandler Carruth1594fee2017-11-14 01:13:59 +000098 if (!ObjSizeEval.bothKnown(SizeOffset)) {
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000099 ++ChecksUnable;
100 return false;
101 }
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000102
Nuno Lopes0e967e02012-06-21 15:59:53 +0000103 Value *Size = SizeOffset.first;
104 Value *Offset = SizeOffset.second;
Nuno Lopes1e8dffd2012-07-03 17:30:18 +0000105 ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
Nuno Lopes0e967e02012-06-21 15:59:53 +0000106
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000107 Type *IntTy = DL.getIntPtrType(Ptr->getType());
Nuno Lopes0e967e02012-06-21 15:59:53 +0000108 Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
109
Nuno Lopes7d000612012-05-31 22:45:40 +0000110 // three checks are required to ensure safety:
111 // . Offset >= 0 (since the offset is given from the base ptr)
112 // . Size >= Offset (unsigned)
113 // . Size - Offset >= NeededSize (unsigned)
Nuno Lopes1e8dffd2012-07-03 17:30:18 +0000114 //
115 // optimization: if Size >= 0 (signed), skip 1st check
Nuno Lopes7d000612012-05-31 22:45:40 +0000116 // FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
Chandler Carruth1594fee2017-11-14 01:13:59 +0000117 Value *ObjSize = IRB.CreateSub(Size, Offset);
118 Value *Cmp2 = IRB.CreateICmpULT(Size, Offset);
119 Value *Cmp3 = IRB.CreateICmpULT(ObjSize, NeededSizeVal);
120 Value *Or = IRB.CreateOr(Cmp2, Cmp3);
Nuno Lopes1e8dffd2012-07-03 17:30:18 +0000121 if (!SizeCI || SizeCI->getValue().slt(0)) {
Chandler Carruth1594fee2017-11-14 01:13:59 +0000122 Value *Cmp1 = IRB.CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
123 Or = IRB.CreateOr(Cmp1, Or);
Nuno Lopes1e8dffd2012-07-03 17:30:18 +0000124 }
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000125
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000126 // check if the comparison is always false
127 ConstantInt *C = dyn_cast_or_null<ConstantInt>(Or);
128 if (C) {
129 ++ChecksSkipped;
130 // If non-zero, nothing to do.
131 if (!C->getZExtValue())
132 return true;
133 }
134 ++ChecksAdded;
135
Chandler Carruth1594fee2017-11-14 01:13:59 +0000136 BasicBlock::iterator SplitI = IRB.GetInsertPoint();
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000137 BasicBlock *OldBB = SplitI->getParent();
138 BasicBlock *Cont = OldBB->splitBasicBlock(SplitI);
139 OldBB->getTerminator()->eraseFromParent();
140
141 if (C) {
142 // If we have a constant zero, unconditionally branch.
143 // FIXME: We should really handle this differently to bypass the splitting
144 // the block.
Chandler Carruth1594fee2017-11-14 01:13:59 +0000145 BranchInst::Create(GetTrapBB(IRB), OldBB);
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000146 return true;
147 }
148
149 // Create the conditional branch.
Chandler Carruth1594fee2017-11-14 01:13:59 +0000150 BranchInst::Create(GetTrapBB(IRB), Cont, Or, OldBB);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000151 return true;
152}
153
154bool BoundsChecking::runOnFunction(Function &F) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000155 const DataLayout &DL = F.getParent()->getDataLayout();
Chandler Carruth1594fee2017-11-14 01:13:59 +0000156 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000157
Chandler Carruth1594fee2017-11-14 01:13:59 +0000158 ObjectSizeOffsetEvaluator ObjSizeEval(DL, &TLI, F.getContext(),
Nuno Lopes340b0462013-10-24 09:17:24 +0000159 /*RoundToAlign=*/true);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000160
161 // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
162 // touching instructions
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000163 std::vector<Instruction *> WorkList;
Chandler Carruth1594fee2017-11-14 01:13:59 +0000164 for (Instruction &I : instructions(F)) {
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000165 if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<AtomicCmpXchgInst>(I) ||
166 isa<AtomicRMWInst>(I))
Chandler Carruth1594fee2017-11-14 01:13:59 +0000167 WorkList.push_back(&I);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000168 }
169
Chandler Carruth1594fee2017-11-14 01:13:59 +0000170 // Create a trapping basic block on demand using a callback. Depending on
171 // flags, this will either create a single block for the entire function or
172 // will create a fresh block every time it is called.
173 BasicBlock *TrapBB = nullptr;
174 auto GetTrapBB = [&TrapBB](BuilderTy &IRB) {
175 if (TrapBB && SingleTrapBB)
176 return TrapBB;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000177
Chandler Carruth1594fee2017-11-14 01:13:59 +0000178 Function *Fn = IRB.GetInsertBlock()->getParent();
179 // FIXME: This debug location doesn't make a lot of sense in the
180 // `SingleTrapBB` case.
181 auto DebugLoc = IRB.getCurrentDebugLocation();
182 IRBuilder<>::InsertPointGuard Guard(IRB);
183 TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
184 IRB.SetInsertPoint(TrapBB);
185
186 auto *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
187 CallInst *TrapCall = IRB.CreateCall(F, {});
188 TrapCall->setDoesNotReturn();
189 TrapCall->setDoesNotThrow();
190 TrapCall->setDebugLoc(DebugLoc);
191 IRB.CreateUnreachable();
192
193 return TrapBB;
194 };
195
196 bool MadeChange = false;
197 for (Instruction *Inst : WorkList) {
198 BuilderTy IRB(Inst->getParent(), BasicBlock::iterator(Inst), TargetFolder(DL));
Nuno Lopesde8c6fb2012-06-23 00:12:34 +0000199 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Chandler Carruth1594fee2017-11-14 01:13:59 +0000200 MadeChange |= instrumentMemAccess(LI->getPointerOperand(), LI, DL, TLI,
201 ObjSizeEval, IRB, GetTrapBB);
Nuno Lopesde8c6fb2012-06-23 00:12:34 +0000202 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000203 MadeChange |=
Chandler Carruth1594fee2017-11-14 01:13:59 +0000204 instrumentMemAccess(SI->getPointerOperand(), SI->getValueOperand(),
205 DL, TLI, ObjSizeEval, IRB, GetTrapBB);
Nuno Lopesde8c6fb2012-06-23 00:12:34 +0000206 } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000207 MadeChange |=
Chandler Carruth1594fee2017-11-14 01:13:59 +0000208 instrumentMemAccess(AI->getPointerOperand(), AI->getCompareOperand(),
209 DL, TLI, ObjSizeEval, IRB, GetTrapBB);
Nuno Lopesde8c6fb2012-06-23 00:12:34 +0000210 } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000211 MadeChange |=
Chandler Carruth1594fee2017-11-14 01:13:59 +0000212 instrumentMemAccess(AI->getPointerOperand(), AI->getValOperand(), DL,
213 TLI, ObjSizeEval, IRB, GetTrapBB);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000214 } else {
215 llvm_unreachable("unknown Instruction type");
216 }
217 }
218 return MadeChange;
219}
220
Joey Gouly95198232012-11-23 10:47:35 +0000221FunctionPass *llvm::createBoundsCheckingPass() {
222 return new BoundsChecking();
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000223}