blob: 5bb06822d523d2f463357c64856ebe3b93fc9a56 [file] [log] [blame]
Kostya Serebryany29a18dc2014-11-11 22:14:37 +00001//===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
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// Coverage instrumentation that works with AddressSanitizer
11// and potentially with other Sanitizers.
12//
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000013// We create a Guard variable with the same linkage
Alexey Samsonov3514f272015-05-07 01:00:31 +000014// as the function and inject this code into the entry block (SCK_Function)
15// or all blocks (SCK_BB):
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000016// if (Guard < 0) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +000017// __sanitizer_cov(&Guard);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000018// }
19// The accesses to Guard are atomic. The rest of the logic is
20// in __sanitizer_cov (it's fine to call it more than once).
21//
Alexey Samsonov3514f272015-05-07 01:00:31 +000022// With SCK_Edge we also split critical edges this effectively
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000023// instrumenting all edges.
24//
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000025// This coverage implementation provides very limited data:
26// it only tells if a given function (block) was ever executed. No counters.
27// But for many use cases this is what we need and the added slowdown small.
28//
29//===----------------------------------------------------------------------===//
30
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000031#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/SmallVector.h"
David Majnemer70497c62015-12-02 23:06:39 +000033#include "llvm/Analysis/EHPersonalities.h"
Mike Aizatsky9b53ab72016-02-27 02:10:27 +000034#include "llvm/Analysis/PostDominators.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000035#include "llvm/IR/CFG.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000036#include "llvm/IR/CallSite.h"
37#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000038#include "llvm/IR/DebugInfo.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000039#include "llvm/IR/Dominators.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000040#include "llvm/IR/Function.h"
41#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000042#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000043#include "llvm/IR/LLVMContext.h"
44#include "llvm/IR/MDBuilder.h"
45#include "llvm/IR/Module.h"
46#include "llvm/IR/Type.h"
47#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/Debug.h"
49#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000050#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000051#include "llvm/Transforms/Scalar.h"
52#include "llvm/Transforms/Utils/BasicBlockUtils.h"
53#include "llvm/Transforms/Utils/ModuleUtils.h"
54
55using namespace llvm;
56
57#define DEBUG_TYPE "sancov"
58
59static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
60static const char *const kSanCovName = "__sanitizer_cov";
Kostya Serebryany77cc7292015-02-04 01:21:45 +000061static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000062static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000063static const char *const kSanCovTracePCIndir = "__sanitizer_cov_trace_pc_indir";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000064static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
65static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000066static const char *const kSanCovTracePC = "__sanitizer_cov_trace_pc";
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000067static const char *const kSanCovTraceCmp = "__sanitizer_cov_trace_cmp";
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +000068static const char *const kSanCovTraceSwitch = "__sanitizer_cov_trace_switch";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000069static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
Evgeniy Stepanov3fdfc7b2015-01-27 15:01:22 +000070static const uint64_t kSanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000071
72static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
73 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
74 "3: all blocks and critical edges, "
75 "4: above plus indirect calls"),
76 cl::Hidden, cl::init(0));
77
Kostya Serebryany77cc7292015-02-04 01:21:45 +000078static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000079 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000080 cl::desc("Use a callback with a guard check inside it if there are"
81 " more than this number of blocks."),
Kostya Serebryany8fb05ac2015-03-10 01:11:53 +000082 cl::Hidden, cl::init(500));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000083
Kostya Serebryanycb45b122014-11-19 00:22:58 +000084static cl::opt<bool>
85 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
86 cl::desc("Experimental basic-block tracing: insert "
87 "callbacks at every basic block"),
88 cl::Hidden, cl::init(false));
89
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000090static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
91 cl::desc("Experimental pc tracing"),
92 cl::Hidden, cl::init(false));
93
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000094static cl::opt<bool>
95 ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares",
96 cl::desc("Experimental tracing of CMP and similar "
97 "instructions"),
98 cl::Hidden, cl::init(false));
99
Mike Aizatsky5971f182016-02-26 01:17:22 +0000100static cl::opt<bool> ClPruneBlocks(
101 "sanitizer-coverage-prune-blocks",
102 cl::desc("Reduce the number of instrumented blocks (experimental)"),
103 cl::Hidden, cl::init(false));
104
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000105// Experimental 8-bit counters used as an additional search heuristic during
106// coverage-guided fuzzing.
107// The counters are not thread-friendly:
108// - contention on these counters may cause significant slowdown;
109// - the counter updates are racy and the results may be inaccurate.
110// They are also inaccurate due to 8-bit integer overflow.
111static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
112 cl::desc("Experimental 8-bit counters"),
113 cl::Hidden, cl::init(false));
114
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000115namespace {
116
Alexey Samsonov3514f272015-05-07 01:00:31 +0000117SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
118 SanitizerCoverageOptions Res;
119 switch (LegacyCoverageLevel) {
120 case 0:
121 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
122 break;
123 case 1:
124 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
125 break;
126 case 2:
127 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
128 break;
129 case 3:
130 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
131 break;
132 case 4:
133 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
134 Res.IndirectCalls = true;
135 break;
136 }
137 return Res;
138}
139
140SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
141 // Sets CoverageType and IndirectCalls.
142 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
143 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
144 Options.IndirectCalls |= CLOpts.IndirectCalls;
145 Options.TraceBB |= ClExperimentalTracing;
146 Options.TraceCmp |= ClExperimentalCMPTracing;
147 Options.Use8bitCounters |= ClUse8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000148 Options.TracePC |= ClExperimentalTracePC;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000149 return Options;
150}
151
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000152class SanitizerCoverageModule : public ModulePass {
153 public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000154 SanitizerCoverageModule(
155 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
156 : ModulePass(ID), Options(OverrideFromCL(Options)) {}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000157 bool runOnModule(Module &M) override;
158 bool runOnFunction(Function &F);
159 static char ID; // Pass identification, replacement for typeid
160 const char *getPassName() const override {
161 return "SanitizerCoverageModule";
162 }
Mike Aizatsky9b53ab72016-02-27 02:10:27 +0000163 void getAnalysisUsage(AnalysisUsage &AU) const override {
164 AU.addRequired<DominatorTreeWrapperPass>();
165 AU.addRequired<PostDominatorTreeWrapperPass>();
166 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000167
Mike Aizatsky9b53ab72016-02-27 02:10:27 +0000168private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000169 void InjectCoverageForIndirectCalls(Function &F,
170 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000171 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000172 void InjectTraceForSwitch(Function &F,
173 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000174 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000175 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000176 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000177 unsigned NumberOfInstrumentedBlocks() {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000178 return SanCovFunction->getNumUses() +
179 SanCovWithCheckFunction->getNumUses() + SanCovTraceBB->getNumUses() +
180 SanCovTraceEnter->getNumUses();
Kostya Serebryany48a40232015-03-10 01:58:27 +0000181 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000182 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000183 Function *SanCovWithCheckFunction;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000184 Function *SanCovIndirCallFunction, *SanCovTracePCIndir;
185 Function *SanCovTraceEnter, *SanCovTraceBB, *SanCovTracePC;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000186 Function *SanCovTraceCmpFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000187 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000188 InlineAsm *EmptyAsm;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000189 Type *IntptrTy, *Int64Ty, *Int64PtrTy;
190 Module *CurModule;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000191 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000192 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000193
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000194 GlobalVariable *GuardArray;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000195 GlobalVariable *EightBitCounterArray;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000196
Alexey Samsonov3514f272015-05-07 01:00:31 +0000197 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000198};
199
200} // namespace
201
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000202bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000203 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
204 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000205 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000206 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000207 CurModule = &M;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000208 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000209 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000210 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000211 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000212 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000213 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000214 Int64Ty = IRB.getInt64Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000215
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000216 SanCovFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000217 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000218 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000219 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000220 SanCovTracePCIndir =
221 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
222 kSanCovTracePCIndir, VoidTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000223 SanCovIndirCallFunction =
224 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
225 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
226 SanCovTraceCmpFunction =
227 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
228 kSanCovTraceCmp, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000229 SanCovTraceSwitchFunction =
230 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
231 kSanCovTraceSwitch, VoidTy, Int64Ty, Int64PtrTy, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000232
Kostya Serebryany73762942014-12-16 21:24:15 +0000233 // We insert an empty inline asm after cov callbacks to avoid callback merge.
234 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
235 StringRef(""), StringRef(""),
236 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000237
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000238 SanCovTracePC = checkSanitizerInterfaceFunction(
239 M.getOrInsertFunction(kSanCovTracePC, VoidTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000240 SanCovTraceEnter = checkSanitizerInterfaceFunction(
241 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
242 SanCovTraceBB = checkSanitizerInterfaceFunction(
243 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000244
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000245 // At this point we create a dummy array of guards because we don't
246 // know how many elements we will need.
247 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000248 Type *Int8Ty = IRB.getInt8Ty();
249
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000250 GuardArray =
251 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
252 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000253 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000254 EightBitCounterArray =
255 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
256 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000257
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000258 for (auto &F : M)
259 runOnFunction(F);
260
Kostya Serebryany48a40232015-03-10 01:58:27 +0000261 auto N = NumberOfInstrumentedBlocks();
262
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000263 // Now we know how many elements we need. Create an array of guards
264 // with one extra element at the beginning for the size.
Kostya Serebryany48a40232015-03-10 01:58:27 +0000265 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000266 GlobalVariable *RealGuardArray = new GlobalVariable(
267 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
268 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
269
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000270
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000271 // Replace the dummy array with the real one.
272 GuardArray->replaceAllUsesWith(
273 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
274 GuardArray->eraseFromParent();
275
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000276 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000277 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000278 // Make sure the array is 16-aligned.
279 static const int kCounterAlignment = 16;
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000280 Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, kCounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000281 RealEightBitCounterArray = new GlobalVariable(
282 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
283 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
284 RealEightBitCounterArray->setAlignment(kCounterAlignment);
285 EightBitCounterArray->replaceAllUsesWith(
286 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
287 EightBitCounterArray->eraseFromParent();
288 }
289
Kostya Serebryany88599462015-02-20 00:30:44 +0000290 // Create variable for module (compilation unit) name
291 Constant *ModNameStrConst =
292 ConstantDataArray::getString(M.getContext(), M.getName(), true);
293 GlobalVariable *ModuleName =
294 new GlobalVariable(M, ModNameStrConst->getType(), true,
295 GlobalValue::PrivateLinkage, ModNameStrConst);
296
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000297 if (!Options.TracePC) {
298 Function *CtorFunc;
299 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
300 M, kSanCovModuleCtorName, kSanCovModuleInitName,
301 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
302 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
303 ConstantInt::get(IntptrTy, N),
304 Options.Use8bitCounters
305 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
306 : Constant::getNullValue(Int8PtrTy),
307 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000308
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000309 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
310 }
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000311
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000312 return true;
313}
314
Mike Aizatsky9b53ab72016-02-27 02:10:27 +0000315static bool shouldInstrumentBlock(const BasicBlock *BB, const DominatorTree *DT,
316 const PostDominatorTree *PDT) {
Mike Aizatsky5971f182016-02-26 01:17:22 +0000317 if (!ClPruneBlocks)
318 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000319
320 // Check if BB dominates all its successors.
Mike Aizatsky9b53ab72016-02-27 02:10:27 +0000321 bool DominatesAll = succ_begin(BB) != succ_end(BB);
Mike Aizatsky5971f182016-02-26 01:17:22 +0000322 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
Mike Aizatsky9b53ab72016-02-27 02:10:27 +0000323 DominatesAll &= DT->dominates(BB, SUCC);
Mike Aizatsky5971f182016-02-26 01:17:22 +0000324 }
325
Mike Aizatsky9b53ab72016-02-27 02:10:27 +0000326 // Check if BB pre-dominates all predecessors.
327 bool PreDominatesAll = pred_begin(BB) != pred_end(BB);
328 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
329 PreDominatesAll &= PDT->dominates(BB, PRED);
330 }
331
332 return !(DominatesAll || PreDominatesAll);
Mike Aizatsky5971f182016-02-26 01:17:22 +0000333}
334
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000335bool SanitizerCoverageModule::runOnFunction(Function &F) {
336 if (F.empty()) return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000337 if (F.getName().find(".module_ctor") != std::string::npos)
338 return false; // Should not instrument sanitizer init functions.
Reid Klecknerdf523372015-09-03 20:18:29 +0000339 // Don't instrument functions using SEH for now. Splitting basic blocks like
340 // we do for coverage breaks WinEHPrepare.
341 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
342 if (F.hasPersonalityFn() &&
343 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
344 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000345 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000346 SplitAllCriticalEdges(F);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000347 SmallVector<Instruction*, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000348 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000349 SmallVector<Instruction*, 8> CmpTraceTargets;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000350 SmallVector<Instruction*, 8> SwitchTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000351
Mike Aizatsky9b53ab72016-02-27 02:10:27 +0000352 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
353 PostDominatorTree *PDT =
354 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
355
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000356 for (auto &BB : F) {
Mike Aizatsky9b53ab72016-02-27 02:10:27 +0000357 if (shouldInstrumentBlock(&BB, DT, PDT))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000358 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000359 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000360 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000361 CallSite CS(&Inst);
362 if (CS && !CS.getCalledFunction())
363 IndirCalls.push_back(&Inst);
364 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000365 if (Options.TraceCmp) {
366 if (isa<ICmpInst>(&Inst))
367 CmpTraceTargets.push_back(&Inst);
368 if (isa<SwitchInst>(&Inst))
369 SwitchTraceTargets.push_back(&Inst);
370 }
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000371 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000372 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000373
374 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000375 InjectCoverageForIndirectCalls(F, IndirCalls);
376 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000377 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000378 return true;
379}
380
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000381bool SanitizerCoverageModule::InjectCoverage(Function &F,
382 ArrayRef<BasicBlock *> AllBlocks) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000383 switch (Options.CoverageType) {
384 case SanitizerCoverageOptions::SCK_None:
385 return false;
386 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000387 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000388 return true;
389 default: {
390 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000391 for (auto BB : AllBlocks)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000392 InjectCoverageAtBlock(F, *BB, UseCalls);
393 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000394 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000395 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000396}
397
398// On every indirect call we call a run-time function
399// __sanitizer_cov_indir_call* with two parameters:
400// - callee address,
401// - global cache array that contains kCacheSize pointers (zero-initialized).
402// The cache is used to speed up recording the caller-callee pairs.
403// The address of the caller is passed implicitly via caller PC.
404// kCacheSize is encoded in the name of the run-time function.
405void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
406 Function &F, ArrayRef<Instruction *> IndirCalls) {
407 if (IndirCalls.empty()) return;
408 const int kCacheSize = 16;
409 const int kCacheAlignment = 64; // Align for better performance.
410 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
411 for (auto I : IndirCalls) {
412 IRBuilder<> IRB(I);
413 CallSite CS(I);
414 Value *Callee = CS.getCalledValue();
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000415 if (isa<InlineAsm>(Callee)) continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000416 GlobalVariable *CalleeCache = new GlobalVariable(
417 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
418 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
419 CalleeCache->setAlignment(kCacheAlignment);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000420 if (Options.TracePC)
421 IRB.CreateCall(SanCovTracePCIndir,
422 IRB.CreatePointerCast(Callee, IntptrTy));
423 else
424 IRB.CreateCall(SanCovIndirCallFunction,
425 {IRB.CreatePointerCast(Callee, IntptrTy),
426 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000427 }
428}
429
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000430// For every switch statement we insert a call:
431// __sanitizer_cov_trace_switch(CondValue,
432// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
433
434void SanitizerCoverageModule::InjectTraceForSwitch(
435 Function &F, ArrayRef<Instruction *> SwitchTraceTargets) {
436 for (auto I : SwitchTraceTargets) {
437 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
438 IRBuilder<> IRB(I);
439 SmallVector<Constant *, 16> Initializers;
440 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000441 if (Cond->getType()->getScalarSizeInBits() >
442 Int64Ty->getScalarSizeInBits())
443 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000444 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
445 Initializers.push_back(
446 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
447 if (Cond->getType()->getScalarSizeInBits() <
448 Int64Ty->getScalarSizeInBits())
449 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
450 for (auto It: SI->cases()) {
451 Constant *C = It.getCaseValue();
452 if (C->getType()->getScalarSizeInBits() <
453 Int64Ty->getScalarSizeInBits())
454 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
455 Initializers.push_back(C);
456 }
457 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
458 GlobalVariable *GV = new GlobalVariable(
459 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
460 ConstantArray::get(ArrayOfInt64Ty, Initializers),
461 "__sancov_gen_cov_switch_values");
462 IRB.CreateCall(SanCovTraceSwitchFunction,
463 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
464 }
465 }
466}
467
468
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000469void SanitizerCoverageModule::InjectTraceForCmp(
470 Function &F, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000471 for (auto I : CmpTraceTargets) {
472 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
473 IRBuilder<> IRB(ICMP);
474 Value *A0 = ICMP->getOperand(0);
475 Value *A1 = ICMP->getOperand(1);
476 if (!A0->getType()->isIntegerTy()) continue;
477 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000478 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
David Blaikieff6409d2015-05-18 22:13:54 +0000479 IRB.CreateCall(
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000480 SanCovTraceCmpFunction,
David Blaikieff6409d2015-05-18 22:13:54 +0000481 {ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()),
482 IRB.CreateIntCast(A0, Int64Ty, true),
483 IRB.CreateIntCast(A1, Int64Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000484 }
485 }
486}
487
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000488void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000489 I->setMetadata(
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000490 I->getModule()->getMDKindID("nosanitize"), MDNode::get(*C, None));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000491}
492
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000493void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
494 bool UseCalls) {
Alexey Samsonov342b1e82015-06-30 23:11:45 +0000495 // Don't insert coverage for unreachable blocks: we will never call
496 // __sanitizer_cov() for them, so counting them in
497 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
498 // percentage. Also, unreachable instructions frequently have no debug
499 // locations.
500 if (isa<UnreachableInst>(BB.getTerminator()))
501 return;
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000502 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000503
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000504 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000505 DebugLoc EntryLoc;
506 if (IsEntryBB) {
507 if (auto SP = getDISubprogram(&F))
508 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000509 // Keep static allocas and llvm.localescape calls in the entry block. Even
510 // if we aren't splitting the block, it's nice for allocas to be before
511 // calls.
512 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000513 } else {
514 EntryLoc = IP->getDebugLoc();
515 }
516
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000517 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000518 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000519 Value *GuardP = IRB.CreateAdd(
520 IRB.CreatePointerCast(GuardArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000521 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000522 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
523 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000524 if (Options.TracePC) {
525 IRB.CreateCall(SanCovTracePC);
526 } else if (Options.TraceBB) {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000527 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
528 } else if (UseCalls) {
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000529 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
530 } else {
531 LoadInst *Load = IRB.CreateLoad(GuardP);
532 Load->setAtomic(Monotonic);
533 Load->setAlignment(4);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000534 SetNoSanitizeMetadata(Load);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000535 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
536 Instruction *Ins = SplitBlockAndInsertIfThen(
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000537 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000538 IRB.SetInsertPoint(Ins);
539 IRB.SetCurrentDebugLocation(EntryLoc);
540 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
541 IRB.CreateCall(SanCovFunction, GuardP);
David Blaikieff6409d2015-05-18 22:13:54 +0000542 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000543 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000544
Alexey Samsonov3514f272015-05-07 01:00:31 +0000545 if (Options.Use8bitCounters) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000546 IRB.SetInsertPoint(&*IP);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000547 Value *P = IRB.CreateAdd(
548 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000549 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000550 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000551 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000552 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000553 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000554 SetNoSanitizeMetadata(LI);
555 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000556 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000557}
558
559char SanitizerCoverageModule::ID = 0;
560INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
561 "SanitizerCoverage: TODO."
562 "ModulePass", false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000563ModulePass *llvm::createSanitizerCoverageModulePass(
564 const SanitizerCoverageOptions &Options) {
565 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000566}