blob: 2a055920c3eea6a262a80be57101d31400db1fea [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 Morehouse034126e2017-08-30 22:49:31 +000028#include "llvm/IR/IntrinsicInst.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000029#include "llvm/IR/Intrinsics.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000030#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000037#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000038#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";
Justin Bognerbe757de2017-08-28 23:38:12 +000052static const char *const SanCovTraceConstCmp1 =
Alexander Potapenko52410812017-08-10 15:00:13 +000053 "__sanitizer_cov_trace_const_cmp1";
Justin Bognerbe757de2017-08-28 23:38:12 +000054static const char *const SanCovTraceConstCmp2 =
Alexander Potapenko52410812017-08-10 15:00:13 +000055 "__sanitizer_cov_trace_const_cmp2";
Justin Bognerbe757de2017-08-28 23:38:12 +000056static const char *const SanCovTraceConstCmp4 =
Alexander Potapenko52410812017-08-10 15:00:13 +000057 "__sanitizer_cov_trace_const_cmp4";
Justin Bognerbe757de2017-08-28 23:38:12 +000058static const char *const SanCovTraceConstCmp8 =
Alexander Potapenko52410812017-08-10 15:00:13 +000059 "__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";
Matt Morehouse5c7fc762017-08-18 18:43:30 +000080
Mike Aizatsky759aca02016-03-18 23:29:29 +000081static cl::opt<int> ClCoverageLevel(
82 "sanitizer-coverage-level",
83 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +000084 "3: all blocks and critical edges"),
Mike Aizatsky759aca02016-03-18 23:29:29 +000085 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000086
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000087static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
88 cl::desc("Experimental pc tracing"), cl::Hidden,
89 cl::init(false));
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000090
Kostya Serebryanyda718e52016-09-14 01:39:35 +000091static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
92 cl::desc("pc tracing with a guard"),
93 cl::Hidden, cl::init(false));
94
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000095// If true, we create a global variable that contains PCs of all instrumented
96// BBs, put this global into a named section, and pass this section's bounds
97// to __sanitizer_cov_pcs_init.
98// This way the coverage instrumentation does not need to acquire the PCs
99// at run-time. Works with trace-pc-guard and inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000100static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000101 cl::desc("create a static PC table"),
102 cl::Hidden, cl::init(false));
103
104static cl::opt<bool>
105 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
106 cl::desc("increments 8-bit counter for every edge"),
107 cl::Hidden, cl::init(false));
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000108
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000109static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000110 ClCMPTracing("sanitizer-coverage-trace-compares",
111 cl::desc("Tracing of CMP and similar instructions"),
112 cl::Hidden, cl::init(false));
113
114static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
115 cl::desc("Tracing of DIV instructions"),
116 cl::Hidden, cl::init(false));
117
118static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
119 cl::desc("Tracing of GEP instructions"),
120 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000121
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000122static cl::opt<bool>
123 ClPruneBlocks("sanitizer-coverage-prune-blocks",
124 cl::desc("Reduce the number of instrumented blocks"),
125 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000126
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000127static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
128 cl::desc("max stack depth tracing"),
129 cl::Hidden, cl::init(false));
130
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000131namespace {
132
Alexey Samsonov3514f272015-05-07 01:00:31 +0000133SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
134 SanitizerCoverageOptions Res;
135 switch (LegacyCoverageLevel) {
136 case 0:
137 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
138 break;
139 case 1:
140 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
141 break;
142 case 2:
143 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
144 break;
145 case 3:
146 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
147 break;
148 case 4:
149 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
150 Res.IndirectCalls = true;
151 break;
152 }
153 return Res;
154}
155
156SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
157 // Sets CoverageType and IndirectCalls.
158 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
159 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
160 Options.IndirectCalls |= CLOpts.IndirectCalls;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000161 Options.TraceCmp |= ClCMPTracing;
162 Options.TraceDiv |= ClDIVTracing;
163 Options.TraceGep |= ClGEPTracing;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000164 Options.TracePC |= ClTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000165 Options.TracePCGuard |= ClTracePCGuard;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000166 Options.Inline8bitCounters |= ClInline8bitCounters;
Kostya Serebryany063b6522017-07-28 00:09:29 +0000167 Options.PCTable |= ClCreatePCTable;
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000168 Options.NoPrune |= !ClPruneBlocks;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000169 Options.StackDepth |= ClStackDepth;
170 if (!Options.TracePCGuard && !Options.TracePC &&
171 !Options.Inline8bitCounters && !Options.StackDepth)
172 Options.TracePCGuard = true; // TracePCGuard is default.
Alexey Samsonov3514f272015-05-07 01:00:31 +0000173 return Options;
174}
175
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000176class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000177public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000178 SanitizerCoverageModule(
179 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000180 : ModulePass(ID), Options(OverrideFromCL(Options)) {
181 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
182 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000183 bool runOnModule(Module &M) override;
184 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000185 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000186 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000187
Chandler Carruth30061152016-03-18 22:43:42 +0000188 void getAnalysisUsage(AnalysisUsage &AU) const override {
189 AU.addRequired<DominatorTreeWrapperPass>();
George Karpenkov018472c2017-05-24 00:29:12 +0000190 AU.addRequired<PostDominatorTreeWrapperPass>();
Chandler Carruth30061152016-03-18 22:43:42 +0000191 }
192
193private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000194 void InjectCoverageForIndirectCalls(Function &F,
195 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000196 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000197 void InjectTraceForDiv(Function &F,
198 ArrayRef<BinaryOperator *> DivTraceTargets);
199 void InjectTraceForGep(Function &F,
200 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000201 void InjectTraceForSwitch(Function &F,
202 ArrayRef<Instruction *> SwitchTraceTargets);
Matt Morehouse034126e2017-08-30 22:49:31 +0000203 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
204 bool IsLeafFunc = true);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000205 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
206 Function &F, Type *Ty,
207 const char *Section);
Justin Bogner873a0742017-08-28 23:46:11 +0000208 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000209 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Matt Morehouse034126e2017-08-30 22:49:31 +0000210 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
211 bool IsLeafFunc = true);
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
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000222 Comdat *GetOrCreateFunctionComdat(Function &F);
223
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000224 std::string getSectionName(const std::string &Section) const;
225 std::string getSectionStart(const std::string &Section) const;
226 std::string getSectionEnd(const std::string &Section) const;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000227 Function *SanCovTracePCIndir;
Kostya Serebryanybe87d482017-04-19 21:48:09 +0000228 Function *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000229 Function *SanCovTraceCmpFunction[4];
Alexander Potapenko52410812017-08-10 15:00:13 +0000230 Function *SanCovTraceConstCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000231 Function *SanCovTraceDivFunction[2];
232 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000233 Function *SanCovTraceSwitchFunction;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000234 GlobalVariable *SanCovLowestStack;
Kostya Serebryany73762942014-12-16 21:24:15 +0000235 InlineAsm *EmptyAsm;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000236 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
Alexander Potapenko52410812017-08-10 15:00:13 +0000237 *Int16Ty, *Int8Ty, *Int8PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000238 Module *CurModule;
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000239 std::string CurModuleUniqueId;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000240 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000241 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000242 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000243
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000244 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000245 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000246 GlobalVariable *FunctionPCsArray; // for pc-table.
Kostya Serebryany4192b962017-09-09 05:30:13 +0000247 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
Matt Morehouse0ea9a902018-06-15 20:12:58 +0000248 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000249
Alexey Samsonov3514f272015-05-07 01:00:31 +0000250 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000251};
252
Mike Aizatsky759aca02016-03-18 23:29:29 +0000253} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000254
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000255std::pair<GlobalVariable *, GlobalVariable *>
256SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
257 Type *Ty) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000258 GlobalVariable *SecStart =
259 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
260 getSectionStart(Section));
261 SecStart->setVisibility(GlobalValue::HiddenVisibility);
262 GlobalVariable *SecEnd =
263 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
264 nullptr, getSectionEnd(Section));
265 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
266
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000267 return std::make_pair(SecStart, SecEnd);
268}
269
270
271Function *SanitizerCoverageModule::CreateInitCallsForSections(
272 Module &M, const char *InitFunctionName, Type *Ty,
273 const char *Section) {
274 IRBuilder<> IRB(M.getContext());
275 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
276 auto SecStart = SecStartEnd.first;
277 auto SecEnd = SecStartEnd.second;
278 Function *CtorFunc;
Matt Morehouse7e042bb2018-08-30 15:54:44 +0000279 Value *SecStartPtr = nullptr;
280 // Account for the fact that on windows-msvc __start_* symbols actually
281 // point to a uint64_t before the start of the array.
282 if (TargetTriple.getObjectFormat() == Triple::COFF) {
283 auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
284 auto GEP = IRB.CreateGEP(SecStartI8Ptr,
285 ConstantInt::get(IntptrTy, sizeof(uint64_t)));
286 SecStartPtr = IRB.CreatePointerCast(GEP, Ty);
287 } else {
288 SecStartPtr = IRB.CreatePointerCast(SecStart, Ty);
289 }
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000290 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
291 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
Matt Morehouse7e042bb2018-08-30 15:54:44 +0000292 {SecStartPtr, IRB.CreatePointerCast(SecEnd, Ty)});
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000293
294 if (TargetTriple.supportsCOMDAT()) {
295 // Use comdat to dedup CtorFunc.
296 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
297 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
298 } else {
299 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
300 }
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000301 return CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000302}
303
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000304bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000305 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
306 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000307 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000308 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000309 CurModule = &M;
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000310 CurModuleUniqueId = getUniqueModuleId(CurModule);
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000311 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000312 FunctionGuardArray = nullptr;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000313 Function8bitCounterArray = nullptr;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000314 FunctionPCsArray = nullptr;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000315 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000316 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000317 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000318 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000319 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000320 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000321 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000322 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000323 Int32Ty = IRB.getInt32Ty();
Alexander Potapenko52410812017-08-10 15:00:13 +0000324 Int16Ty = IRB.getInt16Ty();
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000325 Int8Ty = IRB.getInt8Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000326
Mike Aizatsky759aca02016-03-18 23:29:29 +0000327 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000328 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000329 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000330 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000331 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000332 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
333 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000334 IRB.getInt16Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000335 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
336 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000337 IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000338 SanCovTraceCmpFunction[3] =
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000339 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000340 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000341
Alexander Potapenko52410812017-08-10 15:00:13 +0000342 SanCovTraceConstCmpFunction[0] =
343 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
344 SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
345 SanCovTraceConstCmpFunction[1] =
346 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
347 SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
348 SanCovTraceConstCmpFunction[2] =
349 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
350 SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
351 SanCovTraceConstCmpFunction[3] =
352 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
353 SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
354
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000355 SanCovTraceDivFunction[0] =
356 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000357 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000358 SanCovTraceDivFunction[1] =
359 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000360 SanCovTraceDiv8, VoidTy, Int64Ty));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000361 SanCovTraceGepFunction =
362 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000363 SanCovTraceGep, VoidTy, IntptrTy));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000364 SanCovTraceSwitchFunction =
365 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000366 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000367
368 Constant *SanCovLowestStackConstant =
369 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000370 SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
371 SanCovLowestStack->setThreadLocalMode(
372 GlobalValue::ThreadLocalMode::InitialExecTLSModel);
373 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
374 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000375
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000376 // Make sure smaller parameters are zero-extended to i64 as required by the
377 // x86_64 ABI.
378 if (TargetTriple.getArch() == Triple::x86_64) {
379 for (int i = 0; i < 3; i++) {
380 SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
381 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko52410812017-08-10 15:00:13 +0000382 SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
383 SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000384 }
385 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
386 }
387
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000388
Kostya Serebryany73762942014-12-16 21:24:15 +0000389 // We insert an empty inline asm after cov callbacks to avoid callback merge.
390 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
391 StringRef(""), StringRef(""),
392 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000393
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000394 SanCovTracePC = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000395 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000396 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000397 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000398
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000399 for (auto &F : M)
400 runOnFunction(F);
401
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000402 Function *Ctor = nullptr;
Justin Bogner41e632b2017-02-01 02:38:39 +0000403
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000404 if (FunctionGuardArray)
405 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
406 SanCovGuardsSectionName);
407 if (Function8bitCounterArray)
408 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
409 SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000410 if (Ctor && Options.PCTable) {
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000411 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000412 Function *InitFunction = declareSanitizerInitFunction(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000413 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000414 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
Matt Morehouse7e042bb2018-08-30 15:54:44 +0000415 Value *SecStartPtr = nullptr;
416 // Account for the fact that on windows-msvc __start_pc_table actually
417 // points to a uint64_t before the start of the PC table.
418 if (TargetTriple.getObjectFormat() == Triple::COFF) {
419 auto SecStartI8Ptr = IRB.CreatePointerCast(SecStartEnd.first, Int8PtrTy);
420 auto GEP = IRB.CreateGEP(SecStartI8Ptr,
421 ConstantInt::get(IntptrTy, sizeof(uint64_t)));
422 SecStartPtr = IRB.CreatePointerCast(GEP, IntptrPtrTy);
423 } else {
424 SecStartPtr = IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy);
425 }
426 IRBCtor.CreateCall(
427 InitFunction,
428 {SecStartPtr, IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000429 }
Kostya Serebryany4192b962017-09-09 05:30:13 +0000430 // We don't reference these arrays directly in any of our runtime functions,
431 // so we need to prevent them from being dead stripped.
432 if (TargetTriple.isOSBinFormatMachO())
433 appendToUsed(M, GlobalsToAppendToUsed);
Matt Morehouse0ea9a902018-06-15 20:12:58 +0000434 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000435 return true;
436}
437
Mike Aizatsky9987f432016-03-23 23:15:03 +0000438// True if block has successors and it dominates all of them.
439static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
440 if (succ_begin(BB) == succ_end(BB))
441 return false;
442
443 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
444 if (!DT->dominates(BB, SUCC))
445 return false;
446 }
447
448 return true;
449}
450
George Karpenkov018472c2017-05-24 00:29:12 +0000451// True if block has predecessors and it postdominates all of them.
452static bool isFullPostDominator(const BasicBlock *BB,
453 const PostDominatorTree *PDT) {
454 if (pred_begin(BB) == pred_end(BB))
455 return false;
456
457 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
458 if (!PDT->dominates(BB, PRED))
459 return false;
460 }
461
462 return true;
463}
464
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000465static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
466 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000467 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000468 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000469 // Don't insert coverage for unreachable blocks: we will never call
470 // __sanitizer_cov() for them, so counting them in
471 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
472 // percentage. Also, unreachable instructions frequently have no debug
473 // locations.
474 if (isa<UnreachableInst>(BB->getTerminator()))
475 return false;
476
Reid Kleckner392f0622017-03-23 23:30:41 +0000477 // Don't insert coverage into blocks without a valid insertion point
478 // (catchswitch blocks).
479 if (BB->getFirstInsertionPt() == BB->end())
480 return false;
481
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000482 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000483 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000484
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000485 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
486 &F.getEntryBlock() != BB)
487 return false;
488
George Karpenkova1c53272017-05-25 01:41:46 +0000489 // Do not instrument full dominators, or full post-dominators with multiple
490 // predecessors.
491 return !isFullDominator(BB, DT)
492 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000493}
494
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000495bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000496 if (F.empty())
497 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000498 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000499 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000500 if (F.getName().startswith("__sanitizer_"))
501 return false; // Don't instrument __sanitizer_* callbacks.
Kostya Serebryanybfc83fa2017-07-31 20:00:22 +0000502 // Don't touch available_externally functions, their actual body is elewhere.
503 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
504 return false;
Reid Klecknerec803542016-11-11 19:18:45 +0000505 // Don't instrument MSVC CRT configuration helpers. They may run before normal
506 // initialization.
507 if (F.getName() == "__local_stdio_printf_options" ||
508 F.getName() == "__local_stdio_scanf_options")
509 return false;
Kostya Serebryanya2759322018-05-11 01:09:39 +0000510 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
511 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000512 // Don't instrument functions using SEH for now. Splitting basic blocks like
513 // we do for coverage breaks WinEHPrepare.
514 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
515 if (F.hasPersonalityFn() &&
516 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
517 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000518 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000519 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000520 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000521 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000522 SmallVector<Instruction *, 8> CmpTraceTargets;
523 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000524 SmallVector<BinaryOperator *, 8> DivTraceTargets;
525 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000526
Mike Aizatsky602f7922016-03-21 23:08:16 +0000527 const DominatorTree *DT =
528 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000529 const PostDominatorTree *PDT =
530 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Matt Morehouse034126e2017-08-30 22:49:31 +0000531 bool IsLeafFunc = true;
Mike Aizatsky602f7922016-03-21 23:08:16 +0000532
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000533 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000534 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000535 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000536 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000537 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000538 CallSite CS(&Inst);
539 if (CS && !CS.getCalledFunction())
540 IndirCalls.push_back(&Inst);
541 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000542 if (Options.TraceCmp) {
543 if (isa<ICmpInst>(&Inst))
544 CmpTraceTargets.push_back(&Inst);
545 if (isa<SwitchInst>(&Inst))
546 SwitchTraceTargets.push_back(&Inst);
547 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000548 if (Options.TraceDiv)
549 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
550 if (BO->getOpcode() == Instruction::SDiv ||
551 BO->getOpcode() == Instruction::UDiv)
552 DivTraceTargets.push_back(BO);
553 if (Options.TraceGep)
554 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
555 GepTraceTargets.push_back(GEP);
Matt Morehouse034126e2017-08-30 22:49:31 +0000556 if (Options.StackDepth)
557 if (isa<InvokeInst>(Inst) ||
558 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
559 IsLeafFunc = false;
560 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000561 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000562
Matt Morehouse034126e2017-08-30 22:49:31 +0000563 InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000564 InjectCoverageForIndirectCalls(F, IndirCalls);
565 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000566 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000567 InjectTraceForDiv(F, DivTraceTargets);
568 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000569 return true;
570}
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000571
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000572Comdat *SanitizerCoverageModule::GetOrCreateFunctionComdat(Function &F) {
573 if (auto Comdat = F.getComdat()) return Comdat;
574 if (!TargetTriple.isOSBinFormatELF()) return nullptr;
575 assert(F.hasName());
576 std::string Name = F.getName();
577 if (F.hasLocalLinkage()) {
578 if (CurModuleUniqueId.empty()) return nullptr;
579 Name += CurModuleUniqueId;
580 }
581 auto Comdat = CurModule->getOrInsertComdat(Name);
582 F.setComdat(Comdat);
583 return Comdat;
584}
585
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000586GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
587 size_t NumElements, Function &F, Type *Ty, const char *Section) {
588 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
589 auto Array = new GlobalVariable(
590 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
591 Constant::getNullValue(ArrayTy), "__sancov_gen_");
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000592 if (auto Comdat = GetOrCreateFunctionComdat(F))
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000593 Array->setComdat(Comdat);
594 Array->setSection(getSectionName(Section));
Kostya Serebryanybb6f0792017-07-31 19:49:45 +0000595 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
596 : Ty->getPrimitiveSizeInBits() / 8);
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000597 GlobalsToAppendToCompilerUsed.push_back(Array);
598 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
599 Array->addMetadata(LLVMContext::MD_associated, *MD);
600
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000601 return Array;
602}
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000603
Justin Bogner873a0742017-08-28 23:46:11 +0000604GlobalVariable *
605SanitizerCoverageModule::CreatePCArray(Function &F,
606 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000607 size_t N = AllBlocks.size();
608 assert(N);
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000609 SmallVector<Constant *, 32> PCs;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000610 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000611 for (size_t i = 0; i < N; i++) {
612 if (&F.getEntryBlock() == AllBlocks[i]) {
613 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
614 PCs.push_back((Constant *)IRB.CreateIntToPtr(
615 ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
616 } else {
617 PCs.push_back((Constant *)IRB.CreatePointerCast(
618 BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
619 PCs.push_back((Constant *)IRB.CreateIntToPtr(
620 ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
621 }
622 }
Justin Bogner873a0742017-08-28 23:46:11 +0000623 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
624 SanCovPCsSectionName);
625 PCArray->setInitializer(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000626 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
Justin Bogner873a0742017-08-28 23:46:11 +0000627 PCArray->setConstant(true);
Justin Bognerad96ff12017-08-25 01:24:54 +0000628
Justin Bogner873a0742017-08-28 23:46:11 +0000629 return PCArray;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000630}
631
632void SanitizerCoverageModule::CreateFunctionLocalArrays(
633 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
Justin Bognerf1a54a42017-08-29 00:11:05 +0000634 if (Options.TracePCGuard) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000635 FunctionGuardArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000636 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
Kostya Serebryany4192b962017-09-09 05:30:13 +0000637 GlobalsToAppendToUsed.push_back(FunctionGuardArray);
Justin Bognerf1a54a42017-08-29 00:11:05 +0000638 }
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000639 if (Options.Inline8bitCounters)
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000640 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000641 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000642 if (Options.PCTable)
Justin Bogner873a0742017-08-28 23:46:11 +0000643 FunctionPCsArray = CreatePCArray(F, AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000644}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000645
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000646bool SanitizerCoverageModule::InjectCoverage(Function &F,
Matt Morehouse034126e2017-08-30 22:49:31 +0000647 ArrayRef<BasicBlock *> AllBlocks,
648 bool IsLeafFunc) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000649 if (AllBlocks.empty()) return false;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000650 CreateFunctionLocalArrays(F, AllBlocks);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000651 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
Matt Morehouse034126e2017-08-30 22:49:31 +0000652 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000653 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000654}
655
656// On every indirect call we call a run-time function
657// __sanitizer_cov_indir_call* with two parameters:
658// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000659// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000660// The cache is used to speed up recording the caller-callee pairs.
661// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000662// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000663void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
664 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000665 if (IndirCalls.empty())
666 return;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000667 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000668 for (auto I : IndirCalls) {
669 IRBuilder<> IRB(I);
670 CallSite CS(I);
671 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000672 if (isa<InlineAsm>(Callee))
673 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000674 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000675 }
676}
677
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000678// For every switch statement we insert a call:
679// __sanitizer_cov_trace_switch(CondValue,
680// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
681
682void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000683 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000684 for (auto I : SwitchTraceTargets) {
685 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
686 IRBuilder<> IRB(I);
687 SmallVector<Constant *, 16> Initializers;
688 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000689 if (Cond->getType()->getScalarSizeInBits() >
690 Int64Ty->getScalarSizeInBits())
691 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000692 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
693 Initializers.push_back(
694 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
695 if (Cond->getType()->getScalarSizeInBits() <
696 Int64Ty->getScalarSizeInBits())
697 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000698 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000699 Constant *C = It.getCaseValue();
700 if (C->getType()->getScalarSizeInBits() <
701 Int64Ty->getScalarSizeInBits())
702 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
703 Initializers.push_back(C);
704 }
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000705 llvm::sort(Initializers.begin() + 2, Initializers.end(),
706 [](const Constant *A, const Constant *B) {
707 return cast<ConstantInt>(A)->getLimitedValue() <
708 cast<ConstantInt>(B)->getLimitedValue();
709 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000710 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
711 GlobalVariable *GV = new GlobalVariable(
712 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
713 ConstantArray::get(ArrayOfInt64Ty, Initializers),
714 "__sancov_gen_cov_switch_values");
715 IRB.CreateCall(SanCovTraceSwitchFunction,
716 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
717 }
718 }
719}
720
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000721void SanitizerCoverageModule::InjectTraceForDiv(
722 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
723 for (auto BO : DivTraceTargets) {
724 IRBuilder<> IRB(BO);
725 Value *A1 = BO->getOperand(1);
726 if (isa<ConstantInt>(A1)) continue;
727 if (!A1->getType()->isIntegerTy())
728 continue;
729 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
730 int CallbackIdx = TypeSize == 32 ? 0 :
731 TypeSize == 64 ? 1 : -1;
732 if (CallbackIdx < 0) continue;
733 auto Ty = Type::getIntNTy(*C, TypeSize);
734 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
735 {IRB.CreateIntCast(A1, Ty, true)});
736 }
737}
738
739void SanitizerCoverageModule::InjectTraceForGep(
740 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
741 for (auto GEP : GepTraceTargets) {
742 IRBuilder<> IRB(GEP);
743 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000744 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000745 IRB.CreateCall(SanCovTraceGepFunction,
746 {IRB.CreateIntCast(*I, IntptrTy, true)});
747 }
748}
749
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000750void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000751 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000752 for (auto I : CmpTraceTargets) {
753 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
754 IRBuilder<> IRB(ICMP);
755 Value *A0 = ICMP->getOperand(0);
756 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000757 if (!A0->getType()->isIntegerTy())
758 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000759 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000760 int CallbackIdx = TypeSize == 8 ? 0 :
761 TypeSize == 16 ? 1 :
762 TypeSize == 32 ? 2 :
763 TypeSize == 64 ? 3 : -1;
764 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000765 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Alexander Potapenko52410812017-08-10 15:00:13 +0000766 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
767 bool FirstIsConst = isa<ConstantInt>(A0);
768 bool SecondIsConst = isa<ConstantInt>(A1);
769 // If both are const, then we don't need such a comparison.
770 if (FirstIsConst && SecondIsConst) continue;
771 // If only one is const, then make it the first callback argument.
772 if (FirstIsConst || SecondIsConst) {
773 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
Justin Bognerbe757de2017-08-28 23:38:12 +0000774 if (SecondIsConst)
Alexander Potapenko52410812017-08-10 15:00:13 +0000775 std::swap(A0, A1);
776 }
777
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000778 auto Ty = Type::getIntNTy(*C, TypeSize);
Justin Bognerbe757de2017-08-28 23:38:12 +0000779 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
Alexander Potapenko52410812017-08-10 15:00:13 +0000780 IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000781 }
782 }
783}
784
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000785void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Matt Morehouse034126e2017-08-30 22:49:31 +0000786 size_t Idx,
787 bool IsLeafFunc) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000788 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000789 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000790 DebugLoc EntryLoc;
791 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000792 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000793 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000794 // Keep static allocas and llvm.localescape calls in the entry block. Even
795 // if we aren't splitting the block, it's nice for allocas to be before
796 // calls.
797 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000798 } else {
799 EntryLoc = IP->getDebugLoc();
800 }
801
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000802 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000803 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000804 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000805 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
806 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000807 }
808 if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000809 auto GuardPtr = IRB.CreateIntToPtr(
810 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
811 ConstantInt::get(IntptrTy, Idx * 4)),
812 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000813 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
814 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000815 }
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000816 if (Options.Inline8bitCounters) {
817 auto CounterPtr = IRB.CreateGEP(
818 Function8bitCounterArray,
819 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
820 auto Load = IRB.CreateLoad(CounterPtr);
821 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
822 auto Store = IRB.CreateStore(Inc, CounterPtr);
823 SetNoSanitizeMetadata(Load);
824 SetNoSanitizeMetadata(Store);
825 }
Matt Morehouse034126e2017-08-30 22:49:31 +0000826 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000827 // Check stack depth. If it's the deepest so far, record it.
828 Function *GetFrameAddr =
829 Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
830 auto FrameAddrPtr =
831 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
832 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000833 auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000834 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
835 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
836 IRBuilder<> ThenIRB(ThenTerm);
Matt Morehouse034126e2017-08-30 22:49:31 +0000837 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
838 SetNoSanitizeMetadata(LowestStack);
839 SetNoSanitizeMetadata(Store);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000840 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000841}
842
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000843std::string
844SanitizerCoverageModule::getSectionName(const std::string &Section) const {
Matt Morehouse7e042bb2018-08-30 15:54:44 +0000845 if (TargetTriple.getObjectFormat() == Triple::COFF) {
846 if (Section == SanCovCountersSectionName)
847 return ".SCOV$CM";
848 if (Section == SanCovPCsSectionName)
849 return ".SCOVP$M";
850 return ".SCOV$GM"; // For SanCovGuardsSectionName.
851 }
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000852 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000853 return "__DATA,__" + Section;
854 return "__" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000855}
856
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000857std::string
858SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000859 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000860 return "\1section$start$__DATA$__" + Section;
861 return "__start___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000862}
863
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000864std::string
865SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000866 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000867 return "\1section$end$__DATA$__" + Section;
868 return "__stop___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000869}
870
871
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000872char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000873INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000874 "SanitizerCoverage: TODO."
875 "ModulePass",
876 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000877INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000878INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000879INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000880 "SanitizerCoverage: TODO."
881 "ModulePass",
882 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000883ModulePass *llvm::createSanitizerCoverageModulePass(
884 const SanitizerCoverageOptions &Options) {
885 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000886}