blob: 8a12c0fb38744a5221948175db8487cb6d5c1899 [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//
Kostya Serebryany53b34c82017-05-31 18:27:33 +000010// Coverage instrumentation done on LLVM IR level, works with Sanitizers.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000011//
12//===----------------------------------------------------------------------===//
13
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000014#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/SmallVector.h"
David Majnemer70497c62015-12-02 23:06:39 +000016#include "llvm/Analysis/EHPersonalities.h"
George Karpenkov018472c2017-05-24 00:29:12 +000017#include "llvm/Analysis/PostDominators.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000018#include "llvm/IR/CFG.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000019#include "llvm/IR/CallSite.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000020#include "llvm/IR/Constant.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000021#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000022#include "llvm/IR/DebugInfo.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000023#include "llvm/IR/Dominators.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000024#include "llvm/IR/Function.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000025#include "llvm/IR/GlobalVariable.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000026#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000027#include "llvm/IR/InlineAsm.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000028#include "llvm/IR/Intrinsics.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000029#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/MDBuilder.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Type.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000036#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000037#include "llvm/Transforms/Scalar.h"
38#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39#include "llvm/Transforms/Utils/ModuleUtils.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "sancov"
44
Mike Aizatsky759aca02016-03-18 23:29:29 +000045static const char *const SanCovTracePCIndirName =
46 "__sanitizer_cov_trace_pc_indir";
Mike Aizatsky759aca02016-03-18 23:29:29 +000047static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
Kostya Serebryany524c3f32016-08-18 01:25:28 +000048static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
49static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
50static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
51static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
Alexander Potapenko52410812017-08-10 15:00:13 +000052static const char *const SanCovTraceConstCmp1 =
53 "__sanitizer_cov_trace_const_cmp1";
54static const char *const SanCovTraceConstCmp2 =
55 "__sanitizer_cov_trace_const_cmp2";
56static const char *const SanCovTraceConstCmp4 =
57 "__sanitizer_cov_trace_const_cmp4";
58static const char *const SanCovTraceConstCmp8 =
59 "__sanitizer_cov_trace_const_cmp8";
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000060static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
61static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
62static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
Mike Aizatsky759aca02016-03-18 23:29:29 +000063static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
64static const char *const SanCovModuleCtorName = "sancov.module_ctor";
65static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000066
Kostya Serebryanyda718e52016-09-14 01:39:35 +000067static const char *const SanCovTracePCGuardName =
68 "__sanitizer_cov_trace_pc_guard";
69static const char *const SanCovTracePCGuardInitName =
70 "__sanitizer_cov_trace_pc_guard_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000071static const char *const SanCov8bitCountersInitName =
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000072 "__sanitizer_cov_8bit_counters_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000073static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
Kostya Serebryanyda718e52016-09-14 01:39:35 +000074
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000075static const char *const SanCovGuardsSectionName = "sancov_guards";
George Karpenkov406c1132017-06-14 23:40:25 +000076static const char *const SanCovCountersSectionName = "sancov_cntrs";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000077static const char *const SanCovPCsSectionName = "sancov_pcs";
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000078
Matt Morehouse5c7fc762017-08-18 18:43:30 +000079static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
80static const char *const SanCovLowestStackTLSWrapperName =
81 "_ZTW21__sancov_lowest_stack";
82
Mike Aizatsky759aca02016-03-18 23:29:29 +000083static cl::opt<int> ClCoverageLevel(
84 "sanitizer-coverage-level",
85 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +000086 "3: all blocks and critical edges"),
Mike Aizatsky759aca02016-03-18 23:29:29 +000087 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000088
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000089static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
90 cl::desc("Experimental pc tracing"), cl::Hidden,
91 cl::init(false));
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000092
Kostya Serebryanyda718e52016-09-14 01:39:35 +000093static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
94 cl::desc("pc tracing with a guard"),
95 cl::Hidden, cl::init(false));
96
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000097// If true, we create a global variable that contains PCs of all instrumented
98// BBs, put this global into a named section, and pass this section's bounds
99// to __sanitizer_cov_pcs_init.
100// This way the coverage instrumentation does not need to acquire the PCs
101// at run-time. Works with trace-pc-guard and inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000102static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000103 cl::desc("create a static PC table"),
104 cl::Hidden, cl::init(false));
105
106static cl::opt<bool>
107 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
108 cl::desc("increments 8-bit counter for every edge"),
109 cl::Hidden, cl::init(false));
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000110
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000111static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000112 ClCMPTracing("sanitizer-coverage-trace-compares",
113 cl::desc("Tracing of CMP and similar instructions"),
114 cl::Hidden, cl::init(false));
115
116static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
117 cl::desc("Tracing of DIV instructions"),
118 cl::Hidden, cl::init(false));
119
120static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
121 cl::desc("Tracing of GEP instructions"),
122 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000123
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000124static cl::opt<bool>
125 ClPruneBlocks("sanitizer-coverage-prune-blocks",
126 cl::desc("Reduce the number of instrumented blocks"),
127 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000128
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000129static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
130 cl::desc("max stack depth tracing"),
131 cl::Hidden, cl::init(false));
132
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000133namespace {
134
Alexey Samsonov3514f272015-05-07 01:00:31 +0000135SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
136 SanitizerCoverageOptions Res;
137 switch (LegacyCoverageLevel) {
138 case 0:
139 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
140 break;
141 case 1:
142 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
143 break;
144 case 2:
145 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
146 break;
147 case 3:
148 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
149 break;
150 case 4:
151 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
152 Res.IndirectCalls = true;
153 break;
154 }
155 return Res;
156}
157
158SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
159 // Sets CoverageType and IndirectCalls.
160 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
161 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
162 Options.IndirectCalls |= CLOpts.IndirectCalls;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000163 Options.TraceCmp |= ClCMPTracing;
164 Options.TraceDiv |= ClDIVTracing;
165 Options.TraceGep |= ClGEPTracing;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000166 Options.TracePC |= ClTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000167 Options.TracePCGuard |= ClTracePCGuard;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000168 Options.Inline8bitCounters |= ClInline8bitCounters;
Kostya Serebryany063b6522017-07-28 00:09:29 +0000169 Options.PCTable |= ClCreatePCTable;
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000170 Options.NoPrune |= !ClPruneBlocks;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000171 Options.StackDepth |= ClStackDepth;
172 if (!Options.TracePCGuard && !Options.TracePC &&
173 !Options.Inline8bitCounters && !Options.StackDepth)
174 Options.TracePCGuard = true; // TracePCGuard is default.
Alexey Samsonov3514f272015-05-07 01:00:31 +0000175 return Options;
176}
177
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000178class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000179public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000180 SanitizerCoverageModule(
181 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000182 : ModulePass(ID), Options(OverrideFromCL(Options)) {
183 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
184 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000185 bool runOnModule(Module &M) override;
186 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000187 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000188 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000189
Chandler Carruth30061152016-03-18 22:43:42 +0000190 void getAnalysisUsage(AnalysisUsage &AU) const override {
191 AU.addRequired<DominatorTreeWrapperPass>();
George Karpenkov018472c2017-05-24 00:29:12 +0000192 AU.addRequired<PostDominatorTreeWrapperPass>();
Chandler Carruth30061152016-03-18 22:43:42 +0000193 }
194
195private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000196 void InjectCoverageForIndirectCalls(Function &F,
197 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000198 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000199 void InjectTraceForDiv(Function &F,
200 ArrayRef<BinaryOperator *> DivTraceTargets);
201 void InjectTraceForGep(Function &F,
202 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000203 void InjectTraceForSwitch(Function &F,
204 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000205 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000206 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
207 Function &F, Type *Ty,
208 const char *Section);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000209 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
210 void CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000211 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000212 Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
213 Type *Ty, const char *Section);
214 std::pair<GlobalVariable *, GlobalVariable *>
215 CreateSecStartEnd(Module &M, const char *Section, Type *Ty);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000216
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000217 void SetNoSanitizeMetadata(Instruction *I) {
218 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
219 MDNode::get(*C, None));
220 }
221
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000222 std::string getSectionName(const std::string &Section) const;
223 std::string getSectionStart(const std::string &Section) const;
224 std::string getSectionEnd(const std::string &Section) const;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000225 Function *SanCovTracePCIndir;
Kostya Serebryanybe87d482017-04-19 21:48:09 +0000226 Function *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000227 Function *SanCovTraceCmpFunction[4];
Alexander Potapenko52410812017-08-10 15:00:13 +0000228 Function *SanCovTraceConstCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000229 Function *SanCovTraceDivFunction[2];
230 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000231 Function *SanCovTraceSwitchFunction;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000232 Function *SanCovLowestStackTLSWrapper;
233 GlobalVariable *SanCovLowestStack;
Kostya Serebryany73762942014-12-16 21:24:15 +0000234 InlineAsm *EmptyAsm;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000235 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
Alexander Potapenko52410812017-08-10 15:00:13 +0000236 *Int16Ty, *Int8Ty, *Int8PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000237 Module *CurModule;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000238 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000239 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000240 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000241
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000242 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000243 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000244 GlobalVariable *FunctionPCsArray; // for pc-table.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000245
Alexey Samsonov3514f272015-05-07 01:00:31 +0000246 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000247};
248
Mike Aizatsky759aca02016-03-18 23:29:29 +0000249} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000250
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000251std::pair<GlobalVariable *, GlobalVariable *>
252SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
253 Type *Ty) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000254 GlobalVariable *SecStart =
255 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
256 getSectionStart(Section));
257 SecStart->setVisibility(GlobalValue::HiddenVisibility);
258 GlobalVariable *SecEnd =
259 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
260 nullptr, getSectionEnd(Section));
261 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
262
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000263 return std::make_pair(SecStart, SecEnd);
264}
265
266
267Function *SanitizerCoverageModule::CreateInitCallsForSections(
268 Module &M, const char *InitFunctionName, Type *Ty,
269 const char *Section) {
270 IRBuilder<> IRB(M.getContext());
271 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
272 auto SecStart = SecStartEnd.first;
273 auto SecEnd = SecStartEnd.second;
274 Function *CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000275 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
276 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
277 {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
278
279 if (TargetTriple.supportsCOMDAT()) {
280 // Use comdat to dedup CtorFunc.
281 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
282 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
283 } else {
284 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
285 }
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000286 return CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000287}
288
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000289bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000290 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
291 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000292 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000293 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000294 CurModule = &M;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000295 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000296 FunctionGuardArray = nullptr;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000297 Function8bitCounterArray = nullptr;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000298 FunctionPCsArray = nullptr;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000299 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000300 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000301 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000302 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000303 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000304 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000305 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000306 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000307 Int32Ty = IRB.getInt32Ty();
Alexander Potapenko52410812017-08-10 15:00:13 +0000308 Int16Ty = IRB.getInt16Ty();
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000309 Int8Ty = IRB.getInt8Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000310
Mike Aizatsky759aca02016-03-18 23:29:29 +0000311 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000312 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000313 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000314 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000315 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000316 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
317 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000318 IRB.getInt16Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000319 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
320 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000321 IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000322 SanCovTraceCmpFunction[3] =
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000323 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000324 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000325
Alexander Potapenko52410812017-08-10 15:00:13 +0000326 SanCovTraceConstCmpFunction[0] =
327 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
328 SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
329 SanCovTraceConstCmpFunction[1] =
330 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
331 SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
332 SanCovTraceConstCmpFunction[2] =
333 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
334 SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
335 SanCovTraceConstCmpFunction[3] =
336 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
337 SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
338
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000339 SanCovTraceDivFunction[0] =
340 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000341 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000342 SanCovTraceDivFunction[1] =
343 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000344 SanCovTraceDiv8, VoidTy, Int64Ty));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000345 SanCovTraceGepFunction =
346 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000347 SanCovTraceGep, VoidTy, IntptrTy));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000348 SanCovTraceSwitchFunction =
349 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000350 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000351
352 Constant *SanCovLowestStackConstant =
353 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
354 SanCovLowestStackTLSWrapper =
355 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
356 SanCovLowestStackTLSWrapperName, IntptrTy->getPointerTo()));
357 if (Options.StackDepth) {
358 assert(isa<GlobalVariable>(SanCovLowestStackConstant));
359 SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
360 if (!SanCovLowestStack->isDeclaration()) {
361 // Check that the user has correctly defined:
362 // thread_local uintptr_t __sancov_lowest_stack
363 // and initialize it.
364 assert(SanCovLowestStack->isThreadLocal());
365 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
366 }
367 }
368
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000369 // Make sure smaller parameters are zero-extended to i64 as required by the
370 // x86_64 ABI.
371 if (TargetTriple.getArch() == Triple::x86_64) {
372 for (int i = 0; i < 3; i++) {
373 SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
374 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko52410812017-08-10 15:00:13 +0000375 SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
376 SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000377 }
378 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
379 }
380
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000381
Kostya Serebryany73762942014-12-16 21:24:15 +0000382 // We insert an empty inline asm after cov callbacks to avoid callback merge.
383 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
384 StringRef(""), StringRef(""),
385 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000386
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000387 SanCovTracePC = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000388 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000389 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000390 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000391
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000392 for (auto &F : M)
393 runOnFunction(F);
394
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000395 Function *Ctor = nullptr;
Justin Bogner41e632b2017-02-01 02:38:39 +0000396
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000397 if (FunctionGuardArray)
398 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
399 SanCovGuardsSectionName);
400 if (Function8bitCounterArray)
401 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
402 SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000403 if (Ctor && Options.PCTable) {
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000404 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, Int8PtrTy);
405 Function *InitFunction = declareSanitizerInitFunction(
406 M, SanCovPCsInitName, {Int8PtrTy, Int8PtrTy});
407 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
408 IRBCtor.CreateCall(InitFunction,
409 {IRB.CreatePointerCast(SecStartEnd.first, Int8PtrTy),
410 IRB.CreatePointerCast(SecStartEnd.second, Int8PtrTy)});
411 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000412 return true;
413}
414
Mike Aizatsky9987f432016-03-23 23:15:03 +0000415// True if block has successors and it dominates all of them.
416static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
417 if (succ_begin(BB) == succ_end(BB))
418 return false;
419
420 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
421 if (!DT->dominates(BB, SUCC))
422 return false;
423 }
424
425 return true;
426}
427
George Karpenkov018472c2017-05-24 00:29:12 +0000428// True if block has predecessors and it postdominates all of them.
429static bool isFullPostDominator(const BasicBlock *BB,
430 const PostDominatorTree *PDT) {
431 if (pred_begin(BB) == pred_end(BB))
432 return false;
433
434 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
435 if (!PDT->dominates(BB, PRED))
436 return false;
437 }
438
439 return true;
440}
441
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000442static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
443 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000444 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000445 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000446 // Don't insert coverage for unreachable blocks: we will never call
447 // __sanitizer_cov() for them, so counting them in
448 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
449 // percentage. Also, unreachable instructions frequently have no debug
450 // locations.
451 if (isa<UnreachableInst>(BB->getTerminator()))
452 return false;
453
Reid Kleckner392f0622017-03-23 23:30:41 +0000454 // Don't insert coverage into blocks without a valid insertion point
455 // (catchswitch blocks).
456 if (BB->getFirstInsertionPt() == BB->end())
457 return false;
458
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000459 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000460 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000461
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000462 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
463 &F.getEntryBlock() != BB)
464 return false;
465
George Karpenkova1c53272017-05-25 01:41:46 +0000466 // Do not instrument full dominators, or full post-dominators with multiple
467 // predecessors.
468 return !isFullDominator(BB, DT)
469 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000470}
471
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000472bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000473 if (F.empty())
474 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000475 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000476 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000477 if (F.getName().startswith("__sanitizer_"))
478 return false; // Don't instrument __sanitizer_* callbacks.
Kostya Serebryanybfc83fa2017-07-31 20:00:22 +0000479 // Don't touch available_externally functions, their actual body is elewhere.
480 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
481 return false;
Reid Klecknerec803542016-11-11 19:18:45 +0000482 // Don't instrument MSVC CRT configuration helpers. They may run before normal
483 // initialization.
484 if (F.getName() == "__local_stdio_printf_options" ||
485 F.getName() == "__local_stdio_scanf_options")
486 return false;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000487 // Avoid infinite recursion by not instrumenting stack depth TLS wrapper
488 if (F.getName() == SanCovLowestStackTLSWrapperName)
489 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000490 // Don't instrument functions using SEH for now. Splitting basic blocks like
491 // we do for coverage breaks WinEHPrepare.
492 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
493 if (F.hasPersonalityFn() &&
494 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
495 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000496 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000497 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000498 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000499 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000500 SmallVector<Instruction *, 8> CmpTraceTargets;
501 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000502 SmallVector<BinaryOperator *, 8> DivTraceTargets;
503 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000504
Mike Aizatsky602f7922016-03-21 23:08:16 +0000505 const DominatorTree *DT =
506 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000507 const PostDominatorTree *PDT =
508 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Mike Aizatsky602f7922016-03-21 23:08:16 +0000509
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000510 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000511 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000512 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000513 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000514 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000515 CallSite CS(&Inst);
516 if (CS && !CS.getCalledFunction())
517 IndirCalls.push_back(&Inst);
518 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000519 if (Options.TraceCmp) {
520 if (isa<ICmpInst>(&Inst))
521 CmpTraceTargets.push_back(&Inst);
522 if (isa<SwitchInst>(&Inst))
523 SwitchTraceTargets.push_back(&Inst);
524 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000525 if (Options.TraceDiv)
526 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
527 if (BO->getOpcode() == Instruction::SDiv ||
528 BO->getOpcode() == Instruction::UDiv)
529 DivTraceTargets.push_back(BO);
530 if (Options.TraceGep)
531 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
532 GepTraceTargets.push_back(GEP);
533 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000534 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000535
536 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000537 InjectCoverageForIndirectCalls(F, IndirCalls);
538 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000539 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000540 InjectTraceForDiv(F, DivTraceTargets);
541 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000542 return true;
543}
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000544
545GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
546 size_t NumElements, Function &F, Type *Ty, const char *Section) {
547 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
548 auto Array = new GlobalVariable(
549 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
550 Constant::getNullValue(ArrayTy), "__sancov_gen_");
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000551 if (auto Comdat = F.getComdat())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000552 Array->setComdat(Comdat);
553 Array->setSection(getSectionName(Section));
Kostya Serebryanybb6f0792017-07-31 19:49:45 +0000554 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
555 : Ty->getPrimitiveSizeInBits() / 8);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000556 return Array;
557}
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000558
559void SanitizerCoverageModule::CreatePCArray(Function &F,
560 ArrayRef<BasicBlock *> AllBlocks) {
561 size_t N = AllBlocks.size();
562 assert(N);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000563 SmallVector<Constant *, 16> PCs;
564 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
Kostya Serebryanya1f12ba2017-08-01 00:44:05 +0000565 for (size_t i = 0; i < N; i++)
566 if (&F.getEntryBlock() == AllBlocks[i])
567 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, Int8PtrTy));
568 else
569 PCs.push_back(BlockAddress::get(AllBlocks[i]));
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000570 FunctionPCsArray =
571 CreateFunctionLocalArrayInSection(N, F, Int8PtrTy, SanCovPCsSectionName);
572 FunctionPCsArray->setInitializer(
573 ConstantArray::get(ArrayType::get(Int8PtrTy, N), PCs));
574 FunctionPCsArray->setConstant(true);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000575}
576
577void SanitizerCoverageModule::CreateFunctionLocalArrays(
578 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000579 if (Options.TracePCGuard)
580 FunctionGuardArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000581 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000582 if (Options.Inline8bitCounters)
583 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000584 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000585 if (Options.PCTable)
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000586 CreatePCArray(F, AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000587}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000588
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000589bool SanitizerCoverageModule::InjectCoverage(Function &F,
590 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000591 if (AllBlocks.empty()) return false;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000592 CreateFunctionLocalArrays(F, AllBlocks);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000593 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
594 InjectCoverageAtBlock(F, *AllBlocks[i], i);
595 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000596}
597
598// On every indirect call we call a run-time function
599// __sanitizer_cov_indir_call* with two parameters:
600// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000601// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000602// The cache is used to speed up recording the caller-callee pairs.
603// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000604// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000605void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
606 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000607 if (IndirCalls.empty())
608 return;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000609 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000610 for (auto I : IndirCalls) {
611 IRBuilder<> IRB(I);
612 CallSite CS(I);
613 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000614 if (isa<InlineAsm>(Callee))
615 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000616 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000617 }
618}
619
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000620// For every switch statement we insert a call:
621// __sanitizer_cov_trace_switch(CondValue,
622// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
623
624void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000625 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000626 for (auto I : SwitchTraceTargets) {
627 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
628 IRBuilder<> IRB(I);
629 SmallVector<Constant *, 16> Initializers;
630 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000631 if (Cond->getType()->getScalarSizeInBits() >
632 Int64Ty->getScalarSizeInBits())
633 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000634 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
635 Initializers.push_back(
636 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
637 if (Cond->getType()->getScalarSizeInBits() <
638 Int64Ty->getScalarSizeInBits())
639 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000640 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000641 Constant *C = It.getCaseValue();
642 if (C->getType()->getScalarSizeInBits() <
643 Int64Ty->getScalarSizeInBits())
644 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
645 Initializers.push_back(C);
646 }
Kostya Serebryanyf24e52c2016-12-27 21:20:06 +0000647 std::sort(Initializers.begin() + 2, Initializers.end(),
648 [](const Constant *A, const Constant *B) {
649 return cast<ConstantInt>(A)->getLimitedValue() <
650 cast<ConstantInt>(B)->getLimitedValue();
651 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000652 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
653 GlobalVariable *GV = new GlobalVariable(
654 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
655 ConstantArray::get(ArrayOfInt64Ty, Initializers),
656 "__sancov_gen_cov_switch_values");
657 IRB.CreateCall(SanCovTraceSwitchFunction,
658 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
659 }
660 }
661}
662
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000663void SanitizerCoverageModule::InjectTraceForDiv(
664 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
665 for (auto BO : DivTraceTargets) {
666 IRBuilder<> IRB(BO);
667 Value *A1 = BO->getOperand(1);
668 if (isa<ConstantInt>(A1)) continue;
669 if (!A1->getType()->isIntegerTy())
670 continue;
671 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
672 int CallbackIdx = TypeSize == 32 ? 0 :
673 TypeSize == 64 ? 1 : -1;
674 if (CallbackIdx < 0) continue;
675 auto Ty = Type::getIntNTy(*C, TypeSize);
676 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
677 {IRB.CreateIntCast(A1, Ty, true)});
678 }
679}
680
681void SanitizerCoverageModule::InjectTraceForGep(
682 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
683 for (auto GEP : GepTraceTargets) {
684 IRBuilder<> IRB(GEP);
685 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000686 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000687 IRB.CreateCall(SanCovTraceGepFunction,
688 {IRB.CreateIntCast(*I, IntptrTy, true)});
689 }
690}
691
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000692void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000693 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000694 for (auto I : CmpTraceTargets) {
695 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
696 IRBuilder<> IRB(ICMP);
697 Value *A0 = ICMP->getOperand(0);
698 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000699 if (!A0->getType()->isIntegerTy())
700 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000701 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000702 int CallbackIdx = TypeSize == 8 ? 0 :
703 TypeSize == 16 ? 1 :
704 TypeSize == 32 ? 2 :
705 TypeSize == 64 ? 3 : -1;
706 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000707 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Alexander Potapenko52410812017-08-10 15:00:13 +0000708 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
709 bool FirstIsConst = isa<ConstantInt>(A0);
710 bool SecondIsConst = isa<ConstantInt>(A1);
711 // If both are const, then we don't need such a comparison.
712 if (FirstIsConst && SecondIsConst) continue;
713 // If only one is const, then make it the first callback argument.
714 if (FirstIsConst || SecondIsConst) {
715 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
716 if (SecondIsConst)
717 std::swap(A0, A1);
718 }
719
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000720 auto Ty = Type::getIntNTy(*C, TypeSize);
Alexander Potapenko52410812017-08-10 15:00:13 +0000721 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
722 IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000723 }
724 }
725}
726
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000727void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000728 size_t Idx) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000729 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000730 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000731 DebugLoc EntryLoc;
732 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000733 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000734 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000735 // Keep static allocas and llvm.localescape calls in the entry block. Even
736 // if we aren't splitting the block, it's nice for allocas to be before
737 // calls.
738 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000739 } else {
740 EntryLoc = IP->getDebugLoc();
741 }
742
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000743 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000744 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000745 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000746 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
747 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000748 }
749 if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000750 auto GuardPtr = IRB.CreateIntToPtr(
751 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
752 ConstantInt::get(IntptrTy, Idx * 4)),
753 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000754 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
755 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000756 }
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000757 if (Options.Inline8bitCounters) {
758 auto CounterPtr = IRB.CreateGEP(
759 Function8bitCounterArray,
760 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
761 auto Load = IRB.CreateLoad(CounterPtr);
762 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
763 auto Store = IRB.CreateStore(Inc, CounterPtr);
764 SetNoSanitizeMetadata(Load);
765 SetNoSanitizeMetadata(Store);
766 }
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000767 if (Options.StackDepth && IsEntryBB) {
768 // Check stack depth. If it's the deepest so far, record it.
769 Function *GetFrameAddr =
770 Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
771 auto FrameAddrPtr =
772 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
773 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
774 auto LowestStackPtr = IRB.CreateCall(SanCovLowestStackTLSWrapper);
775 auto LowestStack = IRB.CreateLoad(LowestStackPtr);
776 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
777 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
778 IRBuilder<> ThenIRB(ThenTerm);
779 ThenIRB.CreateStore(FrameAddrInt, LowestStackPtr);
780 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000781}
782
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000783std::string
784SanitizerCoverageModule::getSectionName(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000785 if (TargetTriple.getObjectFormat() == Triple::COFF)
786 return ".SCOV$M";
787 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000788 return "__DATA,__" + Section;
789 return "__" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000790}
791
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000792std::string
793SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000794 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000795 return "\1section$start$__DATA$__" + Section;
796 return "__start___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000797}
798
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000799std::string
800SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000801 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000802 return "\1section$end$__DATA$__" + Section;
803 return "__stop___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000804}
805
806
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000807char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000808INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000809 "SanitizerCoverage: TODO."
810 "ModulePass",
811 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000812INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000813INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000814INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000815 "SanitizerCoverage: TODO."
816 "ModulePass",
817 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000818ModulePass *llvm::createSanitizerCoverageModulePass(
819 const SanitizerCoverageOptions &Options) {
820 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000821}