blob: a0c78e0468c6163fe622c41d3dae2e4aff637ec8 [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//===----------------------------------------------------------------------===//
Nuno Lopesa2f6cec2012-05-22 17:19:09 +00009
Chandler Carruth00a301d2017-11-14 01:30:04 +000010#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000011#include "llvm/ADT/Statistic.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000012#include "llvm/ADT/Twine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000013#include "llvm/Analysis/MemoryBuiltins.h"
Joel Galenson8dbcc582018-07-24 15:21:54 +000014#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth452a0072014-03-04 11:59:06 +000015#include "llvm/Analysis/TargetFolder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000016#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000017#include "llvm/IR/BasicBlock.h"
18#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/DataLayout.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000020#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/IRBuilder.h"
Chandler Carruth83948572014-03-04 10:30:26 +000022#include "llvm/IR/InstIterator.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000023#include "llvm/IR/InstrTypes.h"
24#include "llvm/IR/Instruction.h"
25#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Intrinsics.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000027#include "llvm/IR/Value.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000028#include "llvm/Pass.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000029#include "llvm/Support/Casting.h"
Nuno Lopes288e86ff62012-05-31 22:58:48 +000030#include "llvm/Support/CommandLine.h"
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000031#include "llvm/Support/Debug.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000032#include "llvm/Support/ErrorHandling.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000033#include "llvm/Support/raw_ostream.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000034#include <cstdint>
35#include <vector>
36
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000037using namespace llvm;
38
Chandler Carruth964daaa2014-04-22 02:55:47 +000039#define DEBUG_TYPE "bounds-checking"
40
Nuno Lopes0e967e02012-06-21 15:59:53 +000041static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
42 cl::desc("Use one trap block per function"));
Nuno Lopes288e86ff62012-05-31 22:58:48 +000043
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000044STATISTIC(ChecksAdded, "Bounds checks added");
45STATISTIC(ChecksSkipped, "Bounds checks skipped");
46STATISTIC(ChecksUnable, "Bounds checks unable to add");
47
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000048using BuilderTy = IRBuilder<TargetFolder>;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000049
Joel Galensoncfe5bc12018-08-03 17:12:23 +000050/// Gets the conditions under which memory accessing instructions will overflow.
Chandler Carruth1594fee2017-11-14 01:13:59 +000051///
52/// \p Ptr is the pointer that will be read/written, and \p InstVal is either
53/// the result from the load or the value being stored. It is used to determine
54/// the size of memory block that is touched.
55///
Joel Galensoncfe5bc12018-08-03 17:12:23 +000056/// Returns the condition under which the access will overflow.
57static Value *getBoundsCheckCond(Value *Ptr, Value *InstVal,
58 const DataLayout &DL, TargetLibraryInfo &TLI,
59 ObjectSizeOffsetEvaluator &ObjSizeEval,
60 BuilderTy &IRB, ScalarEvolution &SE) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000061 uint64_t NeededSize = DL.getTypeStoreSize(InstVal->getType());
Nicola Zaghend34e60c2018-05-14 12:53:11 +000062 LLVM_DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
63 << " bytes\n");
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000064
Chandler Carruth1594fee2017-11-14 01:13:59 +000065 SizeOffsetEvalType SizeOffset = ObjSizeEval.compute(Ptr);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000066
Chandler Carruth1594fee2017-11-14 01:13:59 +000067 if (!ObjSizeEval.bothKnown(SizeOffset)) {
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000068 ++ChecksUnable;
Joel Galensoncfe5bc12018-08-03 17:12:23 +000069 return nullptr;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000070 }
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000071
Nuno Lopes0e967e02012-06-21 15:59:53 +000072 Value *Size = SizeOffset.first;
73 Value *Offset = SizeOffset.second;
Nuno Lopes1e8dffd2012-07-03 17:30:18 +000074 ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
Nuno Lopes0e967e02012-06-21 15:59:53 +000075
Mehdi Aminia28d91d2015-03-10 02:37:25 +000076 Type *IntTy = DL.getIntPtrType(Ptr->getType());
Nuno Lopes0e967e02012-06-21 15:59:53 +000077 Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
78
Joel Galenson8dbcc582018-07-24 15:21:54 +000079 auto SizeRange = SE.getUnsignedRange(SE.getSCEV(Size));
80 auto OffsetRange = SE.getUnsignedRange(SE.getSCEV(Offset));
81 auto NeededSizeRange = SE.getUnsignedRange(SE.getSCEV(NeededSizeVal));
82
Nuno Lopes7d000612012-05-31 22:45:40 +000083 // three checks are required to ensure safety:
84 // . Offset >= 0 (since the offset is given from the base ptr)
85 // . Size >= Offset (unsigned)
86 // . Size - Offset >= NeededSize (unsigned)
Nuno Lopes1e8dffd2012-07-03 17:30:18 +000087 //
88 // optimization: if Size >= 0 (signed), skip 1st check
Nuno Lopes7d000612012-05-31 22:45:40 +000089 // FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
Chandler Carruth1594fee2017-11-14 01:13:59 +000090 Value *ObjSize = IRB.CreateSub(Size, Offset);
Joel Galenson8dbcc582018-07-24 15:21:54 +000091 Value *Cmp2 = SizeRange.getUnsignedMin().uge(OffsetRange.getUnsignedMax())
92 ? ConstantInt::getFalse(Ptr->getContext())
93 : IRB.CreateICmpULT(Size, Offset);
94 Value *Cmp3 = SizeRange.sub(OffsetRange)
95 .getUnsignedMin()
96 .uge(NeededSizeRange.getUnsignedMax())
97 ? ConstantInt::getFalse(Ptr->getContext())
98 : IRB.CreateICmpULT(ObjSize, NeededSizeVal);
Chandler Carruth1594fee2017-11-14 01:13:59 +000099 Value *Or = IRB.CreateOr(Cmp2, Cmp3);
Joel Galenson8dbcc582018-07-24 15:21:54 +0000100 if ((!SizeCI || SizeCI->getValue().slt(0)) &&
101 !SizeRange.getSignedMin().isNonNegative()) {
Chandler Carruth1594fee2017-11-14 01:13:59 +0000102 Value *Cmp1 = IRB.CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
103 Or = IRB.CreateOr(Cmp1, Or);
Nuno Lopes1e8dffd2012-07-03 17:30:18 +0000104 }
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000105
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000106 return Or;
107}
108
109/// Adds run-time bounds checks to memory accessing instructions.
110///
111/// \p Or is the condition that should guard the trap.
112///
113/// \p GetTrapBB is a callable that returns the trap BB to use on failure.
114template <typename GetTrapBBT>
115static void insertBoundsCheck(Value *Or, BuilderTy IRB, GetTrapBBT GetTrapBB) {
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000116 // check if the comparison is always false
117 ConstantInt *C = dyn_cast_or_null<ConstantInt>(Or);
118 if (C) {
119 ++ChecksSkipped;
120 // If non-zero, nothing to do.
121 if (!C->getZExtValue())
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000122 return;
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000123 }
124 ++ChecksAdded;
125
Chandler Carruth1594fee2017-11-14 01:13:59 +0000126 BasicBlock::iterator SplitI = IRB.GetInsertPoint();
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000127 BasicBlock *OldBB = SplitI->getParent();
128 BasicBlock *Cont = OldBB->splitBasicBlock(SplitI);
129 OldBB->getTerminator()->eraseFromParent();
130
131 if (C) {
132 // If we have a constant zero, unconditionally branch.
133 // FIXME: We should really handle this differently to bypass the splitting
134 // the block.
Chandler Carruth1594fee2017-11-14 01:13:59 +0000135 BranchInst::Create(GetTrapBB(IRB), OldBB);
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000136 return;
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000137 }
138
139 // Create the conditional branch.
Chandler Carruth1594fee2017-11-14 01:13:59 +0000140 BranchInst::Create(GetTrapBB(IRB), Cont, Or, OldBB);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000141}
142
Joel Galenson8dbcc582018-07-24 15:21:54 +0000143static bool addBoundsChecking(Function &F, TargetLibraryInfo &TLI,
144 ScalarEvolution &SE) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000145 const DataLayout &DL = F.getParent()->getDataLayout();
Chandler Carruth1594fee2017-11-14 01:13:59 +0000146 ObjectSizeOffsetEvaluator ObjSizeEval(DL, &TLI, F.getContext(),
Nuno Lopes340b0462013-10-24 09:17:24 +0000147 /*RoundToAlign=*/true);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000148
149 // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
150 // touching instructions
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000151 SmallVector<std::pair<Instruction *, Value *>, 4> TrapInfo;
Chandler Carruth1594fee2017-11-14 01:13:59 +0000152 for (Instruction &I : instructions(F)) {
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000153 Value *Or = nullptr;
154 BuilderTy IRB(I.getParent(), BasicBlock::iterator(&I), TargetFolder(DL));
155 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
156 Or = getBoundsCheckCond(LI->getPointerOperand(), LI, DL, TLI,
157 ObjSizeEval, IRB, SE);
158 } else if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
159 Or = getBoundsCheckCond(SI->getPointerOperand(), SI->getValueOperand(),
160 DL, TLI, ObjSizeEval, IRB, SE);
161 } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
162 Or = getBoundsCheckCond(AI->getPointerOperand(), AI->getCompareOperand(),
163 DL, TLI, ObjSizeEval, IRB, SE);
164 } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
165 Or = getBoundsCheckCond(AI->getPointerOperand(), AI->getValOperand(), DL,
166 TLI, ObjSizeEval, IRB, SE);
167 }
168 if (Or)
169 TrapInfo.push_back(std::make_pair(&I, Or));
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000170 }
171
Chandler Carruth1594fee2017-11-14 01:13:59 +0000172 // Create a trapping basic block on demand using a callback. Depending on
173 // flags, this will either create a single block for the entire function or
174 // will create a fresh block every time it is called.
175 BasicBlock *TrapBB = nullptr;
176 auto GetTrapBB = [&TrapBB](BuilderTy &IRB) {
177 if (TrapBB && SingleTrapBB)
178 return TrapBB;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000179
Chandler Carruth1594fee2017-11-14 01:13:59 +0000180 Function *Fn = IRB.GetInsertBlock()->getParent();
181 // FIXME: This debug location doesn't make a lot of sense in the
182 // `SingleTrapBB` case.
183 auto DebugLoc = IRB.getCurrentDebugLocation();
184 IRBuilder<>::InsertPointGuard Guard(IRB);
185 TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
186 IRB.SetInsertPoint(TrapBB);
187
188 auto *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
189 CallInst *TrapCall = IRB.CreateCall(F, {});
190 TrapCall->setDoesNotReturn();
191 TrapCall->setDoesNotThrow();
192 TrapCall->setDebugLoc(DebugLoc);
193 IRB.CreateUnreachable();
194
195 return TrapBB;
196 };
197
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000198 // Add the checks.
199 for (const auto &Entry : TrapInfo) {
200 Instruction *Inst = Entry.first;
Chandler Carruth1594fee2017-11-14 01:13:59 +0000201 BuilderTy IRB(Inst->getParent(), BasicBlock::iterator(Inst), TargetFolder(DL));
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000202 insertBoundsCheck(Entry.second, IRB, GetTrapBB);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000203 }
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000204
205 return !TrapInfo.empty();
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000206}
207
Chandler Carruth00a301d2017-11-14 01:30:04 +0000208PreservedAnalyses BoundsCheckingPass::run(Function &F, FunctionAnalysisManager &AM) {
209 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
Joel Galenson8dbcc582018-07-24 15:21:54 +0000210 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
Chandler Carruth00a301d2017-11-14 01:30:04 +0000211
Joel Galenson8dbcc582018-07-24 15:21:54 +0000212 if (!addBoundsChecking(F, TLI, SE))
Chandler Carruth00a301d2017-11-14 01:30:04 +0000213 return PreservedAnalyses::all();
214
215 return PreservedAnalyses::none();
216}
217
218namespace {
219struct BoundsCheckingLegacyPass : public FunctionPass {
220 static char ID;
221
222 BoundsCheckingLegacyPass() : FunctionPass(ID) {
223 initializeBoundsCheckingLegacyPassPass(*PassRegistry::getPassRegistry());
224 }
225
226 bool runOnFunction(Function &F) override {
227 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Joel Galenson8dbcc582018-07-24 15:21:54 +0000228 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
229 return addBoundsChecking(F, TLI, SE);
Chandler Carruth00a301d2017-11-14 01:30:04 +0000230 }
231
232 void getAnalysisUsage(AnalysisUsage &AU) const override {
233 AU.addRequired<TargetLibraryInfoWrapperPass>();
Joel Galenson8dbcc582018-07-24 15:21:54 +0000234 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth00a301d2017-11-14 01:30:04 +0000235 }
236};
237} // namespace
238
239char BoundsCheckingLegacyPass::ID = 0;
240INITIALIZE_PASS_BEGIN(BoundsCheckingLegacyPass, "bounds-checking",
241 "Run-time bounds checking", false, false)
242INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
243INITIALIZE_PASS_END(BoundsCheckingLegacyPass, "bounds-checking",
244 "Run-time bounds checking", false, false)
245
246FunctionPass *llvm::createBoundsCheckingLegacyPass() {
247 return new BoundsCheckingLegacyPass();
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000248}