blob: b6ec70a413e2509f1b7e5a716c8450e9c2ae3f2e [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"
Chandler Carruth30061152016-03-18 22:43:42 +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
Mike Aizatsky759aca02016-03-18 23:29:29 +000059static const char *const SanCovModuleInitName = "__sanitizer_cov_module_init";
60static const char *const SanCovName = "__sanitizer_cov";
61static const char *const SanCovWithCheckName = "__sanitizer_cov_with_check";
62static const char *const SanCovIndirCallName = "__sanitizer_cov_indir_call16";
63static const char *const SanCovTracePCIndirName =
64 "__sanitizer_cov_trace_pc_indir";
65static const char *const SanCovTraceEnterName =
66 "__sanitizer_cov_trace_func_enter";
67static const char *const SanCovTraceBBName =
68 "__sanitizer_cov_trace_basic_block";
69static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
Kostya Serebryany524c3f32016-08-18 01:25:28 +000070static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
71static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
72static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
73static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000074static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
75static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
76static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
Mike Aizatsky759aca02016-03-18 23:29:29 +000077static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
78static const char *const SanCovModuleCtorName = "sancov.module_ctor";
79static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000080
Kostya Serebryanyda718e52016-09-14 01:39:35 +000081static const char *const SanCovTracePCGuardName =
82 "__sanitizer_cov_trace_pc_guard";
83static const char *const SanCovTracePCGuardInitName =
84 "__sanitizer_cov_trace_pc_guard_init";
85
Mike Aizatsky759aca02016-03-18 23:29:29 +000086static cl::opt<int> ClCoverageLevel(
87 "sanitizer-coverage-level",
88 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
89 "3: all blocks and critical edges, "
90 "4: above plus indirect calls"),
91 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000092
Kostya Serebryany77cc7292015-02-04 01:21:45 +000093static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000094 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000095 cl::desc("Use a callback with a guard check inside it if there are"
96 " more than this number of blocks."),
Kostya Serebryany4b2ff072017-01-24 00:57:31 +000097 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000098
Kostya Serebryanycb45b122014-11-19 00:22:58 +000099static cl::opt<bool>
100 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
101 cl::desc("Experimental basic-block tracing: insert "
102 "callbacks at every basic block"),
103 cl::Hidden, cl::init(false));
104
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000105static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
106 cl::desc("Experimental pc tracing"),
107 cl::Hidden, cl::init(false));
108
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000109static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
110 cl::desc("pc tracing with a guard"),
111 cl::Hidden, cl::init(false));
112
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000113static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000114 ClCMPTracing("sanitizer-coverage-trace-compares",
115 cl::desc("Tracing of CMP and similar instructions"),
116 cl::Hidden, cl::init(false));
117
118static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
119 cl::desc("Tracing of DIV instructions"),
120 cl::Hidden, cl::init(false));
121
122static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
123 cl::desc("Tracing of GEP instructions"),
124 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000125
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000126static cl::opt<bool>
127 ClPruneBlocks("sanitizer-coverage-prune-blocks",
128 cl::desc("Reduce the number of instrumented blocks"),
129 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000130
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000131// Experimental 8-bit counters used as an additional search heuristic during
132// coverage-guided fuzzing.
133// The counters are not thread-friendly:
134// - contention on these counters may cause significant slowdown;
135// - the counter updates are racy and the results may be inaccurate.
136// They are also inaccurate due to 8-bit integer overflow.
137static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
138 cl::desc("Experimental 8-bit counters"),
139 cl::Hidden, cl::init(false));
140
Justin Bogner41e632b2017-02-01 02:38:39 +0000141static StringRef getSanCovTracePCGuardSection(const Module &M) {
142 return Triple(M.getTargetTriple()).isOSBinFormatMachO()
143 ? "__DATA,__sancov_guards"
144 : "__sancov_guards";
145}
146
147static StringRef getSanCovTracePCGuardSectionStart(const Module &M) {
148 return Triple(M.getTargetTriple()).isOSBinFormatMachO()
149 ? "\1section$start$__DATA$__sancov_guards"
150 : "__start___sancov_guards";
151}
152
153static StringRef getSanCovTracePCGuardSectionEnd(const Module &M) {
154 return Triple(M.getTargetTriple()).isOSBinFormatMachO()
155 ? "\1section$end$__DATA$__sancov_guards"
156 : "__stop___sancov_guards";
157}
158
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000159namespace {
160
Alexey Samsonov3514f272015-05-07 01:00:31 +0000161SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
162 SanitizerCoverageOptions Res;
163 switch (LegacyCoverageLevel) {
164 case 0:
165 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
166 break;
167 case 1:
168 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
169 break;
170 case 2:
171 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
172 break;
173 case 3:
174 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
175 break;
176 case 4:
177 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
178 Res.IndirectCalls = true;
179 break;
180 }
181 return Res;
182}
183
184SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
185 // Sets CoverageType and IndirectCalls.
186 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
187 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
188 Options.IndirectCalls |= CLOpts.IndirectCalls;
189 Options.TraceBB |= ClExperimentalTracing;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000190 Options.TraceCmp |= ClCMPTracing;
191 Options.TraceDiv |= ClDIVTracing;
192 Options.TraceGep |= ClGEPTracing;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000193 Options.Use8bitCounters |= ClUse8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000194 Options.TracePC |= ClExperimentalTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000195 Options.TracePCGuard |= ClTracePCGuard;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000196 return Options;
197}
198
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000199class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000200public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000201 SanitizerCoverageModule(
202 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000203 : ModulePass(ID), Options(OverrideFromCL(Options)) {
204 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
205 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000206 bool runOnModule(Module &M) override;
207 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000208 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000209 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000210
Chandler Carruth30061152016-03-18 22:43:42 +0000211 void getAnalysisUsage(AnalysisUsage &AU) const override {
212 AU.addRequired<DominatorTreeWrapperPass>();
213 AU.addRequired<PostDominatorTreeWrapperPass>();
214 }
215
216private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000217 void InjectCoverageForIndirectCalls(Function &F,
218 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000219 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000220 void InjectTraceForDiv(Function &F,
221 ArrayRef<BinaryOperator *> DivTraceTargets);
222 void InjectTraceForGep(Function &F,
223 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000224 void InjectTraceForSwitch(Function &F,
225 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000226 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000227 void CreateFunctionGuardArray(size_t NumGuards, Function &F);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000228 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000229 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
230 bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000231 unsigned NumberOfInstrumentedBlocks() {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000232 return SanCovFunction->getNumUses() +
233 SanCovWithCheckFunction->getNumUses() + SanCovTraceBB->getNumUses() +
234 SanCovTraceEnter->getNumUses();
Kostya Serebryany48a40232015-03-10 01:58:27 +0000235 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000236 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000237 Function *SanCovWithCheckFunction;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000238 Function *SanCovIndirCallFunction, *SanCovTracePCIndir;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000239 Function *SanCovTraceEnter, *SanCovTraceBB, *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000240 Function *SanCovTraceCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000241 Function *SanCovTraceDivFunction[2];
242 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000243 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000244 InlineAsm *EmptyAsm;
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000245 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000246 Module *CurModule;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000247 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000248 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000249
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000250 GlobalVariable *GuardArray;
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000251 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000252 GlobalVariable *EightBitCounterArray;
Kostya Serebryany186d6182016-09-27 01:08:33 +0000253 bool HasSancovGuardsSection;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000254
Alexey Samsonov3514f272015-05-07 01:00:31 +0000255 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000256};
257
Mike Aizatsky759aca02016-03-18 23:29:29 +0000258} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000259
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000260bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000261 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
262 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000263 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000264 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000265 CurModule = &M;
Kostya Serebryany186d6182016-09-27 01:08:33 +0000266 HasSancovGuardsSection = false;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000267 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000268 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000269 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000270 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000271 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000272 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000273 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000274 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000275 Int32Ty = IRB.getInt32Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000276
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000277 SanCovFunction = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000278 M.getOrInsertFunction(SanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000279 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000280 M.getOrInsertFunction(SanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
281 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
282 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000283 SanCovIndirCallFunction =
284 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000285 SanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000286 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000287 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000288 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty(), nullptr));
289 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
290 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
291 IRB.getInt16Ty(), nullptr));
292 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
293 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
294 IRB.getInt32Ty(), nullptr));
295 SanCovTraceCmpFunction[3] =
296 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
297 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty, nullptr));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000298
299 SanCovTraceDivFunction[0] =
300 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
301 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty(), nullptr));
302 SanCovTraceDivFunction[1] =
303 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
304 SanCovTraceDiv8, VoidTy, Int64Ty, nullptr));
305 SanCovTraceGepFunction =
306 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
307 SanCovTraceGep, VoidTy, IntptrTy, nullptr));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000308 SanCovTraceSwitchFunction =
309 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000310 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000311
Kostya Serebryany73762942014-12-16 21:24:15 +0000312 // We insert an empty inline asm after cov callbacks to avoid callback merge.
313 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
314 StringRef(""), StringRef(""),
315 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000316
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000317 SanCovTracePC = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000318 M.getOrInsertFunction(SanCovTracePCName, VoidTy, nullptr));
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000319 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000320 SanCovTracePCGuardName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000321 SanCovTraceEnter = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000322 M.getOrInsertFunction(SanCovTraceEnterName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000323 SanCovTraceBB = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000324 M.getOrInsertFunction(SanCovTraceBBName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000325
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000326 // At this point we create a dummy array of guards because we don't
327 // know how many elements we will need.
328 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000329 Type *Int8Ty = IRB.getInt8Ty();
330
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000331 if (!Options.TracePCGuard)
332 GuardArray =
333 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
334 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000335 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000336 EightBitCounterArray =
337 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
338 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000339
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000340 for (auto &F : M)
341 runOnFunction(F);
342
Kostya Serebryany48a40232015-03-10 01:58:27 +0000343 auto N = NumberOfInstrumentedBlocks();
344
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000345 GlobalVariable *RealGuardArray = nullptr;
346 if (!Options.TracePCGuard) {
347 // Now we know how many elements we need. Create an array of guards
348 // with one extra element at the beginning for the size.
349 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
350 RealGuardArray = new GlobalVariable(
351 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
352 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000353
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000354 // Replace the dummy array with the real one.
355 GuardArray->replaceAllUsesWith(
356 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
357 GuardArray->eraseFromParent();
358 }
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000359
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000360 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000361 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000362 // Make sure the array is 16-aligned.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000363 static const int CounterAlignment = 16;
364 Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, CounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000365 RealEightBitCounterArray = new GlobalVariable(
366 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
367 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
Mike Aizatsky759aca02016-03-18 23:29:29 +0000368 RealEightBitCounterArray->setAlignment(CounterAlignment);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000369 EightBitCounterArray->replaceAllUsesWith(
370 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
371 EightBitCounterArray->eraseFromParent();
372 }
373
Kostya Serebryany88599462015-02-20 00:30:44 +0000374 // Create variable for module (compilation unit) name
375 Constant *ModNameStrConst =
376 ConstantDataArray::getString(M.getContext(), M.getName(), true);
Reid Kleckner3a83e762016-11-16 16:50:43 +0000377 GlobalVariable *ModuleName = new GlobalVariable(
378 M, ModNameStrConst->getType(), true, GlobalValue::PrivateLinkage,
379 ModNameStrConst, "__sancov_gen_modname");
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000380 if (Options.TracePCGuard) {
Kostya Serebryany186d6182016-09-27 01:08:33 +0000381 if (HasSancovGuardsSection) {
382 Function *CtorFunc;
Justin Bogner41e632b2017-02-01 02:38:39 +0000383 GlobalVariable *SecStart = new GlobalVariable(
384 M, Int32PtrTy, false, GlobalVariable::ExternalLinkage, nullptr,
385 getSanCovTracePCGuardSectionStart(*CurModule));
386 SecStart->setVisibility(GlobalValue::HiddenVisibility);
387 GlobalVariable *SecEnd = new GlobalVariable(
388 M, Int32PtrTy, false, GlobalVariable::ExternalLinkage, nullptr,
389 getSanCovTracePCGuardSectionEnd(*CurModule));
390 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
391
Kostya Serebryany186d6182016-09-27 01:08:33 +0000392 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
393 M, SanCovModuleCtorName, SanCovTracePCGuardInitName,
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000394 {Int32PtrTy, Int32PtrTy},
Justin Bogner41e632b2017-02-01 02:38:39 +0000395 {IRB.CreatePointerCast(SecStart, Int32PtrTy),
396 IRB.CreatePointerCast(SecEnd, Int32PtrTy)});
Kostya Serebryany186d6182016-09-27 01:08:33 +0000397
398 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000399 }
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000400 } else if (!Options.TracePC) {
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000401 Function *CtorFunc;
402 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000403 M, SanCovModuleCtorName, SanCovModuleInitName,
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000404 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
405 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
Mike Aizatsky759aca02016-03-18 23:29:29 +0000406 ConstantInt::get(IntptrTy, N),
407 Options.Use8bitCounters
408 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
409 : Constant::getNullValue(Int8PtrTy),
410 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000411
Mike Aizatsky759aca02016-03-18 23:29:29 +0000412 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000413 }
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000414
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000415 return true;
416}
417
Mike Aizatsky9987f432016-03-23 23:15:03 +0000418// True if block has successors and it dominates all of them.
419static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
420 if (succ_begin(BB) == succ_end(BB))
421 return false;
422
423 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
424 if (!DT->dominates(BB, SUCC))
425 return false;
426 }
427
428 return true;
429}
430
431// True if block has predecessors and it postdominates all of them.
432static bool isFullPostDominator(const BasicBlock *BB,
433 const PostDominatorTree *PDT) {
434 if (pred_begin(BB) == pred_end(BB))
435 return false;
436
437 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
438 if (!PDT->dominates(BB, PRED))
439 return false;
440 }
441
442 return true;
443}
444
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000445static bool shouldInstrumentBlock(const Function& F, const BasicBlock *BB, const DominatorTree *DT,
Mike Aizatsky602f7922016-03-21 23:08:16 +0000446 const PostDominatorTree *PDT) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000447 // Don't insert coverage for unreachable blocks: we will never call
448 // __sanitizer_cov() for them, so counting them in
449 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
450 // percentage. Also, unreachable instructions frequently have no debug
451 // locations.
452 if (isa<UnreachableInst>(BB->getTerminator()))
453 return false;
454
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000455 if (!ClPruneBlocks || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000456 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000457
Mike Aizatsky9987f432016-03-23 23:15:03 +0000458 return !(isFullDominator(BB, DT) || isFullPostDominator(BB, PDT));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000459}
460
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000461bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000462 if (F.empty())
463 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000464 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000465 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000466 if (F.getName().startswith("__sanitizer_"))
467 return false; // Don't instrument __sanitizer_* callbacks.
Reid Klecknerec803542016-11-11 19:18:45 +0000468 // Don't instrument MSVC CRT configuration helpers. They may run before normal
469 // initialization.
470 if (F.getName() == "__local_stdio_printf_options" ||
471 F.getName() == "__local_stdio_scanf_options")
472 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000473 // Don't instrument functions using SEH for now. Splitting basic blocks like
474 // we do for coverage breaks WinEHPrepare.
475 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
476 if (F.hasPersonalityFn() &&
477 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
478 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000479 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000480 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000481 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000482 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000483 SmallVector<Instruction *, 8> CmpTraceTargets;
484 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000485 SmallVector<BinaryOperator *, 8> DivTraceTargets;
486 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000487
Mike Aizatsky602f7922016-03-21 23:08:16 +0000488 const DominatorTree *DT =
489 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
490 const PostDominatorTree *PDT =
491 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
492
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000493 for (auto &BB : F) {
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000494 if (shouldInstrumentBlock(F, &BB, DT, PDT))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000495 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000496 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000497 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000498 CallSite CS(&Inst);
499 if (CS && !CS.getCalledFunction())
500 IndirCalls.push_back(&Inst);
501 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000502 if (Options.TraceCmp) {
503 if (isa<ICmpInst>(&Inst))
504 CmpTraceTargets.push_back(&Inst);
505 if (isa<SwitchInst>(&Inst))
506 SwitchTraceTargets.push_back(&Inst);
507 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000508 if (Options.TraceDiv)
509 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
510 if (BO->getOpcode() == Instruction::SDiv ||
511 BO->getOpcode() == Instruction::UDiv)
512 DivTraceTargets.push_back(BO);
513 if (Options.TraceGep)
514 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
515 GepTraceTargets.push_back(GEP);
516 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000517 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000518
519 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000520 InjectCoverageForIndirectCalls(F, IndirCalls);
521 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000522 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000523 InjectTraceForDiv(F, DivTraceTargets);
524 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000525 return true;
526}
Kostya Serebryany4d25ad92016-10-11 19:36:50 +0000527void SanitizerCoverageModule::CreateFunctionGuardArray(size_t NumGuards,
528 Function &F) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000529 if (!Options.TracePCGuard) return;
530 HasSancovGuardsSection = true;
531 ArrayType *ArrayOfInt32Ty = ArrayType::get(Int32Ty, NumGuards);
532 FunctionGuardArray = new GlobalVariable(
Kostya Serebryany4d25ad92016-10-11 19:36:50 +0000533 *CurModule, ArrayOfInt32Ty, false, GlobalVariable::PrivateLinkage,
Kostya Serebryany9d6dc7b2016-11-15 21:12:50 +0000534 Constant::getNullValue(ArrayOfInt32Ty), "__sancov_gen_");
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000535 if (auto Comdat = F.getComdat())
536 FunctionGuardArray->setComdat(Comdat);
Justin Bogner41e632b2017-02-01 02:38:39 +0000537 FunctionGuardArray->setSection(getSanCovTracePCGuardSection(*CurModule));
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000538}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000539
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000540bool SanitizerCoverageModule::InjectCoverage(Function &F,
541 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000542 if (AllBlocks.empty()) return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000543 switch (Options.CoverageType) {
544 case SanitizerCoverageOptions::SCK_None:
545 return false;
546 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000547 CreateFunctionGuardArray(1, F);
548 InjectCoverageAtBlock(F, F.getEntryBlock(), 0, false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000549 return true;
550 default: {
551 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000552 CreateFunctionGuardArray(AllBlocks.size(), F);
553 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
554 InjectCoverageAtBlock(F, *AllBlocks[i], i, UseCalls);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000555 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000556 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000557 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000558}
559
560// On every indirect call we call a run-time function
561// __sanitizer_cov_indir_call* with two parameters:
562// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000563// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000564// The cache is used to speed up recording the caller-callee pairs.
565// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000566// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000567void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
568 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000569 if (IndirCalls.empty())
570 return;
571 const int CacheSize = 16;
572 const int CacheAlignment = 64; // Align for better performance.
573 Type *Ty = ArrayType::get(IntptrTy, CacheSize);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000574 for (auto I : IndirCalls) {
575 IRBuilder<> IRB(I);
576 CallSite CS(I);
577 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000578 if (isa<InlineAsm>(Callee))
579 continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000580 GlobalVariable *CalleeCache = new GlobalVariable(
581 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
582 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
Mike Aizatsky759aca02016-03-18 23:29:29 +0000583 CalleeCache->setAlignment(CacheAlignment);
Kostya Serebryany66a9c172016-09-15 22:11:08 +0000584 if (Options.TracePC || Options.TracePCGuard)
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000585 IRB.CreateCall(SanCovTracePCIndir,
586 IRB.CreatePointerCast(Callee, IntptrTy));
587 else
588 IRB.CreateCall(SanCovIndirCallFunction,
589 {IRB.CreatePointerCast(Callee, IntptrTy),
Mike Aizatsky759aca02016-03-18 23:29:29 +0000590 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000591 }
592}
593
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000594// For every switch statement we insert a call:
595// __sanitizer_cov_trace_switch(CondValue,
596// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
597
598void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000599 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000600 for (auto I : SwitchTraceTargets) {
601 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
602 IRBuilder<> IRB(I);
603 SmallVector<Constant *, 16> Initializers;
604 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000605 if (Cond->getType()->getScalarSizeInBits() >
606 Int64Ty->getScalarSizeInBits())
607 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000608 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
609 Initializers.push_back(
610 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
611 if (Cond->getType()->getScalarSizeInBits() <
612 Int64Ty->getScalarSizeInBits())
613 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000614 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000615 Constant *C = It.getCaseValue();
616 if (C->getType()->getScalarSizeInBits() <
617 Int64Ty->getScalarSizeInBits())
618 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
619 Initializers.push_back(C);
620 }
Kostya Serebryanyf24e52c2016-12-27 21:20:06 +0000621 std::sort(Initializers.begin() + 2, Initializers.end(),
622 [](const Constant *A, const Constant *B) {
623 return cast<ConstantInt>(A)->getLimitedValue() <
624 cast<ConstantInt>(B)->getLimitedValue();
625 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000626 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
627 GlobalVariable *GV = new GlobalVariable(
628 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
629 ConstantArray::get(ArrayOfInt64Ty, Initializers),
630 "__sancov_gen_cov_switch_values");
631 IRB.CreateCall(SanCovTraceSwitchFunction,
632 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
633 }
634 }
635}
636
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000637void SanitizerCoverageModule::InjectTraceForDiv(
638 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
639 for (auto BO : DivTraceTargets) {
640 IRBuilder<> IRB(BO);
641 Value *A1 = BO->getOperand(1);
642 if (isa<ConstantInt>(A1)) continue;
643 if (!A1->getType()->isIntegerTy())
644 continue;
645 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
646 int CallbackIdx = TypeSize == 32 ? 0 :
647 TypeSize == 64 ? 1 : -1;
648 if (CallbackIdx < 0) continue;
649 auto Ty = Type::getIntNTy(*C, TypeSize);
650 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
651 {IRB.CreateIntCast(A1, Ty, true)});
652 }
653}
654
655void SanitizerCoverageModule::InjectTraceForGep(
656 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
657 for (auto GEP : GepTraceTargets) {
658 IRBuilder<> IRB(GEP);
659 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000660 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000661 IRB.CreateCall(SanCovTraceGepFunction,
662 {IRB.CreateIntCast(*I, IntptrTy, true)});
663 }
664}
665
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000666void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000667 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000668 for (auto I : CmpTraceTargets) {
669 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
670 IRBuilder<> IRB(ICMP);
671 Value *A0 = ICMP->getOperand(0);
672 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000673 if (!A0->getType()->isIntegerTy())
674 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000675 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000676 int CallbackIdx = TypeSize == 8 ? 0 :
677 TypeSize == 16 ? 1 :
678 TypeSize == 32 ? 2 :
679 TypeSize == 64 ? 3 : -1;
680 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000681 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000682 auto Ty = Type::getIntNTy(*C, TypeSize);
David Blaikieff6409d2015-05-18 22:13:54 +0000683 IRB.CreateCall(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000684 SanCovTraceCmpFunction[CallbackIdx],
685 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000686 }
687 }
688}
689
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000690void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000691 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
692 MDNode::get(*C, None));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000693}
694
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000695void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000696 size_t Idx, bool UseCalls) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000697 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000698 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000699 DebugLoc EntryLoc;
700 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000701 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000702 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000703 // Keep static allocas and llvm.localescape calls in the entry block. Even
704 // if we aren't splitting the block, it's nice for allocas to be before
705 // calls.
706 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000707 } else {
708 EntryLoc = IP->getDebugLoc();
709 }
710
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000711 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000712 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000713 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000714 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
715 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000716 } else if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000717 auto GuardPtr = IRB.CreateIntToPtr(
718 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
719 ConstantInt::get(IntptrTy, Idx * 4)),
720 Int32PtrTy);
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000721 if (!UseCalls) {
722 auto GuardLoad = IRB.CreateLoad(GuardPtr);
723 GuardLoad->setAtomic(AtomicOrdering::Monotonic);
724 GuardLoad->setAlignment(8);
725 SetNoSanitizeMetadata(GuardLoad); // Don't instrument with e.g. asan.
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000726 auto Cmp = IRB.CreateICmpNE(
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000727 GuardLoad, Constant::getNullValue(GuardLoad->getType()));
728 auto Ins = SplitBlockAndInsertIfThen(
729 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000730 IRB.SetInsertPoint(Ins);
Kostya Serebryany520753a2016-12-03 01:43:30 +0000731 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000732 }
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000733 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
734 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000735 } else {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000736 Value *GuardP = IRB.CreateAdd(
737 IRB.CreatePointerCast(GuardArray, IntptrTy),
738 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
739 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
740 if (Options.TraceBB) {
741 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
742 } else if (UseCalls) {
743 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
744 } else {
745 LoadInst *Load = IRB.CreateLoad(GuardP);
746 Load->setAtomic(AtomicOrdering::Monotonic);
747 Load->setAlignment(4);
748 SetNoSanitizeMetadata(Load);
749 Value *Cmp =
750 IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
751 Instruction *Ins = SplitBlockAndInsertIfThen(
752 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
753 IRB.SetInsertPoint(Ins);
754 IRB.SetCurrentDebugLocation(EntryLoc);
755 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
756 IRB.CreateCall(SanCovFunction, GuardP);
757 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
758 }
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000759 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000760
Alexey Samsonov3514f272015-05-07 01:00:31 +0000761 if (Options.Use8bitCounters) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000762 IRB.SetInsertPoint(&*IP);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000763 Value *P = IRB.CreateAdd(
764 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000765 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000766 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000767 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000768 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000769 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000770 SetNoSanitizeMetadata(LI);
771 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000772 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000773}
774
775char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000776INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000777 "SanitizerCoverage: TODO."
778 "ModulePass",
779 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000780INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
781INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
782INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000783 "SanitizerCoverage: TODO."
784 "ModulePass",
785 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000786ModulePass *llvm::createSanitizerCoverageModulePass(
787 const SanitizerCoverageOptions &Options) {
788 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000789}