blob: f6ae0c2dd5f9fa93389620f6e7342008362c9bb8 [file] [log] [blame]
Kostya Serebryany29a18dc2014-11-11 22:14:37 +00001//===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Coverage instrumentation that works with AddressSanitizer
11// and potentially with other Sanitizers.
12//
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000013// We create a Guard variable with the same linkage
Alexey Samsonov3514f272015-05-07 01:00:31 +000014// as the function and inject this code into the entry block (SCK_Function)
15// or all blocks (SCK_BB):
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000016// if (Guard < 0) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +000017// __sanitizer_cov(&Guard);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000018// }
19// The accesses to Guard are atomic. The rest of the logic is
20// in __sanitizer_cov (it's fine to call it more than once).
21//
Alexey Samsonov3514f272015-05-07 01:00:31 +000022// With SCK_Edge we also split critical edges this effectively
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000023// instrumenting all edges.
24//
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000025// This coverage implementation provides very limited data:
26// it only tells if a given function (block) was ever executed. No counters.
27// But for many use cases this is what we need and the added slowdown small.
28//
29//===----------------------------------------------------------------------===//
30
31#include "llvm/Transforms/Instrumentation.h"
32#include "llvm/ADT/ArrayRef.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/IR/CallSite.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000038#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000039#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/MDBuilder.h"
41#include "llvm/IR/Module.h"
42#include "llvm/IR/Type.h"
43#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Support/raw_ostream.h"
46#include "llvm/Transforms/Scalar.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/ModuleUtils.h"
49
50using namespace llvm;
51
52#define DEBUG_TYPE "sancov"
53
54static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
55static const char *const kSanCovName = "__sanitizer_cov";
Kostya Serebryany77cc7292015-02-04 01:21:45 +000056static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000057static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000058static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
59static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000060static const char *const kSanCovTraceCmp = "__sanitizer_cov_trace_cmp";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000061static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
Evgeniy Stepanov3fdfc7b2015-01-27 15:01:22 +000062static const uint64_t kSanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000063
64static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
65 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
66 "3: all blocks and critical edges, "
67 "4: above plus indirect calls"),
68 cl::Hidden, cl::init(0));
69
Kostya Serebryany77cc7292015-02-04 01:21:45 +000070static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000071 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000072 cl::desc("Use a callback with a guard check inside it if there are"
73 " more than this number of blocks."),
Kostya Serebryany8fb05ac2015-03-10 01:11:53 +000074 cl::Hidden, cl::init(500));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000075
Kostya Serebryanycb45b122014-11-19 00:22:58 +000076static cl::opt<bool>
77 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
78 cl::desc("Experimental basic-block tracing: insert "
79 "callbacks at every basic block"),
80 cl::Hidden, cl::init(false));
81
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000082static cl::opt<bool>
83 ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares",
84 cl::desc("Experimental tracing of CMP and similar "
85 "instructions"),
86 cl::Hidden, cl::init(false));
87
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +000088// Experimental 8-bit counters used as an additional search heuristic during
89// coverage-guided fuzzing.
90// The counters are not thread-friendly:
91// - contention on these counters may cause significant slowdown;
92// - the counter updates are racy and the results may be inaccurate.
93// They are also inaccurate due to 8-bit integer overflow.
94static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
95 cl::desc("Experimental 8-bit counters"),
96 cl::Hidden, cl::init(false));
97
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000098namespace {
99
Alexey Samsonov3514f272015-05-07 01:00:31 +0000100SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
101 SanitizerCoverageOptions Res;
102 switch (LegacyCoverageLevel) {
103 case 0:
104 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
105 break;
106 case 1:
107 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
108 break;
109 case 2:
110 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
111 break;
112 case 3:
113 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
114 break;
115 case 4:
116 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
117 Res.IndirectCalls = true;
118 break;
119 }
120 return Res;
121}
122
123SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
124 // Sets CoverageType and IndirectCalls.
125 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
126 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
127 Options.IndirectCalls |= CLOpts.IndirectCalls;
128 Options.TraceBB |= ClExperimentalTracing;
129 Options.TraceCmp |= ClExperimentalCMPTracing;
130 Options.Use8bitCounters |= ClUse8bitCounters;
131 return Options;
132}
133
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000134class SanitizerCoverageModule : public ModulePass {
135 public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000136 SanitizerCoverageModule(
137 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
138 : ModulePass(ID), Options(OverrideFromCL(Options)) {}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000139 bool runOnModule(Module &M) override;
140 bool runOnFunction(Function &F);
141 static char ID; // Pass identification, replacement for typeid
142 const char *getPassName() const override {
143 return "SanitizerCoverageModule";
144 }
145
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000146 private:
147 void InjectCoverageForIndirectCalls(Function &F,
148 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000149 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
150 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000151 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000152 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000153 unsigned NumberOfInstrumentedBlocks() {
154 return SanCovFunction->getNumUses() + SanCovWithCheckFunction->getNumUses();
155 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000156 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000157 Function *SanCovWithCheckFunction;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000158 Function *SanCovIndirCallFunction;
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000159 Function *SanCovTraceEnter, *SanCovTraceBB;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000160 Function *SanCovTraceCmpFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000161 InlineAsm *EmptyAsm;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000162 Type *IntptrTy, *Int64Ty;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000163 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000164 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000165
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000166 GlobalVariable *GuardArray;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000167 GlobalVariable *EightBitCounterArray;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000168
Alexey Samsonov3514f272015-05-07 01:00:31 +0000169 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000170};
171
172} // namespace
173
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000174bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000175 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
176 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000177 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000178 DL = &M.getDataLayout();
179 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000180 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000181 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000182 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000183 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000184 Int64Ty = IRB.getInt64Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000185
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000186 SanCovFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000187 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000188 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000189 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000190 SanCovIndirCallFunction =
191 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
192 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
193 SanCovTraceCmpFunction =
194 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
195 kSanCovTraceCmp, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000196
Kostya Serebryany73762942014-12-16 21:24:15 +0000197 // We insert an empty inline asm after cov callbacks to avoid callback merge.
198 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
199 StringRef(""), StringRef(""),
200 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000201
Alexey Samsonov3514f272015-05-07 01:00:31 +0000202 if (Options.TraceBB) {
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000203 SanCovTraceEnter = checkSanitizerInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000204 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000205 SanCovTraceBB = checkSanitizerInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000206 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000207 }
208
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000209 // At this point we create a dummy array of guards because we don't
210 // know how many elements we will need.
211 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000212 Type *Int8Ty = IRB.getInt8Ty();
213
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000214 GuardArray =
215 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
216 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000217 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000218 EightBitCounterArray =
219 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
220 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000221
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000222 for (auto &F : M)
223 runOnFunction(F);
224
Kostya Serebryany48a40232015-03-10 01:58:27 +0000225 auto N = NumberOfInstrumentedBlocks();
226
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000227 // Now we know how many elements we need. Create an array of guards
228 // with one extra element at the beginning for the size.
Kostya Serebryany48a40232015-03-10 01:58:27 +0000229 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000230 GlobalVariable *RealGuardArray = new GlobalVariable(
231 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
232 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
233
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000234
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000235 // Replace the dummy array with the real one.
236 GuardArray->replaceAllUsesWith(
237 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
238 GuardArray->eraseFromParent();
239
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000240 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000241 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000242 // Make sure the array is 16-aligned.
243 static const int kCounterAlignment = 16;
244 Type *Int8ArrayNTy =
Kostya Serebryany48a40232015-03-10 01:58:27 +0000245 ArrayType::get(Int8Ty, RoundUpToAlignment(N, kCounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000246 RealEightBitCounterArray = new GlobalVariable(
247 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
248 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
249 RealEightBitCounterArray->setAlignment(kCounterAlignment);
250 EightBitCounterArray->replaceAllUsesWith(
251 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
252 EightBitCounterArray->eraseFromParent();
253 }
254
Kostya Serebryany88599462015-02-20 00:30:44 +0000255 // Create variable for module (compilation unit) name
256 Constant *ModNameStrConst =
257 ConstantDataArray::getString(M.getContext(), M.getName(), true);
258 GlobalVariable *ModuleName =
259 new GlobalVariable(M, ModNameStrConst->getType(), true,
260 GlobalValue::PrivateLinkage, ModNameStrConst);
261
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000262 Function *CtorFunc;
263 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
264 M, kSanCovModuleCtorName, kSanCovModuleInitName,
265 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
266 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
267 ConstantInt::get(IntptrTy, N),
268 Options.Use8bitCounters
269 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
270 : Constant::getNullValue(Int8PtrTy),
271 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
272
273 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
274
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000275 return true;
276}
277
278bool SanitizerCoverageModule::runOnFunction(Function &F) {
279 if (F.empty()) return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000280 if (F.getName().find(".module_ctor") != std::string::npos)
281 return false; // Should not instrument sanitizer init functions.
Alexey Samsonov3514f272015-05-07 01:00:31 +0000282 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000283 SplitAllCriticalEdges(F);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000284 SmallVector<Instruction*, 8> IndirCalls;
285 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000286 SmallVector<Instruction*, 8> CmpTraceTargets;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000287 for (auto &BB : F) {
288 AllBlocks.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000289 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000290 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000291 CallSite CS(&Inst);
292 if (CS && !CS.getCalledFunction())
293 IndirCalls.push_back(&Inst);
294 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000295 if (Options.TraceCmp && isa<ICmpInst>(&Inst))
296 CmpTraceTargets.push_back(&Inst);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000297 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000298 }
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000299 InjectCoverage(F, AllBlocks);
300 InjectCoverageForIndirectCalls(F, IndirCalls);
301 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000302 return true;
303}
304
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000305bool SanitizerCoverageModule::InjectCoverage(Function &F,
306 ArrayRef<BasicBlock *> AllBlocks) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000307 switch (Options.CoverageType) {
308 case SanitizerCoverageOptions::SCK_None:
309 return false;
310 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000311 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000312 return true;
313 default: {
314 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000315 for (auto BB : AllBlocks)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000316 InjectCoverageAtBlock(F, *BB, UseCalls);
317 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000318 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000319 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000320}
321
322// On every indirect call we call a run-time function
323// __sanitizer_cov_indir_call* with two parameters:
324// - callee address,
325// - global cache array that contains kCacheSize pointers (zero-initialized).
326// The cache is used to speed up recording the caller-callee pairs.
327// The address of the caller is passed implicitly via caller PC.
328// kCacheSize is encoded in the name of the run-time function.
329void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
330 Function &F, ArrayRef<Instruction *> IndirCalls) {
331 if (IndirCalls.empty()) return;
332 const int kCacheSize = 16;
333 const int kCacheAlignment = 64; // Align for better performance.
334 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
335 for (auto I : IndirCalls) {
336 IRBuilder<> IRB(I);
337 CallSite CS(I);
338 Value *Callee = CS.getCalledValue();
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000339 if (isa<InlineAsm>(Callee)) continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000340 GlobalVariable *CalleeCache = new GlobalVariable(
341 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
342 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
343 CalleeCache->setAlignment(kCacheAlignment);
David Blaikieff6409d2015-05-18 22:13:54 +0000344 IRB.CreateCall(SanCovIndirCallFunction,
345 {IRB.CreatePointerCast(Callee, IntptrTy),
346 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000347 }
348}
349
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000350void SanitizerCoverageModule::InjectTraceForCmp(
351 Function &F, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000352 for (auto I : CmpTraceTargets) {
353 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
354 IRBuilder<> IRB(ICMP);
355 Value *A0 = ICMP->getOperand(0);
356 Value *A1 = ICMP->getOperand(1);
357 if (!A0->getType()->isIntegerTy()) continue;
358 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000359 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
David Blaikieff6409d2015-05-18 22:13:54 +0000360 IRB.CreateCall(
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000361 SanCovTraceCmpFunction,
David Blaikieff6409d2015-05-18 22:13:54 +0000362 {ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()),
363 IRB.CreateIntCast(A0, Int64Ty, true),
364 IRB.CreateIntCast(A1, Int64Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000365 }
366 }
367}
368
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000369void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000370 I->setMetadata(
371 I->getParent()->getParent()->getParent()->getMDKindID("nosanitize"),
372 MDNode::get(*C, None));
373}
374
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000375void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
376 bool UseCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000377 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
378 // Skip static allocas at the top of the entry block so they don't become
379 // dynamic when we split the block. If we used our optimized stack layout,
380 // then there will only be one alloca and it will come first.
381 for (; IP != BE; ++IP) {
382 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
383 if (!AI || !AI->isStaticAlloca())
384 break;
385 }
386
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000387 bool IsEntryBB = &BB == &F.getEntryBlock();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000388 DebugLoc EntryLoc = IsEntryBB && IP->getDebugLoc()
389 ? IP->getDebugLoc().getFnDebugLoc()
Duncan P. N. Exon Smith18c97fa2015-03-20 18:48:45 +0000390 : IP->getDebugLoc();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000391 IRBuilder<> IRB(IP);
392 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000393 SmallVector<Value *, 1> Indices;
394 Value *GuardP = IRB.CreateAdd(
395 IRB.CreatePointerCast(GuardArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000396 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000397 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
398 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000399 if (UseCalls) {
400 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
401 } else {
402 LoadInst *Load = IRB.CreateLoad(GuardP);
403 Load->setAtomic(Monotonic);
404 Load->setAlignment(4);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000405 SetNoSanitizeMetadata(Load);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000406 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
407 Instruction *Ins = SplitBlockAndInsertIfThen(
408 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
409 IRB.SetInsertPoint(Ins);
410 IRB.SetCurrentDebugLocation(EntryLoc);
411 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
412 IRB.CreateCall(SanCovFunction, GuardP);
David Blaikieff6409d2015-05-18 22:13:54 +0000413 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000414 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000415
Alexey Samsonov3514f272015-05-07 01:00:31 +0000416 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000417 IRB.SetInsertPoint(IP);
418 Value *P = IRB.CreateAdd(
419 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000420 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000421 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000422 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000423 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000424 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000425 SetNoSanitizeMetadata(LI);
426 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000427 }
428
Alexey Samsonov3514f272015-05-07 01:00:31 +0000429 if (Options.TraceBB) {
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000430 // Experimental support for tracing.
431 // Insert a callback with the same guard variable as used for coverage.
432 IRB.SetInsertPoint(IP);
433 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
434 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000435}
436
437char SanitizerCoverageModule::ID = 0;
438INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
439 "SanitizerCoverage: TODO."
440 "ModulePass", false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000441ModulePass *llvm::createSanitizerCoverageModulePass(
442 const SanitizerCoverageOptions &Options) {
443 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000444}