blob: 031effb406057a33b2e3c83d2bae0fb50167dfb8 [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 SanCovTracePCGuardSection = "__sancov_guards";
82static const char *const SanCovTracePCGuardName =
83 "__sanitizer_cov_trace_pc_guard";
84static const char *const SanCovTracePCGuardInitName =
85 "__sanitizer_cov_trace_pc_guard_init";
86
Mike Aizatsky759aca02016-03-18 23:29:29 +000087static cl::opt<int> ClCoverageLevel(
88 "sanitizer-coverage-level",
89 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
90 "3: all blocks and critical edges, "
91 "4: above plus indirect calls"),
92 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000093
Kostya Serebryany77cc7292015-02-04 01:21:45 +000094static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000095 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000096 cl::desc("Use a callback with a guard check inside it if there are"
97 " more than this number of blocks."),
Kostya Serebryany8fb05ac2015-03-10 01:11:53 +000098 cl::Hidden, cl::init(500));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000099
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000100static cl::opt<bool>
101 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
102 cl::desc("Experimental basic-block tracing: insert "
103 "callbacks at every basic block"),
104 cl::Hidden, cl::init(false));
105
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000106static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
107 cl::desc("Experimental pc tracing"),
108 cl::Hidden, cl::init(false));
109
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000110static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
111 cl::desc("pc tracing with a guard"),
112 cl::Hidden, cl::init(false));
113
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000114static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000115 ClCMPTracing("sanitizer-coverage-trace-compares",
116 cl::desc("Tracing of CMP and similar instructions"),
117 cl::Hidden, cl::init(false));
118
119static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
120 cl::desc("Tracing of DIV instructions"),
121 cl::Hidden, cl::init(false));
122
123static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
124 cl::desc("Tracing of GEP instructions"),
125 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000126
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000127static cl::opt<bool>
128 ClPruneBlocks("sanitizer-coverage-prune-blocks",
129 cl::desc("Reduce the number of instrumented blocks"),
130 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000131
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000132// Experimental 8-bit counters used as an additional search heuristic during
133// coverage-guided fuzzing.
134// The counters are not thread-friendly:
135// - contention on these counters may cause significant slowdown;
136// - the counter updates are racy and the results may be inaccurate.
137// They are also inaccurate due to 8-bit integer overflow.
138static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
139 cl::desc("Experimental 8-bit counters"),
140 cl::Hidden, cl::init(false));
141
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000142namespace {
143
Alexey Samsonov3514f272015-05-07 01:00:31 +0000144SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
145 SanitizerCoverageOptions Res;
146 switch (LegacyCoverageLevel) {
147 case 0:
148 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
149 break;
150 case 1:
151 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
152 break;
153 case 2:
154 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
155 break;
156 case 3:
157 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
158 break;
159 case 4:
160 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
161 Res.IndirectCalls = true;
162 break;
163 }
164 return Res;
165}
166
167SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
168 // Sets CoverageType and IndirectCalls.
169 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
170 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
171 Options.IndirectCalls |= CLOpts.IndirectCalls;
172 Options.TraceBB |= ClExperimentalTracing;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000173 Options.TraceCmp |= ClCMPTracing;
174 Options.TraceDiv |= ClDIVTracing;
175 Options.TraceGep |= ClGEPTracing;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000176 Options.Use8bitCounters |= ClUse8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000177 Options.TracePC |= ClExperimentalTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000178 Options.TracePCGuard |= ClTracePCGuard;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000179 return Options;
180}
181
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000182class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000183public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000184 SanitizerCoverageModule(
185 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000186 : ModulePass(ID), Options(OverrideFromCL(Options)) {
187 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
188 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000189 bool runOnModule(Module &M) override;
190 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000191 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000192 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000193
Chandler Carruth30061152016-03-18 22:43:42 +0000194 void getAnalysisUsage(AnalysisUsage &AU) const override {
195 AU.addRequired<DominatorTreeWrapperPass>();
196 AU.addRequired<PostDominatorTreeWrapperPass>();
197 }
198
199private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000200 void InjectCoverageForIndirectCalls(Function &F,
201 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000202 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000203 void InjectTraceForDiv(Function &F,
204 ArrayRef<BinaryOperator *> DivTraceTargets);
205 void InjectTraceForGep(Function &F,
206 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000207 void InjectTraceForSwitch(Function &F,
208 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000209 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000210 void CreateFunctionGuardArray(size_t NumGuards, Function &F);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000211 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000212 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
213 bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000214 unsigned NumberOfInstrumentedBlocks() {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000215 return SanCovFunction->getNumUses() +
216 SanCovWithCheckFunction->getNumUses() + SanCovTraceBB->getNumUses() +
217 SanCovTraceEnter->getNumUses();
Kostya Serebryany48a40232015-03-10 01:58:27 +0000218 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000219 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000220 Function *SanCovWithCheckFunction;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000221 Function *SanCovIndirCallFunction, *SanCovTracePCIndir;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000222 Function *SanCovTraceEnter, *SanCovTraceBB, *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000223 Function *SanCovTraceCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000224 Function *SanCovTraceDivFunction[2];
225 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000226 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000227 InlineAsm *EmptyAsm;
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000228 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000229 Module *CurModule;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000230 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000231 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000232
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000233 GlobalVariable *GuardArray;
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000234 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000235 GlobalVariable *EightBitCounterArray;
Kostya Serebryany186d6182016-09-27 01:08:33 +0000236 bool HasSancovGuardsSection;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000237
Alexey Samsonov3514f272015-05-07 01:00:31 +0000238 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000239};
240
Mike Aizatsky759aca02016-03-18 23:29:29 +0000241} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000242
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000243bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000244 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
245 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000246 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000247 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000248 CurModule = &M;
Kostya Serebryany186d6182016-09-27 01:08:33 +0000249 HasSancovGuardsSection = false;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000250 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000251 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000252 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000253 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000254 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000255 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000256 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000257 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000258 Int32Ty = IRB.getInt32Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000259
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000260 SanCovFunction = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000261 M.getOrInsertFunction(SanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000262 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000263 M.getOrInsertFunction(SanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
264 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
265 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000266 SanCovIndirCallFunction =
267 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000268 SanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000269 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000270 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000271 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty(), nullptr));
272 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
273 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
274 IRB.getInt16Ty(), nullptr));
275 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
276 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
277 IRB.getInt32Ty(), nullptr));
278 SanCovTraceCmpFunction[3] =
279 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
280 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty, nullptr));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000281
282 SanCovTraceDivFunction[0] =
283 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
284 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty(), nullptr));
285 SanCovTraceDivFunction[1] =
286 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
287 SanCovTraceDiv8, VoidTy, Int64Ty, nullptr));
288 SanCovTraceGepFunction =
289 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
290 SanCovTraceGep, VoidTy, IntptrTy, nullptr));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000291 SanCovTraceSwitchFunction =
292 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000293 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000294
Kostya Serebryany73762942014-12-16 21:24:15 +0000295 // We insert an empty inline asm after cov callbacks to avoid callback merge.
296 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
297 StringRef(""), StringRef(""),
298 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000299
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000300 SanCovTracePC = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000301 M.getOrInsertFunction(SanCovTracePCName, VoidTy, nullptr));
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000302 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000303 SanCovTracePCGuardName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000304 SanCovTraceEnter = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000305 M.getOrInsertFunction(SanCovTraceEnterName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000306 SanCovTraceBB = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000307 M.getOrInsertFunction(SanCovTraceBBName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000308
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000309 // At this point we create a dummy array of guards because we don't
310 // know how many elements we will need.
311 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000312 Type *Int8Ty = IRB.getInt8Ty();
313
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000314 if (!Options.TracePCGuard)
315 GuardArray =
316 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
317 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000318 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000319 EightBitCounterArray =
320 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
321 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000322
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000323 for (auto &F : M)
324 runOnFunction(F);
325
Kostya Serebryany48a40232015-03-10 01:58:27 +0000326 auto N = NumberOfInstrumentedBlocks();
327
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000328 GlobalVariable *RealGuardArray = nullptr;
329 if (!Options.TracePCGuard) {
330 // Now we know how many elements we need. Create an array of guards
331 // with one extra element at the beginning for the size.
332 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
333 RealGuardArray = new GlobalVariable(
334 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
335 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000336
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000337 // Replace the dummy array with the real one.
338 GuardArray->replaceAllUsesWith(
339 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
340 GuardArray->eraseFromParent();
341 }
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000342
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000343 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000344 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000345 // Make sure the array is 16-aligned.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000346 static const int CounterAlignment = 16;
347 Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, CounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000348 RealEightBitCounterArray = new GlobalVariable(
349 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
350 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
Mike Aizatsky759aca02016-03-18 23:29:29 +0000351 RealEightBitCounterArray->setAlignment(CounterAlignment);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000352 EightBitCounterArray->replaceAllUsesWith(
353 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
354 EightBitCounterArray->eraseFromParent();
355 }
356
Kostya Serebryany88599462015-02-20 00:30:44 +0000357 // Create variable for module (compilation unit) name
358 Constant *ModNameStrConst =
359 ConstantDataArray::getString(M.getContext(), M.getName(), true);
360 GlobalVariable *ModuleName =
361 new GlobalVariable(M, ModNameStrConst->getType(), true,
362 GlobalValue::PrivateLinkage, ModNameStrConst);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000363 if (Options.TracePCGuard) {
Kostya Serebryany186d6182016-09-27 01:08:33 +0000364 if (HasSancovGuardsSection) {
365 Function *CtorFunc;
366 std::string SectionName(SanCovTracePCGuardSection);
367 GlobalVariable *Bounds[2];
368 const char *Prefix[2] = {"__start_", "__stop_"};
369 for (int i = 0; i < 2; i++) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000370 Bounds[i] = new GlobalVariable(M, Int32PtrTy, false,
Kostya Serebryany186d6182016-09-27 01:08:33 +0000371 GlobalVariable::ExternalLinkage, nullptr,
372 Prefix[i] + SectionName);
373 Bounds[i]->setVisibility(GlobalValue::HiddenVisibility);
374 }
375 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
376 M, SanCovModuleCtorName, SanCovTracePCGuardInitName,
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000377 {Int32PtrTy, Int32PtrTy},
378 {IRB.CreatePointerCast(Bounds[0], Int32PtrTy),
379 IRB.CreatePointerCast(Bounds[1], Int32PtrTy)});
Kostya Serebryany186d6182016-09-27 01:08:33 +0000380
381 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000382 }
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000383 } else if (!Options.TracePC) {
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000384 Function *CtorFunc;
385 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000386 M, SanCovModuleCtorName, SanCovModuleInitName,
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000387 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
388 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
Mike Aizatsky759aca02016-03-18 23:29:29 +0000389 ConstantInt::get(IntptrTy, N),
390 Options.Use8bitCounters
391 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
392 : Constant::getNullValue(Int8PtrTy),
393 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000394
Mike Aizatsky759aca02016-03-18 23:29:29 +0000395 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000396 }
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000397
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000398 return true;
399}
400
Mike Aizatsky9987f432016-03-23 23:15:03 +0000401// True if block has successors and it dominates all of them.
402static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
403 if (succ_begin(BB) == succ_end(BB))
404 return false;
405
406 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
407 if (!DT->dominates(BB, SUCC))
408 return false;
409 }
410
411 return true;
412}
413
414// True if block has predecessors and it postdominates all of them.
415static bool isFullPostDominator(const BasicBlock *BB,
416 const PostDominatorTree *PDT) {
417 if (pred_begin(BB) == pred_end(BB))
418 return false;
419
420 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
421 if (!PDT->dominates(BB, PRED))
422 return false;
423 }
424
425 return true;
426}
427
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000428static bool shouldInstrumentBlock(const Function& F, const BasicBlock *BB, const DominatorTree *DT,
Mike Aizatsky602f7922016-03-21 23:08:16 +0000429 const PostDominatorTree *PDT) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000430 // Don't insert coverage for unreachable blocks: we will never call
431 // __sanitizer_cov() for them, so counting them in
432 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
433 // percentage. Also, unreachable instructions frequently have no debug
434 // locations.
435 if (isa<UnreachableInst>(BB->getTerminator()))
436 return false;
437
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000438 if (!ClPruneBlocks || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000439 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000440
Mike Aizatsky9987f432016-03-23 23:15:03 +0000441 return !(isFullDominator(BB, DT) || isFullPostDominator(BB, PDT));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000442}
443
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000444bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000445 if (F.empty())
446 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000447 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000448 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000449 if (F.getName().startswith("__sanitizer_"))
450 return false; // Don't instrument __sanitizer_* callbacks.
Reid Klecknerec803542016-11-11 19:18:45 +0000451 // Don't instrument MSVC CRT configuration helpers. They may run before normal
452 // initialization.
453 if (F.getName() == "__local_stdio_printf_options" ||
454 F.getName() == "__local_stdio_scanf_options")
455 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000456 // Don't instrument functions using SEH for now. Splitting basic blocks like
457 // we do for coverage breaks WinEHPrepare.
458 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
459 if (F.hasPersonalityFn() &&
460 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
461 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000462 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000463 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000464 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000465 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000466 SmallVector<Instruction *, 8> CmpTraceTargets;
467 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000468 SmallVector<BinaryOperator *, 8> DivTraceTargets;
469 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000470
Mike Aizatsky602f7922016-03-21 23:08:16 +0000471 const DominatorTree *DT =
472 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
473 const PostDominatorTree *PDT =
474 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
475
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000476 for (auto &BB : F) {
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000477 if (shouldInstrumentBlock(F, &BB, DT, PDT))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000478 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000479 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000480 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000481 CallSite CS(&Inst);
482 if (CS && !CS.getCalledFunction())
483 IndirCalls.push_back(&Inst);
484 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000485 if (Options.TraceCmp) {
486 if (isa<ICmpInst>(&Inst))
487 CmpTraceTargets.push_back(&Inst);
488 if (isa<SwitchInst>(&Inst))
489 SwitchTraceTargets.push_back(&Inst);
490 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000491 if (Options.TraceDiv)
492 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
493 if (BO->getOpcode() == Instruction::SDiv ||
494 BO->getOpcode() == Instruction::UDiv)
495 DivTraceTargets.push_back(BO);
496 if (Options.TraceGep)
497 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
498 GepTraceTargets.push_back(GEP);
499 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000500 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000501
502 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000503 InjectCoverageForIndirectCalls(F, IndirCalls);
504 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000505 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000506 InjectTraceForDiv(F, DivTraceTargets);
507 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000508 return true;
509}
Kostya Serebryany4d25ad92016-10-11 19:36:50 +0000510void SanitizerCoverageModule::CreateFunctionGuardArray(size_t NumGuards,
511 Function &F) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000512 if (!Options.TracePCGuard) return;
513 HasSancovGuardsSection = true;
514 ArrayType *ArrayOfInt32Ty = ArrayType::get(Int32Ty, NumGuards);
515 FunctionGuardArray = new GlobalVariable(
Kostya Serebryany4d25ad92016-10-11 19:36:50 +0000516 *CurModule, ArrayOfInt32Ty, false, GlobalVariable::PrivateLinkage,
Kostya Serebryany9d6dc7b2016-11-15 21:12:50 +0000517 Constant::getNullValue(ArrayOfInt32Ty), "__sancov_gen_");
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000518 if (auto Comdat = F.getComdat())
519 FunctionGuardArray->setComdat(Comdat);
520 FunctionGuardArray->setSection(SanCovTracePCGuardSection);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000521}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000522
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000523bool SanitizerCoverageModule::InjectCoverage(Function &F,
524 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000525 if (AllBlocks.empty()) return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000526 switch (Options.CoverageType) {
527 case SanitizerCoverageOptions::SCK_None:
528 return false;
529 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000530 CreateFunctionGuardArray(1, F);
531 InjectCoverageAtBlock(F, F.getEntryBlock(), 0, false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000532 return true;
533 default: {
534 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000535 CreateFunctionGuardArray(AllBlocks.size(), F);
536 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
537 InjectCoverageAtBlock(F, *AllBlocks[i], i, UseCalls);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000538 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000539 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000540 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000541}
542
543// On every indirect call we call a run-time function
544// __sanitizer_cov_indir_call* with two parameters:
545// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000546// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000547// The cache is used to speed up recording the caller-callee pairs.
548// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000549// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000550void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
551 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000552 if (IndirCalls.empty())
553 return;
554 const int CacheSize = 16;
555 const int CacheAlignment = 64; // Align for better performance.
556 Type *Ty = ArrayType::get(IntptrTy, CacheSize);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000557 for (auto I : IndirCalls) {
558 IRBuilder<> IRB(I);
559 CallSite CS(I);
560 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000561 if (isa<InlineAsm>(Callee))
562 continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000563 GlobalVariable *CalleeCache = new GlobalVariable(
564 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
565 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
Mike Aizatsky759aca02016-03-18 23:29:29 +0000566 CalleeCache->setAlignment(CacheAlignment);
Kostya Serebryany66a9c172016-09-15 22:11:08 +0000567 if (Options.TracePC || Options.TracePCGuard)
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000568 IRB.CreateCall(SanCovTracePCIndir,
569 IRB.CreatePointerCast(Callee, IntptrTy));
570 else
571 IRB.CreateCall(SanCovIndirCallFunction,
572 {IRB.CreatePointerCast(Callee, IntptrTy),
Mike Aizatsky759aca02016-03-18 23:29:29 +0000573 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000574 }
575}
576
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000577// For every switch statement we insert a call:
578// __sanitizer_cov_trace_switch(CondValue,
579// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
580
581void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000582 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000583 for (auto I : SwitchTraceTargets) {
584 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
585 IRBuilder<> IRB(I);
586 SmallVector<Constant *, 16> Initializers;
587 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000588 if (Cond->getType()->getScalarSizeInBits() >
589 Int64Ty->getScalarSizeInBits())
590 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000591 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
592 Initializers.push_back(
593 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
594 if (Cond->getType()->getScalarSizeInBits() <
595 Int64Ty->getScalarSizeInBits())
596 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000597 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000598 Constant *C = It.getCaseValue();
599 if (C->getType()->getScalarSizeInBits() <
600 Int64Ty->getScalarSizeInBits())
601 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
602 Initializers.push_back(C);
603 }
604 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
605 GlobalVariable *GV = new GlobalVariable(
606 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
607 ConstantArray::get(ArrayOfInt64Ty, Initializers),
608 "__sancov_gen_cov_switch_values");
609 IRB.CreateCall(SanCovTraceSwitchFunction,
610 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
611 }
612 }
613}
614
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000615void SanitizerCoverageModule::InjectTraceForDiv(
616 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
617 for (auto BO : DivTraceTargets) {
618 IRBuilder<> IRB(BO);
619 Value *A1 = BO->getOperand(1);
620 if (isa<ConstantInt>(A1)) continue;
621 if (!A1->getType()->isIntegerTy())
622 continue;
623 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
624 int CallbackIdx = TypeSize == 32 ? 0 :
625 TypeSize == 64 ? 1 : -1;
626 if (CallbackIdx < 0) continue;
627 auto Ty = Type::getIntNTy(*C, TypeSize);
628 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
629 {IRB.CreateIntCast(A1, Ty, true)});
630 }
631}
632
633void SanitizerCoverageModule::InjectTraceForGep(
634 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
635 for (auto GEP : GepTraceTargets) {
636 IRBuilder<> IRB(GEP);
637 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000638 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000639 IRB.CreateCall(SanCovTraceGepFunction,
640 {IRB.CreateIntCast(*I, IntptrTy, true)});
641 }
642}
643
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000644void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000645 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000646 for (auto I : CmpTraceTargets) {
647 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
648 IRBuilder<> IRB(ICMP);
649 Value *A0 = ICMP->getOperand(0);
650 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000651 if (!A0->getType()->isIntegerTy())
652 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000653 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000654 int CallbackIdx = TypeSize == 8 ? 0 :
655 TypeSize == 16 ? 1 :
656 TypeSize == 32 ? 2 :
657 TypeSize == 64 ? 3 : -1;
658 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000659 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000660 auto Ty = Type::getIntNTy(*C, TypeSize);
David Blaikieff6409d2015-05-18 22:13:54 +0000661 IRB.CreateCall(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000662 SanCovTraceCmpFunction[CallbackIdx],
663 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000664 }
665 }
666}
667
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000668void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000669 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
670 MDNode::get(*C, None));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000671}
672
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000673void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000674 size_t Idx, bool UseCalls) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000675 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000676 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000677 DebugLoc EntryLoc;
678 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000679 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000680 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000681 // Keep static allocas and llvm.localescape calls in the entry block. Even
682 // if we aren't splitting the block, it's nice for allocas to be before
683 // calls.
684 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000685 } else {
686 EntryLoc = IP->getDebugLoc();
687 }
688
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000689 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000690 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000691 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000692 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
693 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000694 } else if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000695 auto GuardPtr = IRB.CreateIntToPtr(
696 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
697 ConstantInt::get(IntptrTy, Idx * 4)),
698 Int32PtrTy);
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000699 if (!UseCalls) {
700 auto GuardLoad = IRB.CreateLoad(GuardPtr);
701 GuardLoad->setAtomic(AtomicOrdering::Monotonic);
702 GuardLoad->setAlignment(8);
703 SetNoSanitizeMetadata(GuardLoad); // Don't instrument with e.g. asan.
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000704 auto Cmp = IRB.CreateICmpNE(
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000705 GuardLoad, Constant::getNullValue(GuardLoad->getType()));
706 auto Ins = SplitBlockAndInsertIfThen(
707 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
708 IRB.SetCurrentDebugLocation(EntryLoc);
709 IRB.SetInsertPoint(Ins);
710 }
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000711 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
712 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000713 } else {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000714 Value *GuardP = IRB.CreateAdd(
715 IRB.CreatePointerCast(GuardArray, IntptrTy),
716 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
717 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
718 if (Options.TraceBB) {
719 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
720 } else if (UseCalls) {
721 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
722 } else {
723 LoadInst *Load = IRB.CreateLoad(GuardP);
724 Load->setAtomic(AtomicOrdering::Monotonic);
725 Load->setAlignment(4);
726 SetNoSanitizeMetadata(Load);
727 Value *Cmp =
728 IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
729 Instruction *Ins = SplitBlockAndInsertIfThen(
730 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
731 IRB.SetInsertPoint(Ins);
732 IRB.SetCurrentDebugLocation(EntryLoc);
733 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
734 IRB.CreateCall(SanCovFunction, GuardP);
735 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
736 }
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000737 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000738
Alexey Samsonov3514f272015-05-07 01:00:31 +0000739 if (Options.Use8bitCounters) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000740 IRB.SetInsertPoint(&*IP);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000741 Value *P = IRB.CreateAdd(
742 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000743 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000744 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000745 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000746 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000747 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000748 SetNoSanitizeMetadata(LI);
749 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000750 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000751}
752
753char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000754INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000755 "SanitizerCoverage: TODO."
756 "ModulePass",
757 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000758INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
759INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
760INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000761 "SanitizerCoverage: TODO."
762 "ModulePass",
763 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000764ModulePass *llvm::createSanitizerCoverageModulePass(
765 const SanitizerCoverageOptions &Options) {
766 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000767}