blob: c034a833bed9422249e7f817498c6e8abf5f694a [file] [log] [blame]
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001//===- MemorySanitizer.cpp - detector of uninitialized reads --------------===//
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002//
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//===----------------------------------------------------------------------===//
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00009//
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000010/// \file
11/// This file is a part of MemorySanitizer, a detector of uninitialized
12/// reads.
13///
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000014/// The algorithm of the tool is similar to Memcheck
15/// (http://goo.gl/QKbem). We associate a few shadow bits with every
16/// byte of the application memory, poison the shadow of the malloc-ed
17/// or alloca-ed memory, load the shadow bits on every memory read,
18/// propagate the shadow bits through some of the arithmetic
19/// instruction (including MOV), store the shadow bits on every memory
20/// write, report a bug on some other instructions (e.g. JMP) if the
21/// associated shadow is poisoned.
22///
23/// But there are differences too. The first and the major one:
24/// compiler instrumentation instead of binary instrumentation. This
25/// gives us much better register allocation, possible compiler
26/// optimizations and a fast start-up. But this brings the major issue
27/// as well: msan needs to see all program events, including system
28/// calls and reads/writes in system libraries, so we either need to
29/// compile *everything* with msan or use a binary translation
30/// component (e.g. DynamoRIO) to instrument pre-built libraries.
31/// Another difference from Memcheck is that we use 8 shadow bits per
32/// byte of application memory and use a direct shadow mapping. This
33/// greatly simplifies the instrumentation code and avoids races on
34/// shadow updates (Memcheck is single-threaded so races are not a
35/// concern there. Memcheck uses 2 shadow bits per byte with a slow
36/// path storage that uses 8 bits per byte).
37///
38/// The default value of shadow is 0, which means "clean" (not poisoned).
39///
40/// Every module initializer should call __msan_init to ensure that the
41/// shadow memory is ready. On error, __msan_warning is called. Since
42/// parameters and return values may be passed via registers, we have a
43/// specialized thread-local shadow for return values
44/// (__msan_retval_tls) and parameters (__msan_param_tls).
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +000045///
46/// Origin tracking.
47///
48/// MemorySanitizer can track origins (allocation points) of all uninitialized
49/// values. This behavior is controlled with a flag (msan-track-origins) and is
50/// disabled by default.
51///
52/// Origins are 4-byte values created and interpreted by the runtime library.
53/// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
54/// of application memory. Propagation of origins is basically a bunch of
55/// "select" instructions that pick the origin of a dirty argument, if an
56/// instruction has one.
57///
58/// Every 4 aligned, consecutive bytes of application memory have one origin
59/// value associated with them. If these bytes contain uninitialized data
60/// coming from 2 different allocations, the last store wins. Because of this,
61/// MemorySanitizer reports can show unrelated origins, but this is unlikely in
Alexey Samsonov3efc87e2012-12-28 09:30:44 +000062/// practice.
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +000063///
64/// Origins are meaningless for fully initialized values, so MemorySanitizer
65/// avoids storing origin to memory when a fully initialized value is stored.
66/// This way it avoids needless overwritting origin of the 4-byte region on
67/// a short (i.e. 1 byte) clean store, and it is also good for performance.
Evgeniy Stepanov5522a702013-09-24 11:20:27 +000068///
69/// Atomic handling.
70///
71/// Ideally, every atomic store of application value should update the
72/// corresponding shadow location in an atomic way. Unfortunately, atomic store
73/// of two disjoint locations can not be done without severe slowdown.
74///
75/// Therefore, we implement an approximation that may err on the safe side.
76/// In this implementation, every atomically accessed location in the program
77/// may only change from (partially) uninitialized to fully initialized, but
78/// not the other way around. We load the shadow _after_ the application load,
79/// and we store the shadow _before_ the app store. Also, we always store clean
80/// shadow (if the application store is atomic). This way, if the store-load
81/// pair constitutes a happens-before arc, shadow store and load are correctly
82/// ordered such that the load will get either the value that was stored, or
83/// some later value (which is always clean).
84///
85/// This does not work very well with Compare-And-Swap (CAS) and
86/// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
87/// must store the new shadow before the app operation, and load the shadow
88/// after the app operation. Computers don't work this way. Current
89/// implementation ignores the load aspect of CAS/RMW, always returning a clean
90/// value. It implements the store part as a simple atomic store by storing a
91/// clean shadow.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000092//
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000093//===----------------------------------------------------------------------===//
94
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000095#include "llvm/ADT/APInt.h"
96#include "llvm/ADT/ArrayRef.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000097#include "llvm/ADT/DepthFirstIterator.h"
98#include "llvm/ADT/SmallString.h"
99#include "llvm/ADT/SmallVector.h"
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000100#include "llvm/ADT/StringExtras.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000101#include "llvm/ADT/StringRef.h"
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +0000102#include "llvm/ADT/Triple.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000103#include "llvm/Analysis/TargetLibraryInfo.h"
104#include "llvm/IR/Argument.h"
105#include "llvm/IR/Attributes.h"
106#include "llvm/IR/BasicBlock.h"
107#include "llvm/IR/CallSite.h"
108#include "llvm/IR/CallingConv.h"
109#include "llvm/IR/Constant.h"
110#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000111#include "llvm/IR/DataLayout.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000112#include "llvm/IR/DerivedTypes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000113#include "llvm/IR/Function.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000114#include "llvm/IR/GlobalValue.h"
115#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000116#include "llvm/IR/IRBuilder.h"
117#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +0000118#include "llvm/IR/InstVisitor.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000119#include "llvm/IR/InstrTypes.h"
120#include "llvm/IR/Instruction.h"
121#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000122#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000123#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000124#include "llvm/IR/LLVMContext.h"
125#include "llvm/IR/MDBuilder.h"
126#include "llvm/IR/Module.h"
127#include "llvm/IR/Type.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000128#include "llvm/IR/Value.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +0000129#include "llvm/IR/ValueMap.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000130#include "llvm/Pass.h"
131#include "llvm/Support/AtomicOrdering.h"
132#include "llvm/Support/Casting.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000133#include "llvm/Support/CommandLine.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000134#include "llvm/Support/Compiler.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000135#include "llvm/Support/Debug.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000136#include "llvm/Support/ErrorHandling.h"
137#include "llvm/Support/MathExtras.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000138#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +0000139#include "llvm/Transforms/Instrumentation.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000140#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +0000141#include "llvm/Transforms/Utils/Local.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000142#include "llvm/Transforms/Utils/ModuleUtils.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000143#include <algorithm>
144#include <cassert>
145#include <cstddef>
146#include <cstdint>
147#include <memory>
148#include <string>
149#include <tuple>
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000150
151using namespace llvm;
152
Chandler Carruth964daaa2014-04-22 02:55:47 +0000153#define DEBUG_TYPE "msan"
154
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000155static const unsigned kOriginSize = 4;
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +0000156static const unsigned kMinOriginAlignment = 4;
157static const unsigned kShadowTLSAlignment = 8;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000158
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000159// These constants must be kept in sync with the ones in msan.h.
160static const unsigned kParamTLSSize = 800;
161static const unsigned kRetvalTLSSize = 800;
162
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000163// Accesses sizes are powers of two: 1, 2, 4, 8.
164static const size_t kNumberOfAccessSizes = 4;
165
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +0000166/// \brief Track origins of uninitialized values.
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000167///
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +0000168/// Adds a section to MemorySanitizer report that points to the allocation
169/// (stack or heap) the uninitialized bits came from originally.
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000170static cl::opt<int> ClTrackOrigins("msan-track-origins",
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000171 cl::desc("Track origins (allocation sites) of poisoned memory"),
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000172 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000173
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000174static cl::opt<bool> ClKeepGoing("msan-keep-going",
175 cl::desc("keep going after reporting a UMR"),
176 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000177
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000178static cl::opt<bool> ClPoisonStack("msan-poison-stack",
179 cl::desc("poison uninitialized stack variables"),
180 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000181
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000182static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
183 cl::desc("poison uninitialized stack variables with a call"),
184 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000185
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000186static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
Evgeniy Stepanov670abcf2015-10-05 18:01:17 +0000187 cl::desc("poison uninitialized stack variables with the given pattern"),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000188 cl::Hidden, cl::init(0xff));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000189
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000190static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
191 cl::desc("poison undef temps"),
192 cl::Hidden, cl::init(true));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000193
194static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
195 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
196 cl::Hidden, cl::init(true));
197
Evgeniy Stepanovfac84032013-01-25 15:31:10 +0000198static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
199 cl::desc("exact handling of relational integer ICmp"),
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +0000200 cl::Hidden, cl::init(false));
Evgeniy Stepanovfac84032013-01-25 15:31:10 +0000201
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000202// This flag controls whether we check the shadow of the address
203// operand of load or store. Such bugs are very rare, since load from
204// a garbage address typically results in SEGV, but still happen
205// (e.g. only lower bits of address are garbage, or the access happens
206// early at program startup where malloc-ed memory is more likely to
207// be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
208static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
209 cl::desc("report accesses through a pointer which has poisoned shadow"),
210 cl::Hidden, cl::init(true));
211
212static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
213 cl::desc("print out instructions with default strict semantics"),
214 cl::Hidden, cl::init(false));
215
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000216static cl::opt<int> ClInstrumentationWithCallThreshold(
217 "msan-instrumentation-with-call-threshold",
218 cl::desc(
219 "If the function being instrumented requires more than "
220 "this number of checks and origin stores, use callbacks instead of "
221 "inline checks (-1 means never use callbacks)."),
Evgeniy Stepanov3939f542014-04-21 15:04:05 +0000222 cl::Hidden, cl::init(3500));
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000223
Evgeniy Stepanov7db296e2014-10-23 01:05:46 +0000224// This is an experiment to enable handling of cases where shadow is a non-zero
225// compile-time constant. For some unexplainable reason they were silently
226// ignored in the instrumentation.
227static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
228 cl::desc("Insert checks for constant shadow values"),
229 cl::Hidden, cl::init(false));
Evgeniy Stepanov4b96ed62016-03-16 17:39:17 +0000230
231// This is off by default because of a bug in gold:
232// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
Evgeniy Stepanovd6e91362016-03-15 20:25:47 +0000233static cl::opt<bool> ClWithComdat("msan-with-comdat",
234 cl::desc("Place MSan constructors in comdat sections"),
235 cl::Hidden, cl::init(false));
Evgeniy Stepanov7db296e2014-10-23 01:05:46 +0000236
Ismail Pazarbasie5048e12015-05-07 21:41:52 +0000237static const char *const kMsanModuleCtorName = "msan.module_ctor";
238static const char *const kMsanInitName = "__msan_init";
239
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000240namespace {
241
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000242// Memory map parameters used in application-to-shadow address calculation.
243// Offset = (Addr & ~AndMask) ^ XorMask
244// Shadow = ShadowBase + Offset
245// Origin = OriginBase + Offset
246struct MemoryMapParams {
247 uint64_t AndMask;
248 uint64_t XorMask;
249 uint64_t ShadowBase;
250 uint64_t OriginBase;
251};
252
253struct PlatformMemoryMapParams {
254 const MemoryMapParams *bits32;
255 const MemoryMapParams *bits64;
256};
257
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000258} // end anonymous namespace
259
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000260// i386 Linux
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000261static const MemoryMapParams Linux_I386_MemoryMapParams = {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000262 0x000080000000, // AndMask
263 0, // XorMask (not used)
264 0, // ShadowBase (not used)
265 0x000040000000, // OriginBase
266};
267
268// x86_64 Linux
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000269static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
Evgeniy Stepanovd12212b2015-10-08 21:35:26 +0000270#ifdef MSAN_LINUX_X86_64_OLD_MAPPING
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000271 0x400000000000, // AndMask
272 0, // XorMask (not used)
273 0, // ShadowBase (not used)
274 0x200000000000, // OriginBase
Evgeniy Stepanovd12212b2015-10-08 21:35:26 +0000275#else
276 0, // AndMask (not used)
277 0x500000000000, // XorMask
278 0, // ShadowBase (not used)
279 0x100000000000, // OriginBase
280#endif
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000281};
282
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000283// mips64 Linux
284static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
Sagar Thakure3117402016-08-16 12:55:38 +0000285 0, // AndMask (not used)
286 0x008000000000, // XorMask
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000287 0, // ShadowBase (not used)
288 0x002000000000, // OriginBase
289};
290
Jay Foad7a28cdc2015-06-25 10:34:29 +0000291// ppc64 Linux
292static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
Bill Seurer44156a02017-11-13 15:43:19 +0000293 0xE00000000000, // AndMask
Jay Foad7a28cdc2015-06-25 10:34:29 +0000294 0x100000000000, // XorMask
295 0x080000000000, // ShadowBase
296 0x1C0000000000, // OriginBase
297};
298
Adhemerval Zanellaf0c95bd2015-09-16 15:10:27 +0000299// aarch64 Linux
300static const MemoryMapParams Linux_AArch64_MemoryMapParams = {
Adhemerval Zanella1edb0842015-10-29 13:02:30 +0000301 0, // AndMask (not used)
302 0x06000000000, // XorMask
303 0, // ShadowBase (not used)
304 0x01000000000, // OriginBase
Adhemerval Zanellaf0c95bd2015-09-16 15:10:27 +0000305};
306
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000307// i386 FreeBSD
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000308static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000309 0x000180000000, // AndMask
310 0x000040000000, // XorMask
311 0x000020000000, // ShadowBase
312 0x000700000000, // OriginBase
313};
314
315// x86_64 FreeBSD
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000316static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000317 0xc00000000000, // AndMask
318 0x200000000000, // XorMask
319 0x100000000000, // ShadowBase
320 0x380000000000, // OriginBase
321};
322
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000323static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
324 &Linux_I386_MemoryMapParams,
325 &Linux_X86_64_MemoryMapParams,
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000326};
327
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000328static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000329 nullptr,
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000330 &Linux_MIPS64_MemoryMapParams,
331};
332
Jay Foad7a28cdc2015-06-25 10:34:29 +0000333static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000334 nullptr,
Jay Foad7a28cdc2015-06-25 10:34:29 +0000335 &Linux_PowerPC64_MemoryMapParams,
336};
337
Adhemerval Zanellaf0c95bd2015-09-16 15:10:27 +0000338static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = {
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000339 nullptr,
Adhemerval Zanellaf0c95bd2015-09-16 15:10:27 +0000340 &Linux_AArch64_MemoryMapParams,
341};
342
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000343static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
344 &FreeBSD_I386_MemoryMapParams,
345 &FreeBSD_X86_64_MemoryMapParams,
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000346};
347
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000348namespace {
349
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000350/// \brief An instrumentation pass implementing detection of uninitialized
351/// reads.
352///
353/// MemorySanitizer: instrument the code in module to find
354/// uninitialized reads.
355class MemorySanitizer : public FunctionPass {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000356public:
357 // Pass identification, replacement for typeid.
358 static char ID;
359
Evgeniy Stepanovcd729d62016-11-07 21:00:10 +0000360 MemorySanitizer(int TrackOrigins = 0, bool Recover = false)
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000361 : FunctionPass(ID),
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000362 TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000363 Recover(Recover || ClKeepGoing) {}
364
Mehdi Amini117296c2016-10-01 02:56:57 +0000365 StringRef getPassName() const override { return "MemorySanitizer"; }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000366
Marcin Koscielnicki3feda222016-06-18 10:10:37 +0000367 void getAnalysisUsage(AnalysisUsage &AU) const override {
368 AU.addRequired<TargetLibraryInfoWrapperPass>();
369 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000370
Craig Topper3e4c6972014-03-05 09:10:37 +0000371 bool runOnFunction(Function &F) override;
372 bool doInitialization(Module &M) override;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000373
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000374private:
375 friend struct MemorySanitizerVisitor;
376 friend struct VarArgAMD64Helper;
377 friend struct VarArgMIPS64Helper;
378 friend struct VarArgAArch64Helper;
379 friend struct VarArgPowerPC64Helper;
380
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000381 void initializeCallbacks(Module &M);
382
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000383 /// \brief Track origins (allocation points) of uninitialized values.
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000384 int TrackOrigins;
Evgeniy Stepanovcd729d62016-11-07 21:00:10 +0000385 bool Recover;
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000386
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000387 LLVMContext *C;
388 Type *IntptrTy;
389 Type *OriginTy;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000390
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000391 /// \brief Thread-local shadow storage for function parameters.
392 GlobalVariable *ParamTLS;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000393
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000394 /// \brief Thread-local origin storage for function parameters.
395 GlobalVariable *ParamOriginTLS;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000396
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000397 /// \brief Thread-local shadow storage for function return value.
398 GlobalVariable *RetvalTLS;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000399
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000400 /// \brief Thread-local origin storage for function return value.
401 GlobalVariable *RetvalOriginTLS;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000402
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000403 /// \brief Thread-local shadow storage for in-register va_arg function
404 /// parameters (x86_64-specific).
405 GlobalVariable *VAArgTLS;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000406
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000407 /// \brief Thread-local shadow storage for va_arg overflow area
408 /// (x86_64-specific).
409 GlobalVariable *VAArgOverflowSizeTLS;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000410
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000411 /// \brief Thread-local space used to pass origin value to the UMR reporting
412 /// function.
413 GlobalVariable *OriginTLS;
414
415 /// \brief The run-time callback to print a warning.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000416 Value *WarningFn = nullptr;
417
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000418 // These arrays are indexed by log2(AccessSize).
419 Value *MaybeWarningFn[kNumberOfAccessSizes];
420 Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
421
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000422 /// \brief Run-time helper that generates a new origin value for a stack
423 /// allocation.
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +0000424 Value *MsanSetAllocaOrigin4Fn;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000425
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000426 /// \brief Run-time helper that poisons stack on function entry.
427 Value *MsanPoisonStackFn;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000428
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000429 /// \brief Run-time helper that records a store (or any event) of an
430 /// uninitialized value and returns an updated origin id encoding this info.
431 Value *MsanChainOriginFn;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000432
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000433 /// \brief MSan runtime replacements for memmove, memcpy and memset.
434 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000435
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000436 /// \brief Memory map parameters used in application-to-shadow calculation.
437 const MemoryMapParams *MapParams;
438
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000439 MDNode *ColdCallWeights;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000440
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000441 /// \brief Branch weights for origin store.
442 MDNode *OriginStoreWeights;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000443
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000444 /// \brief An empty volatile inline asm that prevents callback merge.
445 InlineAsm *EmptyAsm;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000446
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000447 Function *MsanCtorFunction;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000448};
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000449
450} // end anonymous namespace
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000451
452char MemorySanitizer::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000453
Marcin Koscielnicki3feda222016-06-18 10:10:37 +0000454INITIALIZE_PASS_BEGIN(
455 MemorySanitizer, "msan",
456 "MemorySanitizer: detects uninitialized reads.", false, false)
457INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
458INITIALIZE_PASS_END(
459 MemorySanitizer, "msan",
460 "MemorySanitizer: detects uninitialized reads.", false, false)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000461
Evgeniy Stepanovcd729d62016-11-07 21:00:10 +0000462FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins, bool Recover) {
463 return new MemorySanitizer(TrackOrigins, Recover);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000464}
465
466/// \brief Create a non-const global initialized with the given string.
467///
468/// Creates a writable global for Str so that we can pass it to the
469/// run-time lib. Runtime uses first 4 bytes of the string to store the
470/// frame ID, so the string needs to be mutable.
471static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
472 StringRef Str) {
473 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
474 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
475 GlobalValue::PrivateLinkage, StrConst, "");
476}
477
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000478/// \brief Insert extern declaration of runtime-provided functions and globals.
479void MemorySanitizer::initializeCallbacks(Module &M) {
480 // Only do this once.
481 if (WarningFn)
482 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000483
484 IRBuilder<> IRB(*C);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000485 // Create the callback.
486 // FIXME: this function should have "Cold" calling conv,
487 // which is not yet implemented.
Evgeniy Stepanovcd729d62016-11-07 21:00:10 +0000488 StringRef WarningFnName = Recover ? "__msan_warning"
489 : "__msan_warning_noreturn";
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000490 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000491
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000492 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
493 AccessSizeIndex++) {
494 unsigned AccessSize = 1 << AccessSizeIndex;
495 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000496 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
497 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000498 IRB.getInt32Ty());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000499
500 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
501 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
502 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000503 IRB.getInt8PtrTy(), IRB.getInt32Ty());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000504 }
505
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +0000506 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000507 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000508 IRB.getInt8PtrTy(), IntptrTy);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000509 MsanPoisonStackFn =
510 M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000511 IRB.getInt8PtrTy(), IntptrTy);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000512 MsanChainOriginFn = M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000513 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty());
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000514 MemmoveFn = M.getOrInsertFunction(
515 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000516 IRB.getInt8PtrTy(), IntptrTy);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000517 MemcpyFn = M.getOrInsertFunction(
518 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000519 IntptrTy);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000520 MemsetFn = M.getOrInsertFunction(
521 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000522 IntptrTy);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000523
524 // Create globals.
525 RetvalTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000526 M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000527 GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000528 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000529 RetvalOriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000530 M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
531 "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000532
533 ParamTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000534 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000535 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000536 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000537 ParamOriginTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000538 M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
539 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
540 nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000541
542 VAArgTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000543 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000544 GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000545 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000546 VAArgOverflowSizeTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000547 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
548 "__msan_va_arg_overflow_size_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000549 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000550 OriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000551 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
552 "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000553
554 // We insert an empty inline asm after __msan_report* to avoid callback merge.
555 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
556 StringRef(""), StringRef(""),
557 /*hasSideEffects=*/true);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000558}
559
560/// \brief Module-level initialization.
561///
562/// inserts a call to __msan_init to the module's constructor list.
563bool MemorySanitizer::doInitialization(Module &M) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000564 auto &DL = M.getDataLayout();
Rafael Espindola93512512014-02-25 17:30:31 +0000565
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000566 Triple TargetTriple(M.getTargetTriple());
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000567 switch (TargetTriple.getOS()) {
568 case Triple::FreeBSD:
569 switch (TargetTriple.getArch()) {
570 case Triple::x86_64:
571 MapParams = FreeBSD_X86_MemoryMapParams.bits64;
572 break;
573 case Triple::x86:
574 MapParams = FreeBSD_X86_MemoryMapParams.bits32;
575 break;
576 default:
577 report_fatal_error("unsupported architecture");
578 }
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000579 break;
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000580 case Triple::Linux:
581 switch (TargetTriple.getArch()) {
582 case Triple::x86_64:
583 MapParams = Linux_X86_MemoryMapParams.bits64;
584 break;
585 case Triple::x86:
586 MapParams = Linux_X86_MemoryMapParams.bits32;
587 break;
588 case Triple::mips64:
589 case Triple::mips64el:
590 MapParams = Linux_MIPS_MemoryMapParams.bits64;
591 break;
Jay Foad7a28cdc2015-06-25 10:34:29 +0000592 case Triple::ppc64:
593 case Triple::ppc64le:
594 MapParams = Linux_PowerPC_MemoryMapParams.bits64;
595 break;
Adhemerval Zanellaf0c95bd2015-09-16 15:10:27 +0000596 case Triple::aarch64:
597 case Triple::aarch64_be:
598 MapParams = Linux_ARM_MemoryMapParams.bits64;
599 break;
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000600 default:
601 report_fatal_error("unsupported architecture");
602 }
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000603 break;
604 default:
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000605 report_fatal_error("unsupported operating system");
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000606 }
607
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000608 C = &(M.getContext());
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000609 IRBuilder<> IRB(*C);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000610 IntptrTy = IRB.getIntPtrTy(DL);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000611 OriginTy = IRB.getInt32Ty();
612
613 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000614 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000615
Ismail Pazarbasie5048e12015-05-07 21:41:52 +0000616 std::tie(MsanCtorFunction, std::ignore) =
617 createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
618 /*InitArgTypes=*/{},
619 /*InitArgs=*/{});
Evgeniy Stepanovd6e91362016-03-15 20:25:47 +0000620 if (ClWithComdat) {
621 Comdat *MsanCtorComdat = M.getOrInsertComdat(kMsanModuleCtorName);
622 MsanCtorFunction->setComdat(MsanCtorComdat);
623 appendToGlobalCtors(M, MsanCtorFunction, 0, MsanCtorFunction);
624 } else {
625 appendToGlobalCtors(M, MsanCtorFunction, 0);
626 }
Ismail Pazarbasie5048e12015-05-07 21:41:52 +0000627
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000628
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000629 if (TrackOrigins)
630 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
631 IRB.getInt32(TrackOrigins), "__msan_track_origins");
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000632
Evgeniy Stepanovcd729d62016-11-07 21:00:10 +0000633 if (Recover)
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000634 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
Evgeniy Stepanovcd729d62016-11-07 21:00:10 +0000635 IRB.getInt32(Recover), "__msan_keep_going");
Evgeniy Stepanovdcf6bcb2013-01-22 13:26:53 +0000636
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000637 return true;
638}
639
640namespace {
641
642/// \brief A helper class that handles instrumentation of VarArg
643/// functions on a particular platform.
644///
645/// Implementations are expected to insert the instrumentation
646/// necessary to propagate argument shadow through VarArg function
647/// calls. Visit* methods are called during an InstVisitor pass over
648/// the function, and should avoid creating new basic blocks. A new
649/// instance of this class is created for each instrumented function.
650struct VarArgHelper {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000651 virtual ~VarArgHelper() = default;
652
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000653 /// \brief Visit a CallSite.
654 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
655
656 /// \brief Visit a va_start call.
657 virtual void visitVAStartInst(VAStartInst &I) = 0;
658
659 /// \brief Visit a va_copy call.
660 virtual void visitVACopyInst(VACopyInst &I) = 0;
661
662 /// \brief Finalize function instrumentation.
663 ///
664 /// This method is called after visiting all interesting (see above)
665 /// instructions in a function.
666 virtual void finalizeInstrumentation() = 0;
667};
668
669struct MemorySanitizerVisitor;
670
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000671} // end anonymous namespace
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000672
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000673static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
674 MemorySanitizerVisitor &Visitor);
675
676static unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000677 if (TypeSize <= 8) return 0;
Evgeniy Stepanovb7363352016-07-01 22:49:59 +0000678 return Log2_32_Ceil((TypeSize + 7) / 8);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000679}
680
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000681namespace {
682
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000683/// This class does all the work for a given function. Store and Load
684/// instructions store and load corresponding shadow and origin
685/// values. Most instructions propagate shadow from arguments to their
686/// return values. Certain instructions (most importantly, BranchInst)
687/// test their argument shadow and print reports (with a runtime call) if it's
688/// non-zero.
689struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
690 Function &F;
691 MemorySanitizer &MS;
692 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
693 ValueMap<Value*, Value*> ShadowMap, OriginMap;
Ahmed Charles56440fd2014-03-06 05:51:42 +0000694 std::unique_ptr<VarArgHelper> VAHelper;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +0000695 const TargetLibraryInfo *TLI;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000696
697 // The following flags disable parts of MSan instrumentation based on
698 // blacklist contents and command-line options.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000699 bool InsertChecks;
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000700 bool PropagateShadow;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000701 bool PoisonStack;
702 bool PoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000703 bool CheckReturnValue;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000704
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000705 struct ShadowOriginAndInsertPoint {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000706 Value *Shadow;
707 Value *Origin;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000708 Instruction *OrigIns;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000709
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000710 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000711 : Shadow(S), Origin(O), OrigIns(I) {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000712 };
713 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
Benjamin Kramer4c137db2016-06-27 12:25:23 +0000714 SmallVector<StoreInst *, 16> StoreList;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000715
716 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000717 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +0000718 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000719 InsertChecks = SanitizeFunction;
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000720 PropagateShadow = SanitizeFunction;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000721 PoisonStack = SanitizeFunction && ClPoisonStack;
722 PoisonUndef = SanitizeFunction && ClPoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000723 // FIXME: Consider using SpecialCaseList to specify a list of functions that
724 // must always return fully initialized values. For now, we hardcode "main".
725 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
Marcin Koscielnicki3feda222016-06-18 10:10:37 +0000726 TLI = &MS.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000727
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000728 DEBUG(if (!InsertChecks)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000729 dbgs() << "MemorySanitizer is not inserting checks into '"
730 << F.getName() << "'\n");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000731 }
732
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000733 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
734 if (MS.TrackOrigins <= 1) return V;
735 return IRB.CreateCall(MS.MsanChainOriginFn, V);
736 }
737
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000738 Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000739 const DataLayout &DL = F.getParent()->getDataLayout();
740 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000741 if (IntptrSize == kOriginSize) return Origin;
742 assert(IntptrSize == kOriginSize * 2);
743 Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
744 return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
745 }
746
747 /// \brief Fill memory range with the given origin value.
748 void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
749 unsigned Size, unsigned Alignment) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000750 const DataLayout &DL = F.getParent()->getDataLayout();
751 unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
752 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000753 assert(IntptrAlignment >= kMinOriginAlignment);
754 assert(IntptrSize >= kOriginSize);
755
756 unsigned Ofs = 0;
757 unsigned CurrentAlignment = Alignment;
758 if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
759 Value *IntptrOrigin = originToIntptr(IRB, Origin);
760 Value *IntptrOriginPtr =
761 IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
762 for (unsigned i = 0; i < Size / IntptrSize; ++i) {
David Blaikie95d3e532015-04-03 23:03:54 +0000763 Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
764 : IntptrOriginPtr;
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000765 IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
766 Ofs += IntptrSize / kOriginSize;
767 CurrentAlignment = IntptrAlignment;
768 }
769 }
770
771 for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
David Blaikie95d3e532015-04-03 23:03:54 +0000772 Value *GEP =
773 i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000774 IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
775 CurrentAlignment = kMinOriginAlignment;
776 }
777 }
778
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000779 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
780 unsigned Alignment, bool AsCall) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000781 const DataLayout &DL = F.getParent()->getDataLayout();
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000782 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000783 unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
Adhemerval Zanellae600c992016-01-11 19:55:27 +0000784 if (Shadow->getType()->isAggregateType()) {
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000785 paintOrigin(IRB, updateOrigin(Origin, IRB),
786 getOriginPtr(Addr, IRB, Alignment), StoreSize,
787 OriginAlignment);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000788 } else {
789 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000790 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
791 if (ConstantShadow) {
792 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000793 paintOrigin(IRB, updateOrigin(Origin, IRB),
794 getOriginPtr(Addr, IRB, Alignment), StoreSize,
795 OriginAlignment);
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000796 return;
797 }
798
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000799 unsigned TypeSizeInBits =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000800 DL.getTypeSizeInBits(ConvertedShadow->getType());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000801 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
802 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
803 Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
804 Value *ConvertedShadow2 = IRB.CreateZExt(
805 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
David Blaikieff6409d2015-05-18 22:13:54 +0000806 IRB.CreateCall(Fn, {ConvertedShadow2,
807 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
808 Origin});
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000809 } else {
810 Value *Cmp = IRB.CreateICmpNE(
811 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
812 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000813 Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000814 IRBuilder<> IRBNew(CheckTerm);
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000815 paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
816 getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
817 OriginAlignment);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000818 }
819 }
820 }
821
822 void materializeStores(bool InstrumentWithCalls) {
Benjamin Kramer4c137db2016-06-27 12:25:23 +0000823 for (StoreInst *SI : StoreList) {
824 IRBuilder<> IRB(SI);
825 Value *Val = SI->getValueOperand();
826 Value *Addr = SI->getPointerOperand();
827 Value *Shadow = SI->isAtomic() ? getCleanShadow(Val) : getShadow(Val);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000828 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
829
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000830 StoreInst *NewSI =
Benjamin Kramer4c137db2016-06-27 12:25:23 +0000831 IRB.CreateAlignedStore(Shadow, ShadowPtr, SI->getAlignment());
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000832 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
Evgeniy Stepanovc4415592013-01-22 12:30:52 +0000833
Benjamin Kramer4c137db2016-06-27 12:25:23 +0000834 if (ClCheckAccessAddress)
Alexander Potapenko391804f2017-11-23 08:34:32 +0000835 insertShadowCheck(Addr, NewSI);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000836
Benjamin Kramer4c137db2016-06-27 12:25:23 +0000837 if (SI->isAtomic())
838 SI->setOrdering(addReleaseOrdering(SI->getOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +0000839
Benjamin Kramer4c137db2016-06-27 12:25:23 +0000840 if (MS.TrackOrigins && !SI->isAtomic())
841 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI->getAlignment(),
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000842 InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000843 }
844 }
845
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000846 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
847 bool AsCall) {
848 IRBuilder<> IRB(OrigIns);
849 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
850 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
851 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000852
853 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
854 if (ConstantShadow) {
855 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
856 if (MS.TrackOrigins) {
857 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
858 MS.OriginTLS);
859 }
David Blaikieff6409d2015-05-18 22:13:54 +0000860 IRB.CreateCall(MS.WarningFn, {});
861 IRB.CreateCall(MS.EmptyAsm, {});
Evgeniy Stepanovcd729d62016-11-07 21:00:10 +0000862 // FIXME: Insert UnreachableInst if !MS.Recover?
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000863 // This may invalidate some of the following checks and needs to be done
864 // at the very end.
865 }
866 return;
867 }
868
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000869 const DataLayout &DL = OrigIns->getModule()->getDataLayout();
870
871 unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000872 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
873 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
874 Value *Fn = MS.MaybeWarningFn[SizeIndex];
875 Value *ConvertedShadow2 =
876 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
David Blaikieff6409d2015-05-18 22:13:54 +0000877 IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000878 ? Origin
David Blaikieff6409d2015-05-18 22:13:54 +0000879 : (Value *)IRB.getInt32(0)});
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000880 } else {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000881 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
882 getCleanShadow(ConvertedShadow), "_mscmp");
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000883 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
884 Cmp, OrigIns,
Evgeniy Stepanovcd729d62016-11-07 21:00:10 +0000885 /* Unreachable */ !MS.Recover, MS.ColdCallWeights);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000886
887 IRB.SetInsertPoint(CheckTerm);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000888 if (MS.TrackOrigins) {
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000889 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000890 MS.OriginTLS);
891 }
David Blaikieff6409d2015-05-18 22:13:54 +0000892 IRB.CreateCall(MS.WarningFn, {});
893 IRB.CreateCall(MS.EmptyAsm, {});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000894 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
895 }
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000896 }
897
898 void materializeChecks(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000899 for (const auto &ShadowData : InstrumentationList) {
900 Instruction *OrigIns = ShadowData.OrigIns;
901 Value *Shadow = ShadowData.Shadow;
902 Value *Origin = ShadowData.Origin;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000903 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
904 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000905 DEBUG(dbgs() << "DONE:\n" << F);
906 }
907
908 /// \brief Add MemorySanitizer instrumentation to a function.
909 bool runOnFunction() {
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000910 MS.initializeCallbacks(*F.getParent());
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +0000911
912 // In the presence of unreachable blocks, we may see Phi nodes with
913 // incoming nodes from such blocks. Since InstVisitor skips unreachable
914 // blocks, such nodes will not have any shadow value associated with them.
915 // It's easier to remove unreachable blocks than deal with missing shadow.
916 removeUnreachableBlocks(F);
917
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000918 // Iterate all BBs in depth-first order and create shadow instructions
919 // for all instructions (where applicable).
920 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
David Blaikieceec2bd2014-04-11 01:50:01 +0000921 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000922 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000923
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000924 // Finalize PHI nodes.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000925 for (PHINode *PN : ShadowPHINodes) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000926 PHINode *PNS = cast<PHINode>(getShadow(PN));
Craig Topperf40110f2014-04-25 05:29:35 +0000927 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000928 size_t NumValues = PN->getNumIncomingValues();
929 for (size_t v = 0; v < NumValues; v++) {
930 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000931 if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000932 }
933 }
934
935 VAHelper->finalizeInstrumentation();
936
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000937 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
938 InstrumentationList.size() + StoreList.size() >
939 (unsigned)ClInstrumentationWithCallThreshold;
940
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000941 // Delayed instrumentation of StoreInst.
Evgeniy Stepanov47ac9ba2012-12-06 11:58:59 +0000942 // This may add new checks to be inserted later.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000943 materializeStores(InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000944
945 // Insert shadow value checks.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000946 materializeChecks(InstrumentWithCalls);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000947
948 return true;
949 }
950
951 /// \brief Compute the shadow type that corresponds to a given Value.
952 Type *getShadowTy(Value *V) {
953 return getShadowTy(V->getType());
954 }
955
956 /// \brief Compute the shadow type that corresponds to a given Type.
957 Type *getShadowTy(Type *OrigTy) {
958 if (!OrigTy->isSized()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000959 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000960 }
961 // For integer type, shadow is the same as the original type.
962 // This may return weird-sized types like i1.
963 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
964 return IT;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000965 const DataLayout &DL = F.getParent()->getDataLayout();
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000966 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000968 return VectorType::get(IntegerType::get(*MS.C, EltSize),
969 VT->getNumElements());
970 }
Evgeniy Stepanov5997feb2014-07-31 11:02:27 +0000971 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
972 return ArrayType::get(getShadowTy(AT->getElementType()),
973 AT->getNumElements());
974 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000975 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
976 SmallVector<Type*, 4> Elements;
977 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
978 Elements.push_back(getShadowTy(ST->getElementType(i)));
979 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
980 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
981 return Res;
982 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000983 uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000984 return IntegerType::get(*MS.C, TypeSize);
985 }
986
987 /// \brief Flatten a vector type.
988 Type *getShadowTyNoVec(Type *ty) {
989 if (VectorType *vt = dyn_cast<VectorType>(ty))
990 return IntegerType::get(*MS.C, vt->getBitWidth());
991 return ty;
992 }
993
994 /// \brief Convert a shadow value to it's flattened variant.
995 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
996 Type *Ty = V->getType();
997 Type *NoVecTy = getShadowTyNoVec(Ty);
998 if (Ty == NoVecTy) return V;
999 return IRB.CreateBitCast(V, NoVecTy);
1000 }
1001
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +00001002 /// \brief Compute the integer shadow offset that corresponds to a given
1003 /// application address.
1004 ///
1005 /// Offset = (Addr & ~AndMask) ^ XorMask
1006 Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
Evgeniy Stepanovd12212b2015-10-08 21:35:26 +00001007 Value *OffsetLong = IRB.CreatePointerCast(Addr, MS.IntptrTy);
1008
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +00001009 uint64_t AndMask = MS.MapParams->AndMask;
Evgeniy Stepanovd12212b2015-10-08 21:35:26 +00001010 if (AndMask)
1011 OffsetLong =
1012 IRB.CreateAnd(OffsetLong, ConstantInt::get(MS.IntptrTy, ~AndMask));
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +00001013
1014 uint64_t XorMask = MS.MapParams->XorMask;
Evgeniy Stepanovd12212b2015-10-08 21:35:26 +00001015 if (XorMask)
1016 OffsetLong =
1017 IRB.CreateXor(OffsetLong, ConstantInt::get(MS.IntptrTy, XorMask));
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +00001018 return OffsetLong;
1019 }
1020
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001021 /// \brief Compute the shadow address that corresponds to a given application
1022 /// address.
1023 ///
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +00001024 /// Shadow = ShadowBase + Offset
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001025 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
1026 IRBuilder<> &IRB) {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +00001027 Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
1028 uint64_t ShadowBase = MS.MapParams->ShadowBase;
1029 if (ShadowBase != 0)
1030 ShadowLong =
1031 IRB.CreateAdd(ShadowLong,
1032 ConstantInt::get(MS.IntptrTy, ShadowBase));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001033 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
1034 }
1035
1036 /// \brief Compute the origin address that corresponds to a given application
1037 /// address.
1038 ///
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +00001039 /// OriginAddr = (OriginBase + Offset) & ~3ULL
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00001040 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +00001041 Value *OriginLong = getShadowPtrOffset(Addr, IRB);
1042 uint64_t OriginBase = MS.MapParams->OriginBase;
1043 if (OriginBase != 0)
1044 OriginLong =
1045 IRB.CreateAdd(OriginLong,
1046 ConstantInt::get(MS.IntptrTy, OriginBase));
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00001047 if (Alignment < kMinOriginAlignment) {
1048 uint64_t Mask = kMinOriginAlignment - 1;
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +00001049 OriginLong = IRB.CreateAnd(OriginLong,
1050 ConstantInt::get(MS.IntptrTy, ~Mask));
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00001051 }
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +00001052 return IRB.CreateIntToPtr(OriginLong,
1053 PointerType::get(IRB.getInt32Ty(), 0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001054 }
1055
1056 /// \brief Compute the shadow address for a given function argument.
1057 ///
1058 /// Shadow = ParamTLS+ArgOffset.
1059 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
1060 int ArgOffset) {
1061 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
1062 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1063 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
1064 "_msarg");
1065 }
1066
1067 /// \brief Compute the origin address for a given function argument.
1068 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
1069 int ArgOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001070 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001071 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
1072 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1073 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
1074 "_msarg_o");
1075 }
1076
1077 /// \brief Compute the shadow address for a retval.
1078 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
Alexander Potapenko9e5477f2017-11-23 15:06:51 +00001079 return IRB.CreatePointerCast(MS.RetvalTLS,
1080 PointerType::get(getShadowTy(A), 0),
1081 "_msret");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001082 }
1083
1084 /// \brief Compute the origin address for a retval.
1085 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
1086 // We keep a single origin for the entire retval. Might be too optimistic.
1087 return MS.RetvalOriginTLS;
1088 }
1089
1090 /// \brief Set SV to be the shadow value for V.
1091 void setShadow(Value *V, Value *SV) {
1092 assert(!ShadowMap.count(V) && "Values may only have one shadow");
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001093 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001094 }
1095
1096 /// \brief Set Origin to be the origin value for V.
1097 void setOrigin(Value *V, Value *Origin) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001098 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001099 assert(!OriginMap.count(V) && "Values may only have one origin");
1100 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
1101 OriginMap[V] = Origin;
1102 }
1103
Evgeniy Stepanovd0285f22017-03-03 01:12:43 +00001104 Constant *getCleanShadow(Type *OrigTy) {
1105 Type *ShadowTy = getShadowTy(OrigTy);
1106 if (!ShadowTy)
1107 return nullptr;
1108 return Constant::getNullValue(ShadowTy);
1109 }
1110
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001111 /// \brief Create a clean shadow value for a given value.
1112 ///
1113 /// Clean shadow (all zeroes) means all bits of the value are defined
1114 /// (initialized).
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +00001115 Constant *getCleanShadow(Value *V) {
Evgeniy Stepanovd0285f22017-03-03 01:12:43 +00001116 return getCleanShadow(V->getType());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001117 }
1118
1119 /// \brief Create a dirty shadow of a given shadow type.
1120 Constant *getPoisonedShadow(Type *ShadowTy) {
1121 assert(ShadowTy);
1122 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
1123 return Constant::getAllOnesValue(ShadowTy);
Evgeniy Stepanov5997feb2014-07-31 11:02:27 +00001124 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
1125 SmallVector<Constant *, 4> Vals(AT->getNumElements(),
1126 getPoisonedShadow(AT->getElementType()));
1127 return ConstantArray::get(AT, Vals);
1128 }
1129 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
1130 SmallVector<Constant *, 4> Vals;
1131 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1132 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1133 return ConstantStruct::get(ST, Vals);
1134 }
1135 llvm_unreachable("Unexpected shadow type");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001136 }
1137
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +00001138 /// \brief Create a dirty shadow for a given value.
1139 Constant *getPoisonedShadow(Value *V) {
1140 Type *ShadowTy = getShadowTy(V);
1141 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +00001142 return nullptr;
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +00001143 return getPoisonedShadow(ShadowTy);
1144 }
1145
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001146 /// \brief Create a clean (zero) origin.
1147 Value *getCleanOrigin() {
1148 return Constant::getNullValue(MS.OriginTy);
1149 }
1150
1151 /// \brief Get the shadow value for a given Value.
1152 ///
1153 /// This function either returns the value set earlier with setShadow,
1154 /// or extracts if from ParamTLS (for function arguments).
1155 Value *getShadow(Value *V) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001156 if (!PropagateShadow) return getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001157 if (Instruction *I = dyn_cast<Instruction>(V)) {
Vitaly Buka8000f222017-11-20 23:37:56 +00001158 if (I->getMetadata("nosanitize"))
1159 return getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001160 // For instructions the shadow is already stored in the map.
1161 Value *Shadow = ShadowMap[V];
1162 if (!Shadow) {
1163 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001164 (void)I;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001165 assert(Shadow && "No shadow for a value");
1166 }
1167 return Shadow;
1168 }
1169 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00001170 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001171 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001172 (void)U;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001173 return AllOnes;
1174 }
1175 if (Argument *A = dyn_cast<Argument>(V)) {
1176 // For arguments we compute the shadow on demand and store it in the map.
1177 Value **ShadowPtr = &ShadowMap[V];
1178 if (*ShadowPtr)
1179 return *ShadowPtr;
1180 Function *F = A->getParent();
1181 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
1182 unsigned ArgOffset = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001183 const DataLayout &DL = F->getParent()->getDataLayout();
Alexey Samsonova02e6642014-05-29 18:40:48 +00001184 for (auto &FArg : F->args()) {
1185 if (!FArg.getType()->isSized()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001186 DEBUG(dbgs() << "Arg is not sized\n");
1187 continue;
1188 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001189 unsigned Size =
1190 FArg.hasByValAttr()
1191 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
1192 : DL.getTypeAllocSize(FArg.getType());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001193 if (A == &FArg) {
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001194 bool Overflow = ArgOffset + Size > kParamTLSSize;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001195 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1196 if (FArg.hasByValAttr()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001197 // ByVal pointer itself has clean shadow. We copy the actual
1198 // argument shadow to the underlying memory.
Evgeniy Stepanovfca01232013-05-28 13:07:43 +00001199 // Figure out maximal valid memcpy alignment.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001200 unsigned ArgAlign = FArg.getParamAlignment();
Evgeniy Stepanovfca01232013-05-28 13:07:43 +00001201 if (ArgAlign == 0) {
1202 Type *EltType = A->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001203 ArgAlign = DL.getABITypeAlignment(EltType);
Evgeniy Stepanovfca01232013-05-28 13:07:43 +00001204 }
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001205 if (Overflow) {
1206 // ParamTLS overflow.
1207 EntryIRB.CreateMemSet(
1208 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
1209 Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
1210 } else {
1211 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1212 Value *Cpy = EntryIRB.CreateMemCpy(
1213 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
Pete Cooper67cf9a72015-11-19 05:56:52 +00001214 CopyAlign);
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001215 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
1216 (void)Cpy;
1217 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001218 *ShadowPtr = getCleanShadow(V);
1219 } else {
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001220 if (Overflow) {
1221 // ParamTLS overflow.
1222 *ShadowPtr = getCleanShadow(V);
1223 } else {
1224 *ShadowPtr =
1225 EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1226 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001227 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001228 DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001229 **ShadowPtr << "\n");
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001230 if (MS.TrackOrigins && !Overflow) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001231 Value *OriginPtr =
1232 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001233 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00001234 } else {
1235 setOrigin(A, getCleanOrigin());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001236 }
1237 }
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001238 ArgOffset += alignTo(Size, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001239 }
1240 assert(*ShadowPtr && "Could not find shadow for an argument");
1241 return *ShadowPtr;
1242 }
1243 // For everything else the shadow is zero.
1244 return getCleanShadow(V);
1245 }
1246
1247 /// \brief Get the shadow for i-th argument of the instruction I.
1248 Value *getShadow(Instruction *I, int i) {
1249 return getShadow(I->getOperand(i));
1250 }
1251
1252 /// \brief Get the origin for a value.
1253 Value *getOrigin(Value *V) {
Craig Topperf40110f2014-04-25 05:29:35 +00001254 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00001255 if (!PropagateShadow) return getCleanOrigin();
1256 if (isa<Constant>(V)) return getCleanOrigin();
1257 assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1258 "Unexpected value type in getOrigin()");
Vitaly Buka8000f222017-11-20 23:37:56 +00001259 if (Instruction *I = dyn_cast<Instruction>(V)) {
1260 if (I->getMetadata("nosanitize"))
1261 return getCleanOrigin();
1262 }
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00001263 Value *Origin = OriginMap[V];
1264 assert(Origin && "Missing origin");
1265 return Origin;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001266 }
1267
1268 /// \brief Get the origin for i-th argument of the instruction I.
1269 Value *getOrigin(Instruction *I, int i) {
1270 return getOrigin(I->getOperand(i));
1271 }
1272
1273 /// \brief Remember the place where a shadow check should be inserted.
1274 ///
1275 /// This location will be later instrumented with a check that will print a
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001276 /// UMR warning in runtime if the shadow value is not 0.
1277 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1278 assert(Shadow);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001279 if (!InsertChecks) return;
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001280#ifndef NDEBUG
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001281 Type *ShadowTy = Shadow->getType();
1282 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1283 "Can only insert checks for integer and vector shadow types");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001284#endif
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001285 InstrumentationList.push_back(
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001286 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1287 }
1288
1289 /// \brief Remember the place where a shadow check should be inserted.
1290 ///
1291 /// This location will be later instrumented with a check that will print a
1292 /// UMR warning in runtime if the value is not fully defined.
1293 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1294 assert(Val);
Evgeniy Stepanovd337a592014-10-24 23:34:15 +00001295 Value *Shadow, *Origin;
1296 if (ClCheckConstantShadow) {
1297 Shadow = getShadow(Val);
1298 if (!Shadow) return;
1299 Origin = getOrigin(Val);
1300 } else {
1301 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1302 if (!Shadow) return;
1303 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1304 }
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001305 insertShadowCheck(Shadow, Origin, OrigIns);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001306 }
1307
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001308 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1309 switch (a) {
JF Bastien800f87a2016-04-06 21:19:33 +00001310 case AtomicOrdering::NotAtomic:
1311 return AtomicOrdering::NotAtomic;
1312 case AtomicOrdering::Unordered:
1313 case AtomicOrdering::Monotonic:
1314 case AtomicOrdering::Release:
1315 return AtomicOrdering::Release;
1316 case AtomicOrdering::Acquire:
1317 case AtomicOrdering::AcquireRelease:
1318 return AtomicOrdering::AcquireRelease;
1319 case AtomicOrdering::SequentiallyConsistent:
1320 return AtomicOrdering::SequentiallyConsistent;
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001321 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001322 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001323 }
1324
1325 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1326 switch (a) {
JF Bastien800f87a2016-04-06 21:19:33 +00001327 case AtomicOrdering::NotAtomic:
1328 return AtomicOrdering::NotAtomic;
1329 case AtomicOrdering::Unordered:
1330 case AtomicOrdering::Monotonic:
1331 case AtomicOrdering::Acquire:
1332 return AtomicOrdering::Acquire;
1333 case AtomicOrdering::Release:
1334 case AtomicOrdering::AcquireRelease:
1335 return AtomicOrdering::AcquireRelease;
1336 case AtomicOrdering::SequentiallyConsistent:
1337 return AtomicOrdering::SequentiallyConsistent;
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001338 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001339 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001340 }
1341
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001342 // ------------------- Visitors.
Vitaly Buka8000f222017-11-20 23:37:56 +00001343 using InstVisitor<MemorySanitizerVisitor>::visit;
1344 void visit(Instruction &I) {
1345 if (!I.getMetadata("nosanitize"))
1346 InstVisitor<MemorySanitizerVisitor>::visit(I);
1347 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001348
1349 /// \brief Instrument LoadInst
1350 ///
1351 /// Loads the corresponding shadow and (optionally) origin.
1352 /// Optionally, checks that the load address is fully defined.
1353 void visitLoadInst(LoadInst &I) {
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001354 assert(I.getType()->isSized() && "Load type must have size");
Vitaly Buka8000f222017-11-20 23:37:56 +00001355 assert(!I.getMetadata("nosanitize"));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001356 IRBuilder<> IRB(I.getNextNode());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001357 Type *ShadowTy = getShadowTy(&I);
1358 Value *Addr = I.getPointerOperand();
Vitaly Buka8000f222017-11-20 23:37:56 +00001359 if (PropagateShadow) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001360 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1361 setShadow(&I,
1362 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1363 } else {
1364 setShadow(&I, getCleanShadow(&I));
1365 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001366
1367 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001368 insertShadowCheck(I.getPointerOperand(), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001369
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001370 if (I.isAtomic())
1371 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1372
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001373 if (MS.TrackOrigins) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001374 if (PropagateShadow) {
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00001375 unsigned Alignment = I.getAlignment();
1376 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1377 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
1378 OriginAlignment));
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001379 } else {
1380 setOrigin(&I, getCleanOrigin());
1381 }
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001382 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001383 }
1384
1385 /// \brief Instrument StoreInst
1386 ///
1387 /// Stores the corresponding shadow and (optionally) origin.
1388 /// Optionally, checks that the store address is fully defined.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001389 void visitStoreInst(StoreInst &I) {
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +00001390 StoreList.push_back(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001391 }
1392
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001393 void handleCASOrRMW(Instruction &I) {
1394 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1395
1396 IRBuilder<> IRB(&I);
1397 Value *Addr = I.getOperand(0);
1398 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1399
1400 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001401 insertShadowCheck(Addr, &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001402
1403 // Only test the conditional argument of cmpxchg instruction.
1404 // The other argument can potentially be uninitialized, but we can not
1405 // detect this situation reliably without possible false positives.
1406 if (isa<AtomicCmpXchgInst>(I))
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001407 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001408
1409 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1410
1411 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00001412 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001413 }
1414
1415 void visitAtomicRMWInst(AtomicRMWInst &I) {
1416 handleCASOrRMW(I);
1417 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1418 }
1419
1420 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1421 handleCASOrRMW(I);
Tim Northovere94a5182014-03-11 10:48:52 +00001422 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001423 }
1424
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001425 // Vector manipulation.
1426 void visitExtractElementInst(ExtractElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001427 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001428 IRBuilder<> IRB(&I);
1429 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1430 "_msprop"));
1431 setOrigin(&I, getOrigin(&I, 0));
1432 }
1433
1434 void visitInsertElementInst(InsertElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001435 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001436 IRBuilder<> IRB(&I);
1437 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1438 I.getOperand(2), "_msprop"));
1439 setOriginForNaryOp(I);
1440 }
1441
1442 void visitShuffleVectorInst(ShuffleVectorInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001443 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001444 IRBuilder<> IRB(&I);
1445 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1446 I.getOperand(2), "_msprop"));
1447 setOriginForNaryOp(I);
1448 }
1449
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001450 // Casts.
1451 void visitSExtInst(SExtInst &I) {
1452 IRBuilder<> IRB(&I);
1453 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1454 setOrigin(&I, getOrigin(&I, 0));
1455 }
1456
1457 void visitZExtInst(ZExtInst &I) {
1458 IRBuilder<> IRB(&I);
1459 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1460 setOrigin(&I, getOrigin(&I, 0));
1461 }
1462
1463 void visitTruncInst(TruncInst &I) {
1464 IRBuilder<> IRB(&I);
1465 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1466 setOrigin(&I, getOrigin(&I, 0));
1467 }
1468
1469 void visitBitCastInst(BitCastInst &I) {
Evgeniy Stepanov24ac55d2015-08-14 22:03:50 +00001470 // Special case: if this is the bitcast (there is exactly 1 allowed) between
1471 // a musttail call and a ret, don't instrument. New instructions are not
1472 // allowed after a musttail call.
1473 if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
1474 if (CI->isMustTailCall())
1475 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001476 IRBuilder<> IRB(&I);
1477 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1478 setOrigin(&I, getOrigin(&I, 0));
1479 }
1480
1481 void visitPtrToIntInst(PtrToIntInst &I) {
1482 IRBuilder<> IRB(&I);
1483 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1484 "_msprop_ptrtoint"));
1485 setOrigin(&I, getOrigin(&I, 0));
1486 }
1487
1488 void visitIntToPtrInst(IntToPtrInst &I) {
1489 IRBuilder<> IRB(&I);
1490 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1491 "_msprop_inttoptr"));
1492 setOrigin(&I, getOrigin(&I, 0));
1493 }
1494
1495 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1496 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1497 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1498 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1499 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1500 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1501
1502 /// \brief Propagate shadow for bitwise AND.
1503 ///
1504 /// This code is exact, i.e. if, for example, a bit in the left argument
1505 /// is defined and 0, then neither the value not definedness of the
1506 /// corresponding bit in B don't affect the resulting shadow.
1507 void visitAnd(BinaryOperator &I) {
1508 IRBuilder<> IRB(&I);
1509 // "And" of 0 and a poisoned value results in unpoisoned value.
1510 // 1&1 => 1; 0&1 => 0; p&1 => p;
1511 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1512 // 1&p => p; 0&p => 0; p&p => p;
1513 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1514 Value *S1 = getShadow(&I, 0);
1515 Value *S2 = getShadow(&I, 1);
1516 Value *V1 = I.getOperand(0);
1517 Value *V2 = I.getOperand(1);
1518 if (V1->getType() != S1->getType()) {
1519 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1520 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1521 }
1522 Value *S1S2 = IRB.CreateAnd(S1, S2);
1523 Value *V1S2 = IRB.CreateAnd(V1, S2);
1524 Value *S1V2 = IRB.CreateAnd(S1, V2);
1525 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1526 setOriginForNaryOp(I);
1527 }
1528
1529 void visitOr(BinaryOperator &I) {
1530 IRBuilder<> IRB(&I);
1531 // "Or" of 1 and a poisoned value results in unpoisoned value.
1532 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1533 // 1|0 => 1; 0|0 => 0; p|0 => p;
1534 // 1|p => 1; 0|p => p; p|p => p;
1535 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1536 Value *S1 = getShadow(&I, 0);
1537 Value *S2 = getShadow(&I, 1);
1538 Value *V1 = IRB.CreateNot(I.getOperand(0));
1539 Value *V2 = IRB.CreateNot(I.getOperand(1));
1540 if (V1->getType() != S1->getType()) {
1541 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1542 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1543 }
1544 Value *S1S2 = IRB.CreateAnd(S1, S2);
1545 Value *V1S2 = IRB.CreateAnd(V1, S2);
1546 Value *S1V2 = IRB.CreateAnd(S1, V2);
1547 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1548 setOriginForNaryOp(I);
1549 }
1550
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001551 /// \brief Default propagation of shadow and/or origin.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001552 ///
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001553 /// This class implements the general case of shadow propagation, used in all
1554 /// cases where we don't know and/or don't care about what the operation
1555 /// actually does. It converts all input shadow values to a common type
1556 /// (extending or truncating as necessary), and bitwise OR's them.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001557 ///
1558 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1559 /// fully initialized), and less prone to false positives.
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001560 ///
1561 /// This class also implements the general case of origin propagation. For a
1562 /// Nary operation, result origin is set to the origin of an argument that is
1563 /// not entirely initialized. If there is more than one such arguments, the
1564 /// rightmost of them is picked. It does not matter which one is picked if all
1565 /// arguments are initialized.
1566 template <bool CombineShadow>
1567 class Combiner {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001568 Value *Shadow = nullptr;
1569 Value *Origin = nullptr;
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001570 IRBuilder<> &IRB;
1571 MemorySanitizerVisitor *MSV;
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001572
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001573 public:
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001574 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB)
1575 : IRB(IRB), MSV(MSV) {}
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001576
1577 /// \brief Add a pair of shadow and origin values to the mix.
1578 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1579 if (CombineShadow) {
1580 assert(OpShadow);
1581 if (!Shadow)
1582 Shadow = OpShadow;
1583 else {
1584 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1585 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1586 }
1587 }
1588
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001589 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001590 assert(OpOrigin);
1591 if (!Origin) {
1592 Origin = OpOrigin;
1593 } else {
Evgeniy Stepanov70d1b0a2014-06-09 14:29:34 +00001594 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1595 // No point in adding something that might result in 0 origin value.
1596 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1597 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1598 Value *Cond =
1599 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1600 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1601 }
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001602 }
1603 }
1604 return *this;
1605 }
1606
1607 /// \brief Add an application value to the mix.
1608 Combiner &Add(Value *V) {
1609 Value *OpShadow = MSV->getShadow(V);
Craig Topperf40110f2014-04-25 05:29:35 +00001610 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001611 return Add(OpShadow, OpOrigin);
1612 }
1613
1614 /// \brief Set the current combined values as the given instruction's shadow
1615 /// and origin.
1616 void Done(Instruction *I) {
1617 if (CombineShadow) {
1618 assert(Shadow);
1619 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1620 MSV->setShadow(I, Shadow);
1621 }
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001622 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001623 assert(Origin);
1624 MSV->setOrigin(I, Origin);
1625 }
1626 }
1627 };
1628
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001629 using ShadowAndOriginCombiner = Combiner<true>;
1630 using OriginCombiner = Combiner<false>;
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001631
1632 /// \brief Propagate origin for arbitrary operation.
1633 void setOriginForNaryOp(Instruction &I) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001634 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001635 IRBuilder<> IRB(&I);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001636 OriginCombiner OC(this, IRB);
1637 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1638 OC.Add(OI->get());
1639 OC.Done(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001640 }
1641
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001642 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +00001643 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1644 "Vector of pointers is not a valid shadow type");
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001645 return Ty->isVectorTy() ?
1646 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1647 Ty->getPrimitiveSizeInBits();
1648 }
1649
1650 /// \brief Cast between two shadow types, extending or truncating as
1651 /// necessary.
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001652 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1653 bool Signed = false) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001654 Type *srcTy = V->getType();
Alexander Potapenkoa658ae82017-05-11 11:07:48 +00001655 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1656 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1657 if (srcSizeInBits > 1 && dstSizeInBits == 1)
1658 return IRB.CreateICmpNE(V, getCleanShadow(V));
1659
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001660 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001661 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001662 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1663 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001664 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001665 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1666 Value *V2 =
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001667 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001668 return IRB.CreateBitCast(V2, dstTy);
1669 // TODO: handle struct types.
1670 }
1671
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00001672 /// \brief Cast an application value to the type of its own shadow.
1673 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1674 Type *ShadowTy = getShadowTy(V);
1675 if (V->getType() == ShadowTy)
1676 return V;
1677 if (V->getType()->isPtrOrPtrVectorTy())
1678 return IRB.CreatePtrToInt(V, ShadowTy);
1679 else
1680 return IRB.CreateBitCast(V, ShadowTy);
1681 }
1682
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001683 /// \brief Propagate shadow for arbitrary operation.
1684 void handleShadowOr(Instruction &I) {
1685 IRBuilder<> IRB(&I);
1686 ShadowAndOriginCombiner SC(this, IRB);
1687 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1688 SC.Add(OI->get());
1689 SC.Done(&I);
1690 }
1691
Evgeniy Stepanovdf187fe2014-06-17 09:23:12 +00001692 // \brief Handle multiplication by constant.
1693 //
1694 // Handle a special case of multiplication by constant that may have one or
1695 // more zeros in the lower bits. This makes corresponding number of lower bits
1696 // of the result zero as well. We model it by shifting the other operand
1697 // shadow left by the required number of bits. Effectively, we transform
1698 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1699 // We use multiplication by 2**N instead of shift to cover the case of
1700 // multiplication by 0, which may occur in some elements of a vector operand.
1701 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1702 Value *OtherArg) {
1703 Constant *ShadowMul;
1704 Type *Ty = ConstArg->getType();
1705 if (Ty->isVectorTy()) {
1706 unsigned NumElements = Ty->getVectorNumElements();
1707 Type *EltTy = Ty->getSequentialElementType();
1708 SmallVector<Constant *, 16> Elements;
1709 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
Evgeniy Stepanovebd3f442015-10-14 00:21:13 +00001710 if (ConstantInt *Elt =
1711 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001712 const APInt &V = Elt->getValue();
Evgeniy Stepanovebd3f442015-10-14 00:21:13 +00001713 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1714 Elements.push_back(ConstantInt::get(EltTy, V2));
1715 } else {
1716 Elements.push_back(ConstantInt::get(EltTy, 1));
1717 }
Evgeniy Stepanovdf187fe2014-06-17 09:23:12 +00001718 }
1719 ShadowMul = ConstantVector::get(Elements);
1720 } else {
Evgeniy Stepanovebd3f442015-10-14 00:21:13 +00001721 if (ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg)) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001722 const APInt &V = Elt->getValue();
Evgeniy Stepanovebd3f442015-10-14 00:21:13 +00001723 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1724 ShadowMul = ConstantInt::get(Ty, V2);
1725 } else {
1726 ShadowMul = ConstantInt::get(Ty, 1);
1727 }
Evgeniy Stepanovdf187fe2014-06-17 09:23:12 +00001728 }
1729
1730 IRBuilder<> IRB(&I);
1731 setShadow(&I,
1732 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1733 setOrigin(&I, getOrigin(OtherArg));
1734 }
1735
1736 void visitMul(BinaryOperator &I) {
1737 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1738 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1739 if (constOp0 && !constOp1)
1740 handleMulByConstant(I, constOp0, I.getOperand(1));
1741 else if (constOp1 && !constOp0)
1742 handleMulByConstant(I, constOp1, I.getOperand(0));
1743 else
1744 handleShadowOr(I);
1745 }
1746
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001747 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1748 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1749 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1750 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1751 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1752 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001753
1754 void handleDiv(Instruction &I) {
1755 IRBuilder<> IRB(&I);
1756 // Strict on the second argument.
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001757 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001758 setShadow(&I, getShadow(&I, 0));
1759 setOrigin(&I, getOrigin(&I, 0));
1760 }
1761
1762 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1763 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1764 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1765 void visitURem(BinaryOperator &I) { handleDiv(I); }
1766 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1767 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1768
1769 /// \brief Instrument == and != comparisons.
1770 ///
1771 /// Sometimes the comparison result is known even if some of the bits of the
1772 /// arguments are not.
1773 void handleEqualityComparison(ICmpInst &I) {
1774 IRBuilder<> IRB(&I);
1775 Value *A = I.getOperand(0);
1776 Value *B = I.getOperand(1);
1777 Value *Sa = getShadow(A);
1778 Value *Sb = getShadow(B);
Evgeniy Stepanovd14e47b2013-01-15 16:44:52 +00001779
1780 // Get rid of pointers and vectors of pointers.
1781 // For ints (and vectors of ints), types of A and Sa match,
1782 // and this is a no-op.
1783 A = IRB.CreatePointerCast(A, Sa->getType());
1784 B = IRB.CreatePointerCast(B, Sb->getType());
1785
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001786 // A == B <==> (C = A^B) == 0
1787 // A != B <==> (C = A^B) != 0
1788 // Sc = Sa | Sb
1789 Value *C = IRB.CreateXor(A, B);
1790 Value *Sc = IRB.CreateOr(Sa, Sb);
1791 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1792 // Result is defined if one of the following is true
1793 // * there is a defined 1 bit in C
1794 // * C is fully defined
1795 // Si = !(C & ~Sc) && Sc
1796 Value *Zero = Constant::getNullValue(Sc->getType());
1797 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1798 Value *Si =
1799 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1800 IRB.CreateICmpEQ(
1801 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1802 Si->setName("_msprop_icmp");
1803 setShadow(&I, Si);
1804 setOriginForNaryOp(I);
1805 }
1806
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001807 /// \brief Build the lowest possible value of V, taking into account V's
1808 /// uninitialized bits.
1809 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1810 bool isSigned) {
1811 if (isSigned) {
1812 // Split shadow into sign bit and other bits.
1813 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1814 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1815 // Maximise the undefined shadow bit, minimize other undefined bits.
1816 return
1817 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1818 } else {
1819 // Minimize undefined bits.
1820 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1821 }
1822 }
1823
1824 /// \brief Build the highest possible value of V, taking into account V's
1825 /// uninitialized bits.
1826 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1827 bool isSigned) {
1828 if (isSigned) {
1829 // Split shadow into sign bit and other bits.
1830 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1831 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1832 // Minimise the undefined shadow bit, maximise other undefined bits.
1833 return
1834 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1835 } else {
1836 // Maximize undefined bits.
1837 return IRB.CreateOr(A, Sa);
1838 }
1839 }
1840
1841 /// \brief Instrument relational comparisons.
1842 ///
1843 /// This function does exact shadow propagation for all relational
1844 /// comparisons of integers, pointers and vectors of those.
1845 /// FIXME: output seems suboptimal when one of the operands is a constant
1846 void handleRelationalComparisonExact(ICmpInst &I) {
1847 IRBuilder<> IRB(&I);
1848 Value *A = I.getOperand(0);
1849 Value *B = I.getOperand(1);
1850 Value *Sa = getShadow(A);
1851 Value *Sb = getShadow(B);
1852
1853 // Get rid of pointers and vectors of pointers.
1854 // For ints (and vectors of ints), types of A and Sa match,
1855 // and this is a no-op.
1856 A = IRB.CreatePointerCast(A, Sa->getType());
1857 B = IRB.CreatePointerCast(B, Sb->getType());
1858
Evgeniy Stepanov2cb0fa12013-01-25 15:35:29 +00001859 // Let [a0, a1] be the interval of possible values of A, taking into account
1860 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1861 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001862 bool IsSigned = I.isSigned();
1863 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1864 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1865 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1866 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1867 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1868 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1869 Value *Si = IRB.CreateXor(S1, S2);
1870 setShadow(&I, Si);
1871 setOriginForNaryOp(I);
1872 }
1873
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001874 /// \brief Instrument signed relational comparisons.
1875 ///
Evgeniy Stepanovd04d07e2015-08-25 22:19:11 +00001876 /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest
1877 /// bit of the shadow. Everything else is delegated to handleShadowOr().
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001878 void handleSignedRelationalComparison(ICmpInst &I) {
Evgeniy Stepanovd04d07e2015-08-25 22:19:11 +00001879 Constant *constOp;
1880 Value *op = nullptr;
1881 CmpInst::Predicate pre;
1882 if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) {
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001883 op = I.getOperand(0);
Evgeniy Stepanovd04d07e2015-08-25 22:19:11 +00001884 pre = I.getPredicate();
1885 } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) {
1886 op = I.getOperand(1);
1887 pre = I.getSwappedPredicate();
1888 } else {
1889 handleShadowOr(I);
1890 return;
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001891 }
Evgeniy Stepanovd04d07e2015-08-25 22:19:11 +00001892
1893 if ((constOp->isNullValue() &&
1894 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) ||
1895 (constOp->isAllOnesValue() &&
1896 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) {
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001897 IRBuilder<> IRB(&I);
Evgeniy Stepanovd04d07e2015-08-25 22:19:11 +00001898 Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op),
1899 "_msprop_icmp_s");
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001900 setShadow(&I, Shadow);
1901 setOrigin(&I, getOrigin(op));
1902 } else {
1903 handleShadowOr(I);
1904 }
1905 }
1906
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001907 void visitICmpInst(ICmpInst &I) {
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001908 if (!ClHandleICmp) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001909 handleShadowOr(I);
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001910 return;
1911 }
1912 if (I.isEquality()) {
1913 handleEqualityComparison(I);
1914 return;
1915 }
1916
1917 assert(I.isRelational());
1918 if (ClHandleICmpExact) {
1919 handleRelationalComparisonExact(I);
1920 return;
1921 }
1922 if (I.isSigned()) {
1923 handleSignedRelationalComparison(I);
1924 return;
1925 }
1926
1927 assert(I.isUnsigned());
1928 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1929 handleRelationalComparisonExact(I);
1930 return;
1931 }
1932
1933 handleShadowOr(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001934 }
1935
1936 void visitFCmpInst(FCmpInst &I) {
1937 handleShadowOr(I);
1938 }
1939
1940 void handleShift(BinaryOperator &I) {
1941 IRBuilder<> IRB(&I);
1942 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1943 // Otherwise perform the same shift on S1.
1944 Value *S1 = getShadow(&I, 0);
1945 Value *S2 = getShadow(&I, 1);
1946 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1947 S2->getType());
1948 Value *V2 = I.getOperand(1);
1949 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1950 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1951 setOriginForNaryOp(I);
1952 }
1953
1954 void visitShl(BinaryOperator &I) { handleShift(I); }
1955 void visitAShr(BinaryOperator &I) { handleShift(I); }
1956 void visitLShr(BinaryOperator &I) { handleShift(I); }
1957
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001958 /// \brief Instrument llvm.memmove
1959 ///
1960 /// At this point we don't know if llvm.memmove will be inlined or not.
1961 /// If we don't instrument it and it gets inlined,
1962 /// our interceptor will not kick in and we will lose the memmove.
1963 /// If we instrument the call here, but it does not get inlined,
1964 /// we will memove the shadow twice: which is bad in case
1965 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1966 ///
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001967 /// Similar situation exists for memcpy and memset.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001968 void visitMemMoveInst(MemMoveInst &I) {
1969 IRBuilder<> IRB(&I);
David Blaikieff6409d2015-05-18 22:13:54 +00001970 IRB.CreateCall(
1971 MS.MemmoveFn,
1972 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1973 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1974 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001975 I.eraseFromParent();
1976 }
1977
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001978 // Similar to memmove: avoid copying shadow twice.
1979 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1980 // FIXME: consider doing manual inline for small constant sizes and proper
1981 // alignment.
1982 void visitMemCpyInst(MemCpyInst &I) {
1983 IRBuilder<> IRB(&I);
David Blaikieff6409d2015-05-18 22:13:54 +00001984 IRB.CreateCall(
1985 MS.MemcpyFn,
1986 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1987 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1988 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001989 I.eraseFromParent();
1990 }
1991
1992 // Same as memcpy.
1993 void visitMemSetInst(MemSetInst &I) {
1994 IRBuilder<> IRB(&I);
David Blaikieff6409d2015-05-18 22:13:54 +00001995 IRB.CreateCall(
1996 MS.MemsetFn,
1997 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1998 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1999 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00002000 I.eraseFromParent();
2001 }
2002
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002003 void visitVAStartInst(VAStartInst &I) {
2004 VAHelper->visitVAStartInst(I);
2005 }
2006
2007 void visitVACopyInst(VACopyInst &I) {
2008 VAHelper->visitVACopyInst(I);
2009 }
2010
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002011 /// \brief Handle vector store-like intrinsics.
2012 ///
2013 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
2014 /// has 1 pointer argument and 1 vector argument, returns void.
2015 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
2016 IRBuilder<> IRB(&I);
2017 Value* Addr = I.getArgOperand(0);
2018 Value *Shadow = getShadow(&I, 1);
2019 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
2020
2021 // We don't know the pointer alignment (could be unaligned SSE store!).
2022 // Have to assume to worst case.
2023 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
2024
2025 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002026 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002027
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002028 // FIXME: factor out common code from materializeStores
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002029 if (MS.TrackOrigins)
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00002030 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002031 return true;
2032 }
2033
2034 /// \brief Handle vector load-like intrinsics.
2035 ///
2036 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
2037 /// has 1 pointer argument, returns a vector.
2038 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
2039 IRBuilder<> IRB(&I);
2040 Value *Addr = I.getArgOperand(0);
2041
2042 Type *ShadowTy = getShadowTy(&I);
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00002043 if (PropagateShadow) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00002044 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
2045 // We don't know the pointer alignment (could be unaligned SSE load!).
2046 // Have to assume to worst case.
2047 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
2048 } else {
2049 setShadow(&I, getCleanShadow(&I));
2050 }
2051
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002052 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002053 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002054
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00002055 if (MS.TrackOrigins) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00002056 if (PropagateShadow)
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00002057 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00002058 else
2059 setOrigin(&I, getCleanOrigin());
2060 }
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002061 return true;
2062 }
2063
2064 /// \brief Handle (SIMD arithmetic)-like intrinsics.
2065 ///
2066 /// Instrument intrinsics with any number of arguments of the same type,
2067 /// equal to the return type. The type should be simple (no aggregates or
2068 /// pointers; vectors are fine).
2069 /// Caller guarantees that this intrinsic does not access memory.
2070 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
2071 Type *RetTy = I.getType();
2072 if (!(RetTy->isIntOrIntVectorTy() ||
2073 RetTy->isFPOrFPVectorTy() ||
2074 RetTy->isX86_MMXTy()))
2075 return false;
2076
2077 unsigned NumArgOperands = I.getNumArgOperands();
2078
2079 for (unsigned i = 0; i < NumArgOperands; ++i) {
2080 Type *Ty = I.getArgOperand(i)->getType();
2081 if (Ty != RetTy)
2082 return false;
2083 }
2084
2085 IRBuilder<> IRB(&I);
2086 ShadowAndOriginCombiner SC(this, IRB);
2087 for (unsigned i = 0; i < NumArgOperands; ++i)
2088 SC.Add(I.getArgOperand(i));
2089 SC.Done(&I);
2090
2091 return true;
2092 }
2093
2094 /// \brief Heuristically instrument unknown intrinsics.
2095 ///
2096 /// The main purpose of this code is to do something reasonable with all
2097 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
2098 /// We recognize several classes of intrinsics by their argument types and
2099 /// ModRefBehaviour and apply special intrumentation when we are reasonably
2100 /// sure that we know what the intrinsic does.
2101 ///
2102 /// We special-case intrinsics where this approach fails. See llvm.bswap
2103 /// handling as an example of that.
2104 bool handleUnknownIntrinsic(IntrinsicInst &I) {
2105 unsigned NumArgOperands = I.getNumArgOperands();
2106 if (NumArgOperands == 0)
2107 return false;
2108
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002109 if (NumArgOperands == 2 &&
2110 I.getArgOperand(0)->getType()->isPointerTy() &&
2111 I.getArgOperand(1)->getType()->isVectorTy() &&
2112 I.getType()->isVoidTy() &&
Igor Laevsky68688df2015-10-20 21:33:30 +00002113 !I.onlyReadsMemory()) {
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002114 // This looks like a vector store.
2115 return handleVectorStoreIntrinsic(I);
2116 }
2117
2118 if (NumArgOperands == 1 &&
2119 I.getArgOperand(0)->getType()->isPointerTy() &&
2120 I.getType()->isVectorTy() &&
Igor Laevsky68688df2015-10-20 21:33:30 +00002121 I.onlyReadsMemory()) {
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002122 // This looks like a vector load.
2123 return handleVectorLoadIntrinsic(I);
2124 }
2125
Igor Laevsky68688df2015-10-20 21:33:30 +00002126 if (I.doesNotAccessMemory())
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002127 if (maybeHandleSimpleNomemIntrinsic(I))
2128 return true;
2129
2130 // FIXME: detect and handle SSE maskstore/maskload
2131 return false;
2132 }
2133
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002134 void handleBswap(IntrinsicInst &I) {
2135 IRBuilder<> IRB(&I);
2136 Value *Op = I.getArgOperand(0);
2137 Type *OpType = Op->getType();
2138 Function *BswapFunc = Intrinsic::getDeclaration(
Craig Toppere1d12942014-08-27 05:25:25 +00002139 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002140 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2141 setOrigin(&I, getOrigin(Op));
2142 }
2143
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002144 // \brief Instrument vector convert instrinsic.
2145 //
2146 // This function instruments intrinsics like cvtsi2ss:
2147 // %Out = int_xxx_cvtyyy(%ConvertOp)
2148 // or
2149 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2150 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2151 // number \p Out elements, and (if has 2 arguments) copies the rest of the
2152 // elements from \p CopyOp.
2153 // In most cases conversion involves floating-point value which may trigger a
2154 // hardware exception when not fully initialized. For this reason we require
2155 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2156 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2157 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2158 // return a fully initialized value.
2159 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2160 IRBuilder<> IRB(&I);
2161 Value *CopyOp, *ConvertOp;
2162
2163 switch (I.getNumArgOperands()) {
Igor Bregerdfcc3d32015-06-17 07:23:57 +00002164 case 3:
2165 assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
Galina Kistanovae9cacb62017-06-03 05:19:32 +00002166 LLVM_FALLTHROUGH;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002167 case 2:
2168 CopyOp = I.getArgOperand(0);
2169 ConvertOp = I.getArgOperand(1);
2170 break;
2171 case 1:
2172 ConvertOp = I.getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002173 CopyOp = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002174 break;
2175 default:
2176 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2177 }
2178
2179 // The first *NumUsedElements* elements of ConvertOp are converted to the
2180 // same number of output elements. The rest of the output is copied from
2181 // CopyOp, or (if not available) filled with zeroes.
2182 // Combine shadow for elements of ConvertOp that are used in this operation,
2183 // and insert a check.
2184 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2185 // int->any conversion.
2186 Value *ConvertShadow = getShadow(ConvertOp);
Craig Topperf40110f2014-04-25 05:29:35 +00002187 Value *AggShadow = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002188 if (ConvertOp->getType()->isVectorTy()) {
2189 AggShadow = IRB.CreateExtractElement(
2190 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2191 for (int i = 1; i < NumUsedElements; ++i) {
2192 Value *MoreShadow = IRB.CreateExtractElement(
2193 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2194 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2195 }
2196 } else {
2197 AggShadow = ConvertShadow;
2198 }
2199 assert(AggShadow->getType()->isIntegerTy());
2200 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2201
2202 // Build result shadow by zero-filling parts of CopyOp shadow that come from
2203 // ConvertOp.
2204 if (CopyOp) {
2205 assert(CopyOp->getType() == I.getType());
2206 assert(CopyOp->getType()->isVectorTy());
2207 Value *ResultShadow = getShadow(CopyOp);
2208 Type *EltTy = ResultShadow->getType()->getVectorElementType();
2209 for (int i = 0; i < NumUsedElements; ++i) {
2210 ResultShadow = IRB.CreateInsertElement(
2211 ResultShadow, ConstantInt::getNullValue(EltTy),
2212 ConstantInt::get(IRB.getInt32Ty(), i));
2213 }
2214 setShadow(&I, ResultShadow);
2215 setOrigin(&I, getOrigin(CopyOp));
2216 } else {
2217 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00002218 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002219 }
2220 }
2221
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002222 // Given a scalar or vector, extract lower 64 bits (or less), and return all
2223 // zeroes if it is zero, and all ones otherwise.
2224 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2225 if (S->getType()->isVectorTy())
2226 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2227 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2228 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2229 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2230 }
2231
Evgeniy Stepanov35f3e5e2016-04-29 01:19:52 +00002232 // Given a vector, extract its first element, and return all
2233 // zeroes if it is zero, and all ones otherwise.
2234 Value *LowerElementShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
Ivan Krasin8dafa2d2016-04-29 02:09:57 +00002235 Value *S1 = IRB.CreateExtractElement(S, (uint64_t)0);
Evgeniy Stepanov35f3e5e2016-04-29 01:19:52 +00002236 Value *S2 = IRB.CreateICmpNE(S1, getCleanShadow(S1));
2237 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2238 }
2239
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002240 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2241 Type *T = S->getType();
2242 assert(T->isVectorTy());
2243 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2244 return IRB.CreateSExt(S2, T);
2245 }
2246
2247 // \brief Instrument vector shift instrinsic.
2248 //
2249 // This function instruments intrinsics like int_x86_avx2_psll_w.
2250 // Intrinsic shifts %In by %ShiftSize bits.
2251 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2252 // size, and the rest is ignored. Behavior is defined even if shift size is
2253 // greater than register (or field) width.
2254 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2255 assert(I.getNumArgOperands() == 2);
2256 IRBuilder<> IRB(&I);
2257 // If any of the S2 bits are poisoned, the whole thing is poisoned.
2258 // Otherwise perform the same shift on S1.
2259 Value *S1 = getShadow(&I, 0);
2260 Value *S2 = getShadow(&I, 1);
2261 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2262 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2263 Value *V1 = I.getOperand(0);
2264 Value *V2 = I.getOperand(1);
David Blaikieff6409d2015-05-18 22:13:54 +00002265 Value *Shift = IRB.CreateCall(I.getCalledValue(),
2266 {IRB.CreateBitCast(S1, V1->getType()), V2});
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002267 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2268 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2269 setOriginForNaryOp(I);
2270 }
2271
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002272 // \brief Get an X86_MMX-sized vector type.
2273 Type *getMMXVectorTy(unsigned EltSizeInBits) {
2274 const unsigned X86_MMXSizeInBits = 64;
2275 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2276 X86_MMXSizeInBits / EltSizeInBits);
2277 }
2278
2279 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2280 // intrinsic.
2281 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2282 switch (id) {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002283 case Intrinsic::x86_sse2_packsswb_128:
2284 case Intrinsic::x86_sse2_packuswb_128:
2285 return Intrinsic::x86_sse2_packsswb_128;
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002286
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002287 case Intrinsic::x86_sse2_packssdw_128:
2288 case Intrinsic::x86_sse41_packusdw:
2289 return Intrinsic::x86_sse2_packssdw_128;
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002290
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002291 case Intrinsic::x86_avx2_packsswb:
2292 case Intrinsic::x86_avx2_packuswb:
2293 return Intrinsic::x86_avx2_packsswb;
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002294
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002295 case Intrinsic::x86_avx2_packssdw:
2296 case Intrinsic::x86_avx2_packusdw:
2297 return Intrinsic::x86_avx2_packssdw;
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002298
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002299 case Intrinsic::x86_mmx_packsswb:
2300 case Intrinsic::x86_mmx_packuswb:
2301 return Intrinsic::x86_mmx_packsswb;
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002302
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002303 case Intrinsic::x86_mmx_packssdw:
2304 return Intrinsic::x86_mmx_packssdw;
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002305 default:
2306 llvm_unreachable("unexpected intrinsic id");
2307 }
2308 }
2309
Evgeniy Stepanov5d972932014-06-17 11:26:00 +00002310 // \brief Instrument vector pack instrinsic.
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002311 //
2312 // This function instruments intrinsics like x86_mmx_packsswb, that
Evgeniy Stepanov5d972932014-06-17 11:26:00 +00002313 // packs elements of 2 input vectors into half as many bits with saturation.
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002314 // Shadow is propagated with the signed variant of the same intrinsic applied
2315 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2316 // EltSizeInBits is used only for x86mmx arguments.
2317 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002318 assert(I.getNumArgOperands() == 2);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002319 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002320 IRBuilder<> IRB(&I);
2321 Value *S1 = getShadow(&I, 0);
2322 Value *S2 = getShadow(&I, 1);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002323 assert(isX86_MMX || S1->getType()->isVectorTy());
2324
2325 // SExt and ICmpNE below must apply to individual elements of input vectors.
2326 // In case of x86mmx arguments, cast them to appropriate vector types and
2327 // back.
2328 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2329 if (isX86_MMX) {
2330 S1 = IRB.CreateBitCast(S1, T);
2331 S2 = IRB.CreateBitCast(S2, T);
2332 }
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002333 Value *S1_ext = IRB.CreateSExt(
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002334 IRB.CreateICmpNE(S1, Constant::getNullValue(T)), T);
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002335 Value *S2_ext = IRB.CreateSExt(
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002336 IRB.CreateICmpNE(S2, Constant::getNullValue(T)), T);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002337 if (isX86_MMX) {
2338 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2339 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2340 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2341 }
2342
2343 Function *ShadowFn = Intrinsic::getDeclaration(
2344 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2345
David Blaikieff6409d2015-05-18 22:13:54 +00002346 Value *S =
2347 IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002348 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002349 setShadow(&I, S);
2350 setOriginForNaryOp(I);
2351 }
2352
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002353 // \brief Instrument sum-of-absolute-differencies intrinsic.
2354 void handleVectorSadIntrinsic(IntrinsicInst &I) {
2355 const unsigned SignificantBitsPerResultElement = 16;
2356 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2357 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2358 unsigned ZeroBitsPerResultElement =
2359 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2360
2361 IRBuilder<> IRB(&I);
2362 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2363 S = IRB.CreateBitCast(S, ResTy);
2364 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2365 ResTy);
2366 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2367 S = IRB.CreateBitCast(S, getShadowTy(&I));
2368 setShadow(&I, S);
2369 setOriginForNaryOp(I);
2370 }
2371
2372 // \brief Instrument multiply-add intrinsic.
2373 void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2374 unsigned EltSizeInBits = 0) {
2375 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2376 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2377 IRBuilder<> IRB(&I);
2378 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2379 S = IRB.CreateBitCast(S, ResTy);
2380 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2381 ResTy);
2382 S = IRB.CreateBitCast(S, getShadowTy(&I));
2383 setShadow(&I, S);
2384 setOriginForNaryOp(I);
2385 }
2386
Evgeniy Stepanov35f3e5e2016-04-29 01:19:52 +00002387 // \brief Instrument compare-packed intrinsic.
2388 // Basically, an or followed by sext(icmp ne 0) to end up with all-zeros or
2389 // all-ones shadow.
2390 void handleVectorComparePackedIntrinsic(IntrinsicInst &I) {
2391 IRBuilder<> IRB(&I);
2392 Type *ResTy = getShadowTy(&I);
2393 Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2394 Value *S = IRB.CreateSExt(
2395 IRB.CreateICmpNE(S0, Constant::getNullValue(ResTy)), ResTy);
2396 setShadow(&I, S);
2397 setOriginForNaryOp(I);
2398 }
2399
2400 // \brief Instrument compare-scalar intrinsic.
2401 // This handles both cmp* intrinsics which return the result in the first
2402 // element of a vector, and comi* which return the result as i32.
2403 void handleVectorCompareScalarIntrinsic(IntrinsicInst &I) {
2404 IRBuilder<> IRB(&I);
2405 Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2406 Value *S = LowerElementShadowExtend(IRB, S0, getShadowTy(&I));
2407 setShadow(&I, S);
2408 setOriginForNaryOp(I);
2409 }
2410
Evgeniy Stepanovd0285f22017-03-03 01:12:43 +00002411 void handleStmxcsr(IntrinsicInst &I) {
2412 IRBuilder<> IRB(&I);
2413 Value* Addr = I.getArgOperand(0);
2414 Type *Ty = IRB.getInt32Ty();
2415 Value *ShadowPtr = getShadowPtr(Addr, Ty, IRB);
2416
2417 IRB.CreateStore(getCleanShadow(Ty),
2418 IRB.CreatePointerCast(ShadowPtr, Ty->getPointerTo()));
2419
2420 if (ClCheckAccessAddress)
2421 insertShadowCheck(Addr, &I);
2422 }
2423
2424 void handleLdmxcsr(IntrinsicInst &I) {
2425 if (!InsertChecks) return;
2426
2427 IRBuilder<> IRB(&I);
2428 Value *Addr = I.getArgOperand(0);
2429 Type *Ty = IRB.getInt32Ty();
2430 unsigned Alignment = 1;
2431
2432 if (ClCheckAccessAddress)
2433 insertShadowCheck(Addr, &I);
2434
2435 Value *Shadow = IRB.CreateAlignedLoad(getShadowPtr(Addr, Ty, IRB),
2436 Alignment, "_ldmxcsr");
2437 Value *Origin = MS.TrackOrigins
2438 ? IRB.CreateLoad(getOriginPtr(Addr, IRB, Alignment))
2439 : getCleanOrigin();
2440 insertShadowCheck(Shadow, Origin, &I);
2441 }
2442
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002443 void visitIntrinsicInst(IntrinsicInst &I) {
2444 switch (I.getIntrinsicID()) {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002445 case Intrinsic::bswap:
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002446 handleBswap(I);
2447 break;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002448 case Intrinsic::x86_sse_stmxcsr:
Evgeniy Stepanovd0285f22017-03-03 01:12:43 +00002449 handleStmxcsr(I);
2450 break;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002451 case Intrinsic::x86_sse_ldmxcsr:
Evgeniy Stepanovd0285f22017-03-03 01:12:43 +00002452 handleLdmxcsr(I);
2453 break;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002454 case Intrinsic::x86_avx512_vcvtsd2usi64:
2455 case Intrinsic::x86_avx512_vcvtsd2usi32:
2456 case Intrinsic::x86_avx512_vcvtss2usi64:
2457 case Intrinsic::x86_avx512_vcvtss2usi32:
2458 case Intrinsic::x86_avx512_cvttss2usi64:
2459 case Intrinsic::x86_avx512_cvttss2usi:
2460 case Intrinsic::x86_avx512_cvttsd2usi64:
2461 case Intrinsic::x86_avx512_cvttsd2usi:
2462 case Intrinsic::x86_avx512_cvtusi2sd:
2463 case Intrinsic::x86_avx512_cvtusi2ss:
2464 case Intrinsic::x86_avx512_cvtusi642sd:
2465 case Intrinsic::x86_avx512_cvtusi642ss:
2466 case Intrinsic::x86_sse2_cvtsd2si64:
2467 case Intrinsic::x86_sse2_cvtsd2si:
2468 case Intrinsic::x86_sse2_cvtsd2ss:
2469 case Intrinsic::x86_sse2_cvtsi2sd:
2470 case Intrinsic::x86_sse2_cvtsi642sd:
2471 case Intrinsic::x86_sse2_cvtss2sd:
2472 case Intrinsic::x86_sse2_cvttsd2si64:
2473 case Intrinsic::x86_sse2_cvttsd2si:
2474 case Intrinsic::x86_sse_cvtsi2ss:
2475 case Intrinsic::x86_sse_cvtsi642ss:
2476 case Intrinsic::x86_sse_cvtss2si64:
2477 case Intrinsic::x86_sse_cvtss2si:
2478 case Intrinsic::x86_sse_cvttss2si64:
2479 case Intrinsic::x86_sse_cvttss2si:
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002480 handleVectorConvertIntrinsic(I, 1);
2481 break;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002482 case Intrinsic::x86_sse_cvtps2pi:
2483 case Intrinsic::x86_sse_cvttps2pi:
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002484 handleVectorConvertIntrinsic(I, 2);
2485 break;
Craig Topperc7486af2016-11-15 16:27:33 +00002486
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002487 case Intrinsic::x86_avx512_psll_w_512:
2488 case Intrinsic::x86_avx512_psll_d_512:
2489 case Intrinsic::x86_avx512_psll_q_512:
2490 case Intrinsic::x86_avx512_pslli_w_512:
2491 case Intrinsic::x86_avx512_pslli_d_512:
2492 case Intrinsic::x86_avx512_pslli_q_512:
2493 case Intrinsic::x86_avx512_psrl_w_512:
2494 case Intrinsic::x86_avx512_psrl_d_512:
2495 case Intrinsic::x86_avx512_psrl_q_512:
2496 case Intrinsic::x86_avx512_psra_w_512:
2497 case Intrinsic::x86_avx512_psra_d_512:
2498 case Intrinsic::x86_avx512_psra_q_512:
2499 case Intrinsic::x86_avx512_psrli_w_512:
2500 case Intrinsic::x86_avx512_psrli_d_512:
2501 case Intrinsic::x86_avx512_psrli_q_512:
2502 case Intrinsic::x86_avx512_psrai_w_512:
2503 case Intrinsic::x86_avx512_psrai_d_512:
2504 case Intrinsic::x86_avx512_psrai_q_512:
2505 case Intrinsic::x86_avx512_psra_q_256:
2506 case Intrinsic::x86_avx512_psra_q_128:
2507 case Intrinsic::x86_avx512_psrai_q_256:
2508 case Intrinsic::x86_avx512_psrai_q_128:
2509 case Intrinsic::x86_avx2_psll_w:
2510 case Intrinsic::x86_avx2_psll_d:
2511 case Intrinsic::x86_avx2_psll_q:
2512 case Intrinsic::x86_avx2_pslli_w:
2513 case Intrinsic::x86_avx2_pslli_d:
2514 case Intrinsic::x86_avx2_pslli_q:
2515 case Intrinsic::x86_avx2_psrl_w:
2516 case Intrinsic::x86_avx2_psrl_d:
2517 case Intrinsic::x86_avx2_psrl_q:
2518 case Intrinsic::x86_avx2_psra_w:
2519 case Intrinsic::x86_avx2_psra_d:
2520 case Intrinsic::x86_avx2_psrli_w:
2521 case Intrinsic::x86_avx2_psrli_d:
2522 case Intrinsic::x86_avx2_psrli_q:
2523 case Intrinsic::x86_avx2_psrai_w:
2524 case Intrinsic::x86_avx2_psrai_d:
2525 case Intrinsic::x86_sse2_psll_w:
2526 case Intrinsic::x86_sse2_psll_d:
2527 case Intrinsic::x86_sse2_psll_q:
2528 case Intrinsic::x86_sse2_pslli_w:
2529 case Intrinsic::x86_sse2_pslli_d:
2530 case Intrinsic::x86_sse2_pslli_q:
2531 case Intrinsic::x86_sse2_psrl_w:
2532 case Intrinsic::x86_sse2_psrl_d:
2533 case Intrinsic::x86_sse2_psrl_q:
2534 case Intrinsic::x86_sse2_psra_w:
2535 case Intrinsic::x86_sse2_psra_d:
2536 case Intrinsic::x86_sse2_psrli_w:
2537 case Intrinsic::x86_sse2_psrli_d:
2538 case Intrinsic::x86_sse2_psrli_q:
2539 case Intrinsic::x86_sse2_psrai_w:
2540 case Intrinsic::x86_sse2_psrai_d:
2541 case Intrinsic::x86_mmx_psll_w:
2542 case Intrinsic::x86_mmx_psll_d:
2543 case Intrinsic::x86_mmx_psll_q:
2544 case Intrinsic::x86_mmx_pslli_w:
2545 case Intrinsic::x86_mmx_pslli_d:
2546 case Intrinsic::x86_mmx_pslli_q:
2547 case Intrinsic::x86_mmx_psrl_w:
2548 case Intrinsic::x86_mmx_psrl_d:
2549 case Intrinsic::x86_mmx_psrl_q:
2550 case Intrinsic::x86_mmx_psra_w:
2551 case Intrinsic::x86_mmx_psra_d:
2552 case Intrinsic::x86_mmx_psrli_w:
2553 case Intrinsic::x86_mmx_psrli_d:
2554 case Intrinsic::x86_mmx_psrli_q:
2555 case Intrinsic::x86_mmx_psrai_w:
2556 case Intrinsic::x86_mmx_psrai_d:
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002557 handleVectorShiftIntrinsic(I, /* Variable */ false);
2558 break;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002559 case Intrinsic::x86_avx2_psllv_d:
2560 case Intrinsic::x86_avx2_psllv_d_256:
2561 case Intrinsic::x86_avx512_psllv_d_512:
2562 case Intrinsic::x86_avx2_psllv_q:
2563 case Intrinsic::x86_avx2_psllv_q_256:
2564 case Intrinsic::x86_avx512_psllv_q_512:
2565 case Intrinsic::x86_avx2_psrlv_d:
2566 case Intrinsic::x86_avx2_psrlv_d_256:
2567 case Intrinsic::x86_avx512_psrlv_d_512:
2568 case Intrinsic::x86_avx2_psrlv_q:
2569 case Intrinsic::x86_avx2_psrlv_q_256:
2570 case Intrinsic::x86_avx512_psrlv_q_512:
2571 case Intrinsic::x86_avx2_psrav_d:
2572 case Intrinsic::x86_avx2_psrav_d_256:
2573 case Intrinsic::x86_avx512_psrav_d_512:
2574 case Intrinsic::x86_avx512_psrav_q_128:
2575 case Intrinsic::x86_avx512_psrav_q_256:
2576 case Intrinsic::x86_avx512_psrav_q_512:
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002577 handleVectorShiftIntrinsic(I, /* Variable */ true);
2578 break;
2579
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002580 case Intrinsic::x86_sse2_packsswb_128:
2581 case Intrinsic::x86_sse2_packssdw_128:
2582 case Intrinsic::x86_sse2_packuswb_128:
2583 case Intrinsic::x86_sse41_packusdw:
2584 case Intrinsic::x86_avx2_packsswb:
2585 case Intrinsic::x86_avx2_packssdw:
2586 case Intrinsic::x86_avx2_packuswb:
2587 case Intrinsic::x86_avx2_packusdw:
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002588 handleVectorPackIntrinsic(I);
2589 break;
2590
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002591 case Intrinsic::x86_mmx_packsswb:
2592 case Intrinsic::x86_mmx_packuswb:
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002593 handleVectorPackIntrinsic(I, 16);
2594 break;
2595
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002596 case Intrinsic::x86_mmx_packssdw:
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002597 handleVectorPackIntrinsic(I, 32);
2598 break;
2599
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002600 case Intrinsic::x86_mmx_psad_bw:
2601 case Intrinsic::x86_sse2_psad_bw:
2602 case Intrinsic::x86_avx2_psad_bw:
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002603 handleVectorSadIntrinsic(I);
2604 break;
2605
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002606 case Intrinsic::x86_sse2_pmadd_wd:
2607 case Intrinsic::x86_avx2_pmadd_wd:
2608 case Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2609 case Intrinsic::x86_avx2_pmadd_ub_sw:
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002610 handleVectorPmaddIntrinsic(I);
2611 break;
2612
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002613 case Intrinsic::x86_ssse3_pmadd_ub_sw:
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002614 handleVectorPmaddIntrinsic(I, 8);
2615 break;
2616
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002617 case Intrinsic::x86_mmx_pmadd_wd:
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002618 handleVectorPmaddIntrinsic(I, 16);
2619 break;
2620
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002621 case Intrinsic::x86_sse_cmp_ss:
2622 case Intrinsic::x86_sse2_cmp_sd:
2623 case Intrinsic::x86_sse_comieq_ss:
2624 case Intrinsic::x86_sse_comilt_ss:
2625 case Intrinsic::x86_sse_comile_ss:
2626 case Intrinsic::x86_sse_comigt_ss:
2627 case Intrinsic::x86_sse_comige_ss:
2628 case Intrinsic::x86_sse_comineq_ss:
2629 case Intrinsic::x86_sse_ucomieq_ss:
2630 case Intrinsic::x86_sse_ucomilt_ss:
2631 case Intrinsic::x86_sse_ucomile_ss:
2632 case Intrinsic::x86_sse_ucomigt_ss:
2633 case Intrinsic::x86_sse_ucomige_ss:
2634 case Intrinsic::x86_sse_ucomineq_ss:
2635 case Intrinsic::x86_sse2_comieq_sd:
2636 case Intrinsic::x86_sse2_comilt_sd:
2637 case Intrinsic::x86_sse2_comile_sd:
2638 case Intrinsic::x86_sse2_comigt_sd:
2639 case Intrinsic::x86_sse2_comige_sd:
2640 case Intrinsic::x86_sse2_comineq_sd:
2641 case Intrinsic::x86_sse2_ucomieq_sd:
2642 case Intrinsic::x86_sse2_ucomilt_sd:
2643 case Intrinsic::x86_sse2_ucomile_sd:
2644 case Intrinsic::x86_sse2_ucomigt_sd:
2645 case Intrinsic::x86_sse2_ucomige_sd:
2646 case Intrinsic::x86_sse2_ucomineq_sd:
Evgeniy Stepanov35f3e5e2016-04-29 01:19:52 +00002647 handleVectorCompareScalarIntrinsic(I);
2648 break;
2649
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00002650 case Intrinsic::x86_sse_cmp_ps:
2651 case Intrinsic::x86_sse2_cmp_pd:
Evgeniy Stepanov35f3e5e2016-04-29 01:19:52 +00002652 // FIXME: For x86_avx_cmp_pd_256 and x86_avx_cmp_ps_256 this function
2653 // generates reasonably looking IR that fails in the backend with "Do not
2654 // know how to split the result of this operator!".
2655 handleVectorComparePackedIntrinsic(I);
2656 break;
2657
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002658 default:
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002659 if (!handleUnknownIntrinsic(I))
2660 visitInstruction(I);
Evgeniy Stepanov88b8dce2012-12-17 16:30:05 +00002661 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002662 }
2663 }
2664
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002665 void visitCallSite(CallSite CS) {
2666 Instruction &I = *CS.getInstruction();
Vitaly Buka8000f222017-11-20 23:37:56 +00002667 assert(!I.getMetadata("nosanitize"));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002668 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2669 if (CS.isCall()) {
Evgeniy Stepanov7ad7e832012-11-29 14:32:03 +00002670 CallInst *Call = cast<CallInst>(&I);
2671
2672 // For inline asm, do the usual thing: check argument shadow and mark all
2673 // outputs as clean. Note that any side effects of the inline asm that are
2674 // not immediately visible in its constraints are not handled.
2675 if (Call->isInlineAsm()) {
2676 visitInstruction(I);
2677 return;
2678 }
2679
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002680 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002681
2682 // We are going to insert code that relies on the fact that the callee
2683 // will become a non-readonly function after it is instrumented by us. To
2684 // prevent this code from being optimized out, mark that function
2685 // non-readonly in advance.
2686 if (Function *Func = Call->getCalledFunction()) {
2687 // Clear out readonly/readnone attributes.
2688 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002689 B.addAttribute(Attribute::ReadOnly)
2690 .addAttribute(Attribute::ReadNone);
Reid Kleckneree4930b2017-05-02 22:07:37 +00002691 Func->removeAttributes(AttributeList::FunctionIndex, B);
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002692 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002693
2694 maybeMarkSanitizerLibraryCallNoBuiltin(Call, TLI);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002695 }
2696 IRBuilder<> IRB(&I);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002697
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002698 unsigned ArgOffset = 0;
2699 DEBUG(dbgs() << " CallSite: " << I << "\n");
2700 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2701 ArgIt != End; ++ArgIt) {
2702 Value *A = *ArgIt;
2703 unsigned i = ArgIt - CS.arg_begin();
2704 if (!A->getType()->isSized()) {
2705 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2706 continue;
2707 }
2708 unsigned Size = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00002709 Value *Store = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002710 // Compute the Shadow for arg even if it is ByVal, because
2711 // in that case getShadow() will copy the actual arg shadow to
2712 // __msan_param_tls.
2713 Value *ArgShadow = getShadow(A);
2714 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2715 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2716 " Shadow: " << *ArgShadow << "\n");
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002717 bool ArgIsInitialized = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002718 const DataLayout &DL = F.getParent()->getDataLayout();
Reid Klecknerfb502d22017-04-14 20:19:02 +00002719 if (CS.paramHasAttr(i, Attribute::ByVal)) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002720 assert(A->getType()->isPointerTy() &&
2721 "ByVal argument is not a pointer!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002722 Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00002723 if (ArgOffset + Size > kParamTLSSize) break;
Reid Kleckner859f8b52017-04-28 20:34:27 +00002724 unsigned ParamAlignment = CS.getParamAlignment(i);
Evgeniy Stepanove08633e2014-10-17 23:29:44 +00002725 unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002726 Store = IRB.CreateMemCpy(ArgShadowBase,
2727 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002728 Size, Alignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002729 } else {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002730 Size = DL.getTypeAllocSize(A->getType());
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00002731 if (ArgOffset + Size > kParamTLSSize) break;
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002732 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2733 kShadowTLSAlignment);
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002734 Constant *Cst = dyn_cast<Constant>(ArgShadow);
2735 if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002736 }
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002737 if (MS.TrackOrigins && !ArgIsInitialized)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +00002738 IRB.CreateStore(getOrigin(A),
2739 getOriginPtrForArgument(A, IRB, ArgOffset));
Edwin Vane82f80d42013-01-29 17:42:24 +00002740 (void)Store;
Craig Toppere73658d2014-04-28 04:05:08 +00002741 assert(Size != 0 && Store != nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002742 DEBUG(dbgs() << " Param:" << *Store << "\n");
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002743 ArgOffset += alignTo(Size, 8);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002744 }
2745 DEBUG(dbgs() << " done with call args\n");
2746
2747 FunctionType *FT =
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002748 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002749 if (FT->isVarArg()) {
2750 VAHelper->visitCallSite(CS, IRB);
2751 }
2752
2753 // Now, get the shadow for the RetVal.
2754 if (!I.getType()->isSized()) return;
Evgeniy Stepanov24ac55d2015-08-14 22:03:50 +00002755 // Don't emit the epilogue for musttail call returns.
2756 if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002757 IRBuilder<> IRBBefore(&I);
Alp Tokercb402912014-01-24 17:20:08 +00002758 // Until we have full dynamic coverage, make sure the retval shadow is 0.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002759 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002760 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002761 BasicBlock::iterator NextInsn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002762 if (CS.isCall()) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002763 NextInsn = ++I.getIterator();
2764 assert(NextInsn != I.getParent()->end());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002765 } else {
2766 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2767 if (!NormalDest->getSinglePredecessor()) {
2768 // FIXME: this case is tricky, so we are just conservative here.
2769 // Perhaps we need to split the edge between this BB and NormalDest,
2770 // but a naive attempt to use SplitEdge leads to a crash.
2771 setShadow(&I, getCleanShadow(&I));
2772 setOrigin(&I, getCleanOrigin());
2773 return;
2774 }
Evgeniy Stepanov4a8d1512017-12-04 22:50:39 +00002775 // FIXME: NextInsn is likely in a basic block that has not been visited yet.
2776 // Anything inserted there will be instrumented by MSan later!
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002777 NextInsn = NormalDest->getFirstInsertionPt();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002778 assert(NextInsn != NormalDest->end() &&
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002779 "Could not find insertion point for retval shadow load");
2780 }
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002781 IRBuilder<> IRBAfter(&*NextInsn);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002782 Value *RetvalShadow =
2783 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2784 kShadowTLSAlignment, "_msret");
2785 setShadow(&I, RetvalShadow);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002786 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002787 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2788 }
2789
Evgeniy Stepanov24ac55d2015-08-14 22:03:50 +00002790 bool isAMustTailRetVal(Value *RetVal) {
2791 if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
2792 RetVal = I->getOperand(0);
2793 }
2794 if (auto *I = dyn_cast<CallInst>(RetVal)) {
2795 return I->isMustTailCall();
2796 }
2797 return false;
2798 }
2799
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002800 void visitReturnInst(ReturnInst &I) {
2801 IRBuilder<> IRB(&I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002802 Value *RetVal = I.getReturnValue();
2803 if (!RetVal) return;
Evgeniy Stepanov24ac55d2015-08-14 22:03:50 +00002804 // Don't emit the epilogue for musttail call returns.
2805 if (isAMustTailRetVal(RetVal)) return;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002806 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2807 if (CheckReturnValue) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002808 insertShadowCheck(RetVal, &I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002809 Value *Shadow = getCleanShadow(RetVal);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002810 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002811 } else {
2812 Value *Shadow = getShadow(RetVal);
2813 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002814 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002815 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2816 }
2817 }
2818
2819 void visitPHINode(PHINode &I) {
2820 IRBuilder<> IRB(&I);
Evgeniy Stepanovd948a5f2014-07-07 13:28:31 +00002821 if (!PropagateShadow) {
2822 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00002823 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanovd948a5f2014-07-07 13:28:31 +00002824 return;
2825 }
2826
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002827 ShadowPHINodes.push_back(&I);
2828 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2829 "_msphi_s"));
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002830 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002831 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2832 "_msphi_o"));
2833 }
2834
2835 void visitAllocaInst(AllocaInst &I) {
2836 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00002837 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002838 IRBuilder<> IRB(I.getNextNode());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002839 const DataLayout &DL = F.getParent()->getDataLayout();
Evgeniy Stepanovd1daf632017-02-24 00:13:17 +00002840 uint64_t TypeSize = DL.getTypeAllocSize(I.getAllocatedType());
2841 Value *Len = ConstantInt::get(MS.IntptrTy, TypeSize);
2842 if (I.isArrayAllocation())
2843 Len = IRB.CreateMul(Len, I.getArraySize());
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002844 if (PoisonStack && ClPoisonStackWithCall) {
David Blaikieff6409d2015-05-18 22:13:54 +00002845 IRB.CreateCall(MS.MsanPoisonStackFn,
Evgeniy Stepanovd1daf632017-02-24 00:13:17 +00002846 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002847 } else {
2848 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002849 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
Evgeniy Stepanovd1daf632017-02-24 00:13:17 +00002850 IRB.CreateMemSet(ShadowBase, PoisonValue, Len, I.getAlignment());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002851 }
2852
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002853 if (PoisonStack && MS.TrackOrigins) {
Alp Tokere69170a2014-06-26 22:52:05 +00002854 SmallString<2048> StackDescriptionStorage;
2855 raw_svector_ostream StackDescription(StackDescriptionStorage);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002856 // We create a string with a description of the stack allocation and
2857 // pass it into __msan_set_alloca_origin.
2858 // It will be printed by the run-time if stack-originated UMR is found.
2859 // The first 4 bytes of the string are set to '----' and will be replaced
2860 // by __msan_va_arg_overflow_size_tls at the first call.
2861 StackDescription << "----" << I.getName() << "@" << F.getName();
2862 Value *Descr =
2863 createPrivateNonConstGlobalForString(*F.getParent(),
2864 StackDescription.str());
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002865
David Blaikieff6409d2015-05-18 22:13:54 +00002866 IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
Evgeniy Stepanovd1daf632017-02-24 00:13:17 +00002867 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len,
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002868 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
David Blaikieff6409d2015-05-18 22:13:54 +00002869 IRB.CreatePointerCast(&F, MS.IntptrTy)});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002870 }
2871 }
2872
2873 void visitSelectInst(SelectInst& I) {
2874 IRBuilder<> IRB(&I);
Evgeniy Stepanov566f5912013-09-03 10:04:11 +00002875 // a = select b, c, d
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002876 Value *B = I.getCondition();
2877 Value *C = I.getTrueValue();
2878 Value *D = I.getFalseValue();
2879 Value *Sb = getShadow(B);
2880 Value *Sc = getShadow(C);
2881 Value *Sd = getShadow(D);
2882
2883 // Result shadow if condition shadow is 0.
2884 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2885 Value *Sa1;
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002886 if (I.getType()->isAggregateType()) {
2887 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2888 // an extra "select". This results in much more compact IR.
2889 // Sa = select Sb, poisoned, (select b, Sc, Sd)
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002890 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002891 } else {
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002892 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2893 // If Sb (condition is poisoned), look for bits in c and d that are equal
2894 // and both unpoisoned.
2895 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2896
2897 // Cast arguments to shadow-compatible type.
2898 C = CreateAppToShadowCast(IRB, C);
2899 D = CreateAppToShadowCast(IRB, D);
2900
2901 // Result shadow if condition shadow is 1.
2902 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002903 }
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002904 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2905 setShadow(&I, Sa);
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002906 if (MS.TrackOrigins) {
2907 // Origins are always i32, so any vector conditions must be flattened.
2908 // FIXME: consider tracking vector origins for app vectors?
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002909 if (B->getType()->isVectorTy()) {
2910 Type *FlatTy = getShadowTyNoVec(B->getType());
2911 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002912 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002913 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002914 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002915 }
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002916 // a = select b, c, d
2917 // Oa = Sb ? Ob : (b ? Oc : Od)
Evgeniy Stepanova0b68992014-11-28 11:17:58 +00002918 setOrigin(
2919 &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2920 IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2921 getOrigin(I.getFalseValue()))));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002922 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002923 }
2924
2925 void visitLandingPadInst(LandingPadInst &I) {
2926 // Do nothing.
Hans Wennborg08b34a02017-11-13 23:47:58 +00002927 // See https://github.com/google/sanitizers/issues/504
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002928 setShadow(&I, getCleanShadow(&I));
2929 setOrigin(&I, getCleanOrigin());
2930 }
2931
David Majnemer8a1c45d2015-12-12 05:38:55 +00002932 void visitCatchSwitchInst(CatchSwitchInst &I) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002933 setShadow(&I, getCleanShadow(&I));
2934 setOrigin(&I, getCleanOrigin());
David Majnemer654e1302015-07-31 17:58:14 +00002935 }
2936
David Majnemer8a1c45d2015-12-12 05:38:55 +00002937 void visitFuncletPadInst(FuncletPadInst &I) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002938 setShadow(&I, getCleanShadow(&I));
2939 setOrigin(&I, getCleanOrigin());
David Majnemer654e1302015-07-31 17:58:14 +00002940 }
2941
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002942 void visitGetElementPtrInst(GetElementPtrInst &I) {
2943 handleShadowOr(I);
2944 }
2945
2946 void visitExtractValueInst(ExtractValueInst &I) {
2947 IRBuilder<> IRB(&I);
2948 Value *Agg = I.getAggregateOperand();
2949 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2950 Value *AggShadow = getShadow(Agg);
2951 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2952 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2953 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2954 setShadow(&I, ResShadow);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002955 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002956 }
2957
2958 void visitInsertValueInst(InsertValueInst &I) {
2959 IRBuilder<> IRB(&I);
2960 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2961 Value *AggShadow = getShadow(I.getAggregateOperand());
2962 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2963 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2964 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2965 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2966 DEBUG(dbgs() << " Res: " << *Res << "\n");
2967 setShadow(&I, Res);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002968 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002969 }
2970
2971 void dumpInst(Instruction &I) {
2972 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2973 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2974 } else {
2975 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2976 }
2977 errs() << "QQQ " << I << "\n";
2978 }
2979
2980 void visitResumeInst(ResumeInst &I) {
2981 DEBUG(dbgs() << "Resume: " << I << "\n");
2982 // Nothing to do here.
2983 }
2984
David Majnemer654e1302015-07-31 17:58:14 +00002985 void visitCleanupReturnInst(CleanupReturnInst &CRI) {
2986 DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
2987 // Nothing to do here.
2988 }
2989
2990 void visitCatchReturnInst(CatchReturnInst &CRI) {
2991 DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
2992 // Nothing to do here.
2993 }
2994
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002995 void visitInstruction(Instruction &I) {
2996 // Everything else: stop propagating and check for poisoned shadow.
2997 if (ClDumpStrictInstructions)
2998 dumpInst(I);
2999 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
Evgeniy Stepanov3d5ea712017-07-11 18:13:52 +00003000 for (size_t i = 0, n = I.getNumOperands(); i < n; i++) {
3001 Value *Operand = I.getOperand(i);
3002 if (Operand->getType()->isSized())
3003 insertShadowCheck(Operand, &I);
3004 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003005 setShadow(&I, getCleanShadow(&I));
3006 setOrigin(&I, getCleanOrigin());
3007 }
3008};
3009
3010/// \brief AMD64-specific implementation of VarArgHelper.
3011struct VarArgAMD64Helper : public VarArgHelper {
3012 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
3013 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00003014 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003015 static const unsigned AMD64FpEndOffset = 176;
3016
3017 Function &F;
3018 MemorySanitizer &MS;
3019 MemorySanitizerVisitor &MSV;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003020 Value *VAArgTLSCopy = nullptr;
3021 Value *VAArgOverflowSize = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003022
3023 SmallVector<CallInst*, 16> VAStartInstrumentationList;
3024
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003025 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
3026
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003027 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
3028 MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
3029
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003030 ArgKind classifyArgument(Value* arg) {
3031 // A very rough approximation of X86_64 argument classification rules.
3032 Type *T = arg->getType();
3033 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
3034 return AK_FloatingPoint;
3035 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
3036 return AK_GeneralPurpose;
3037 if (T->isPointerTy())
3038 return AK_GeneralPurpose;
3039 return AK_Memory;
3040 }
3041
3042 // For VarArg functions, store the argument shadow in an ABI-specific format
3043 // that corresponds to va_list layout.
3044 // We do this because Clang lowers va_arg in the frontend, and this pass
3045 // only sees the low level code that deals with va_list internals.
3046 // A much easier alternative (provided that Clang emits va_arg instructions)
3047 // would have been to associate each live instance of va_list with a copy of
3048 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
3049 // order.
Craig Topper3e4c6972014-03-05 09:10:37 +00003050 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003051 unsigned GpOffset = 0;
3052 unsigned FpOffset = AMD64GpEndOffset;
3053 unsigned OverflowOffset = AMD64FpEndOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003054 const DataLayout &DL = F.getParent()->getDataLayout();
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003055 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
3056 ArgIt != End; ++ArgIt) {
3057 Value *A = *ArgIt;
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003058 unsigned ArgNo = CS.getArgumentNo(ArgIt);
Marcin Koscielnickib088ad12016-05-06 19:36:56 +00003059 bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
Reid Klecknerfb502d22017-04-14 20:19:02 +00003060 bool IsByVal = CS.paramHasAttr(ArgNo, Attribute::ByVal);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003061 if (IsByVal) {
3062 // ByVal arguments always go to the overflow area.
Marcin Koscielnickib088ad12016-05-06 19:36:56 +00003063 // Fixed arguments passed through the overflow area will be stepped
3064 // over by va_start, so don't count them towards the offset.
3065 if (IsFixed)
3066 continue;
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003067 assert(A->getType()->isPointerTy());
3068 Type *RealTy = A->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003069 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003070 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003071 OverflowOffset += alignTo(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003072 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
Pete Cooper67cf9a72015-11-19 05:56:52 +00003073 ArgSize, kShadowTLSAlignment);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003074 } else {
3075 ArgKind AK = classifyArgument(A);
3076 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
3077 AK = AK_Memory;
3078 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
3079 AK = AK_Memory;
3080 Value *Base;
3081 switch (AK) {
3082 case AK_GeneralPurpose:
3083 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
3084 GpOffset += 8;
3085 break;
3086 case AK_FloatingPoint:
3087 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
3088 FpOffset += 16;
3089 break;
3090 case AK_Memory:
Marcin Koscielnickib088ad12016-05-06 19:36:56 +00003091 if (IsFixed)
3092 continue;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003093 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003094 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003095 OverflowOffset += alignTo(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003096 }
Marcin Koscielnickib088ad12016-05-06 19:36:56 +00003097 // Take fixed arguments into account for GpOffset and FpOffset,
3098 // but don't actually store shadows for them.
3099 if (IsFixed)
3100 continue;
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003101 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003102 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003103 }
3104 Constant *OverflowSize =
3105 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
3106 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
3107 }
3108
3109 /// \brief Compute the shadow address for a given va_arg.
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003110 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003111 int ArgOffset) {
3112 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3113 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00003114 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003115 "_msarg");
3116 }
3117
Craig Topper3e4c6972014-03-05 09:10:37 +00003118 void visitVAStartInst(VAStartInst &I) override {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003119 if (F.getCallingConv() == CallingConv::Win64)
Charles Davis11952592015-08-25 23:27:41 +00003120 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003121 IRBuilder<> IRB(&I);
3122 VAStartInstrumentationList.push_back(&I);
3123 Value *VAListTag = I.getArgOperand(0);
3124 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3125
3126 // Unpoison the whole __va_list_tag.
3127 // FIXME: magic ABI constants.
3128 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00003129 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003130 }
3131
Craig Topper3e4c6972014-03-05 09:10:37 +00003132 void visitVACopyInst(VACopyInst &I) override {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003133 if (F.getCallingConv() == CallingConv::Win64)
Charles Davis11952592015-08-25 23:27:41 +00003134 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003135 IRBuilder<> IRB(&I);
3136 Value *VAListTag = I.getArgOperand(0);
3137 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3138
3139 // Unpoison the whole __va_list_tag.
3140 // FIXME: magic ABI constants.
3141 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00003142 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003143 }
3144
Craig Topper3e4c6972014-03-05 09:10:37 +00003145 void finalizeInstrumentation() override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003146 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
3147 "finalizeInstrumentation called twice");
3148 if (!VAStartInstrumentationList.empty()) {
3149 // If there is a va_start in this function, make a backup copy of
3150 // va_arg_tls somewhere in the function entry block.
3151 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
3152 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3153 Value *CopySize =
3154 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
3155 VAArgOverflowSize);
3156 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
Pete Cooper67cf9a72015-11-19 05:56:52 +00003157 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003158 }
3159
3160 // Instrument va_start.
3161 // Copy va_list shadow from the backup copy of the TLS contents.
3162 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3163 CallInst *OrigInst = VAStartInstrumentationList[i];
3164 IRBuilder<> IRB(OrigInst->getNextNode());
3165 Value *VAListTag = OrigInst->getArgOperand(0);
3166
3167 Value *RegSaveAreaPtrPtr =
3168 IRB.CreateIntToPtr(
3169 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3170 ConstantInt::get(MS.IntptrTy, 16)),
3171 Type::getInt64PtrTy(*MS.C));
3172 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3173 Value *RegSaveAreaShadowPtr =
3174 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
3175 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
Pete Cooper67cf9a72015-11-19 05:56:52 +00003176 AMD64FpEndOffset, 16);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003177
3178 Value *OverflowArgAreaPtrPtr =
3179 IRB.CreateIntToPtr(
3180 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3181 ConstantInt::get(MS.IntptrTy, 8)),
3182 Type::getInt64PtrTy(*MS.C));
3183 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
3184 Value *OverflowArgAreaShadowPtr =
3185 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
David Blaikie95d3e532015-04-03 23:03:54 +00003186 Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
3187 AMD64FpEndOffset);
Pete Cooper67cf9a72015-11-19 05:56:52 +00003188 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003189 }
3190 }
3191};
3192
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003193/// \brief MIPS64-specific implementation of VarArgHelper.
3194struct VarArgMIPS64Helper : public VarArgHelper {
3195 Function &F;
3196 MemorySanitizer &MS;
3197 MemorySanitizerVisitor &MSV;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003198 Value *VAArgTLSCopy = nullptr;
3199 Value *VAArgSize = nullptr;
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003200
3201 SmallVector<CallInst*, 16> VAStartInstrumentationList;
3202
3203 VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003204 MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003205
3206 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
3207 unsigned VAArgOffset = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003208 const DataLayout &DL = F.getParent()->getDataLayout();
Marcin Koscielnicki60061c22016-05-05 20:13:17 +00003209 for (CallSite::arg_iterator ArgIt = CS.arg_begin() +
3210 CS.getFunctionType()->getNumParams(), End = CS.arg_end();
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003211 ArgIt != End; ++ArgIt) {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003212 Triple TargetTriple(F.getParent()->getTargetTriple());
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003213 Value *A = *ArgIt;
3214 Value *Base;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003215 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003216 if (TargetTriple.getArch() == Triple::mips64) {
Marcin Koscielnickief2e7b42016-04-19 23:46:59 +00003217 // Adjusting the shadow for argument with size < 8 to match the placement
3218 // of bits in big endian system
3219 if (ArgSize < 8)
3220 VAArgOffset += (8 - ArgSize);
3221 }
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003222 Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
3223 VAArgOffset += ArgSize;
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003224 VAArgOffset = alignTo(VAArgOffset, 8);
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003225 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
3226 }
3227
3228 Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
3229 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
3230 // a new class member i.e. it is the total size of all VarArgs.
3231 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
3232 }
3233
3234 /// \brief Compute the shadow address for a given va_arg.
3235 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3236 int ArgOffset) {
3237 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3238 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3239 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3240 "_msarg");
3241 }
3242
3243 void visitVAStartInst(VAStartInst &I) override {
3244 IRBuilder<> IRB(&I);
3245 VAStartInstrumentationList.push_back(&I);
3246 Value *VAListTag = I.getArgOperand(0);
3247 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3248 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3249 /* size */8, /* alignment */8, false);
3250 }
3251
3252 void visitVACopyInst(VACopyInst &I) override {
3253 IRBuilder<> IRB(&I);
3254 Value *VAListTag = I.getArgOperand(0);
3255 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3256 // Unpoison the whole __va_list_tag.
3257 // FIXME: magic ABI constants.
3258 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3259 /* size */8, /* alignment */8, false);
3260 }
3261
3262 void finalizeInstrumentation() override {
3263 assert(!VAArgSize && !VAArgTLSCopy &&
3264 "finalizeInstrumentation called twice");
3265 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
3266 VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3267 Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
3268 VAArgSize);
3269
3270 if (!VAStartInstrumentationList.empty()) {
3271 // If there is a va_start in this function, make a backup copy of
3272 // va_arg_tls somewhere in the function entry block.
3273 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
Pete Cooper67cf9a72015-11-19 05:56:52 +00003274 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003275 }
3276
3277 // Instrument va_start.
3278 // Copy va_list shadow from the backup copy of the TLS contents.
3279 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3280 CallInst *OrigInst = VAStartInstrumentationList[i];
3281 IRBuilder<> IRB(OrigInst->getNextNode());
3282 Value *VAListTag = OrigInst->getArgOperand(0);
3283 Value *RegSaveAreaPtrPtr =
3284 IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3285 Type::getInt64PtrTy(*MS.C));
3286 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3287 Value *RegSaveAreaShadowPtr =
3288 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
Pete Cooper67cf9a72015-11-19 05:56:52 +00003289 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003290 }
3291 }
3292};
3293
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003294/// \brief AArch64-specific implementation of VarArgHelper.
3295struct VarArgAArch64Helper : public VarArgHelper {
Marcin Koscielnicki60b3cbe2016-05-09 20:57:36 +00003296 static const unsigned kAArch64GrArgSize = 64;
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003297 static const unsigned kAArch64VrArgSize = 128;
3298
3299 static const unsigned AArch64GrBegOffset = 0;
3300 static const unsigned AArch64GrEndOffset = kAArch64GrArgSize;
3301 // Make VR space aligned to 16 bytes.
Marcin Koscielnicki60b3cbe2016-05-09 20:57:36 +00003302 static const unsigned AArch64VrBegOffset = AArch64GrEndOffset;
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003303 static const unsigned AArch64VrEndOffset = AArch64VrBegOffset
3304 + kAArch64VrArgSize;
3305 static const unsigned AArch64VAEndOffset = AArch64VrEndOffset;
3306
3307 Function &F;
3308 MemorySanitizer &MS;
3309 MemorySanitizerVisitor &MSV;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003310 Value *VAArgTLSCopy = nullptr;
3311 Value *VAArgOverflowSize = nullptr;
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003312
3313 SmallVector<CallInst*, 16> VAStartInstrumentationList;
3314
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003315 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
3316
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003317 VarArgAArch64Helper(Function &F, MemorySanitizer &MS,
3318 MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
3319
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003320 ArgKind classifyArgument(Value* arg) {
3321 Type *T = arg->getType();
3322 if (T->isFPOrFPVectorTy())
3323 return AK_FloatingPoint;
3324 if ((T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
3325 || (T->isPointerTy()))
3326 return AK_GeneralPurpose;
3327 return AK_Memory;
3328 }
3329
3330 // The instrumentation stores the argument shadow in a non ABI-specific
3331 // format because it does not know which argument is named (since Clang,
3332 // like x86_64 case, lowers the va_args in the frontend and this pass only
3333 // sees the low level code that deals with va_list internals).
3334 // The first seven GR registers are saved in the first 56 bytes of the
3335 // va_arg tls arra, followers by the first 8 FP/SIMD registers, and then
3336 // the remaining arguments.
3337 // Using constant offset within the va_arg TLS array allows fast copy
3338 // in the finalize instrumentation.
3339 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
3340 unsigned GrOffset = AArch64GrBegOffset;
3341 unsigned VrOffset = AArch64VrBegOffset;
3342 unsigned OverflowOffset = AArch64VAEndOffset;
3343
3344 const DataLayout &DL = F.getParent()->getDataLayout();
Marcin Koscielnicki60b3cbe2016-05-09 20:57:36 +00003345 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003346 ArgIt != End; ++ArgIt) {
3347 Value *A = *ArgIt;
Marcin Koscielnicki60b3cbe2016-05-09 20:57:36 +00003348 unsigned ArgNo = CS.getArgumentNo(ArgIt);
3349 bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003350 ArgKind AK = classifyArgument(A);
3351 if (AK == AK_GeneralPurpose && GrOffset >= AArch64GrEndOffset)
3352 AK = AK_Memory;
3353 if (AK == AK_FloatingPoint && VrOffset >= AArch64VrEndOffset)
3354 AK = AK_Memory;
3355 Value *Base;
3356 switch (AK) {
3357 case AK_GeneralPurpose:
3358 Base = getShadowPtrForVAArgument(A->getType(), IRB, GrOffset);
3359 GrOffset += 8;
3360 break;
3361 case AK_FloatingPoint:
3362 Base = getShadowPtrForVAArgument(A->getType(), IRB, VrOffset);
3363 VrOffset += 16;
3364 break;
3365 case AK_Memory:
Marcin Koscielnicki60b3cbe2016-05-09 20:57:36 +00003366 // Don't count fixed arguments in the overflow area - va_start will
3367 // skip right over them.
3368 if (IsFixed)
3369 continue;
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003370 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
3371 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003372 OverflowOffset += alignTo(ArgSize, 8);
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003373 break;
3374 }
Marcin Koscielnicki60b3cbe2016-05-09 20:57:36 +00003375 // Count Gp/Vr fixed arguments to their respective offsets, but don't
3376 // bother to actually store a shadow.
3377 if (IsFixed)
3378 continue;
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003379 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
3380 }
3381 Constant *OverflowSize =
3382 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AArch64VAEndOffset);
3383 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
3384 }
3385
3386 /// Compute the shadow address for a given va_arg.
3387 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3388 int ArgOffset) {
3389 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3390 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3391 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3392 "_msarg");
3393 }
3394
3395 void visitVAStartInst(VAStartInst &I) override {
3396 IRBuilder<> IRB(&I);
3397 VAStartInstrumentationList.push_back(&I);
3398 Value *VAListTag = I.getArgOperand(0);
3399 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3400 // Unpoison the whole __va_list_tag.
3401 // FIXME: magic ABI constants (size of va_list).
3402 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3403 /* size */32, /* alignment */8, false);
3404 }
3405
3406 void visitVACopyInst(VACopyInst &I) override {
3407 IRBuilder<> IRB(&I);
3408 Value *VAListTag = I.getArgOperand(0);
3409 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3410 // Unpoison the whole __va_list_tag.
3411 // FIXME: magic ABI constants (size of va_list).
3412 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3413 /* size */32, /* alignment */8, false);
3414 }
3415
3416 // Retrieve a va_list field of 'void*' size.
3417 Value* getVAField64(IRBuilder<> &IRB, Value *VAListTag, int offset) {
3418 Value *SaveAreaPtrPtr =
3419 IRB.CreateIntToPtr(
3420 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3421 ConstantInt::get(MS.IntptrTy, offset)),
3422 Type::getInt64PtrTy(*MS.C));
3423 return IRB.CreateLoad(SaveAreaPtrPtr);
3424 }
3425
3426 // Retrieve a va_list field of 'int' size.
3427 Value* getVAField32(IRBuilder<> &IRB, Value *VAListTag, int offset) {
3428 Value *SaveAreaPtr =
3429 IRB.CreateIntToPtr(
3430 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3431 ConstantInt::get(MS.IntptrTy, offset)),
3432 Type::getInt32PtrTy(*MS.C));
3433 Value *SaveArea32 = IRB.CreateLoad(SaveAreaPtr);
3434 return IRB.CreateSExt(SaveArea32, MS.IntptrTy);
3435 }
3436
3437 void finalizeInstrumentation() override {
3438 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
3439 "finalizeInstrumentation called twice");
3440 if (!VAStartInstrumentationList.empty()) {
3441 // If there is a va_start in this function, make a backup copy of
3442 // va_arg_tls somewhere in the function entry block.
3443 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
3444 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3445 Value *CopySize =
3446 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AArch64VAEndOffset),
3447 VAArgOverflowSize);
3448 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3449 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
3450 }
3451
3452 Value *GrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64GrArgSize);
3453 Value *VrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64VrArgSize);
3454
3455 // Instrument va_start, copy va_list shadow from the backup copy of
3456 // the TLS contents.
3457 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3458 CallInst *OrigInst = VAStartInstrumentationList[i];
3459 IRBuilder<> IRB(OrigInst->getNextNode());
3460
3461 Value *VAListTag = OrigInst->getArgOperand(0);
3462
3463 // The variadic ABI for AArch64 creates two areas to save the incoming
3464 // argument registers (one for 64-bit general register xn-x7 and another
3465 // for 128-bit FP/SIMD vn-v7).
3466 // We need then to propagate the shadow arguments on both regions
3467 // 'va::__gr_top + va::__gr_offs' and 'va::__vr_top + va::__vr_offs'.
3468 // The remaning arguments are saved on shadow for 'va::stack'.
3469 // One caveat is it requires only to propagate the non-named arguments,
3470 // however on the call site instrumentation 'all' the arguments are
3471 // saved. So to copy the shadow values from the va_arg TLS array
3472 // we need to adjust the offset for both GR and VR fields based on
3473 // the __{gr,vr}_offs value (since they are stores based on incoming
3474 // named arguments).
3475
3476 // Read the stack pointer from the va_list.
3477 Value *StackSaveAreaPtr = getVAField64(IRB, VAListTag, 0);
3478
3479 // Read both the __gr_top and __gr_off and add them up.
3480 Value *GrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 8);
3481 Value *GrOffSaveArea = getVAField32(IRB, VAListTag, 24);
3482
3483 Value *GrRegSaveAreaPtr = IRB.CreateAdd(GrTopSaveAreaPtr, GrOffSaveArea);
3484
3485 // Read both the __vr_top and __vr_off and add them up.
3486 Value *VrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 16);
3487 Value *VrOffSaveArea = getVAField32(IRB, VAListTag, 28);
3488
3489 Value *VrRegSaveAreaPtr = IRB.CreateAdd(VrTopSaveAreaPtr, VrOffSaveArea);
3490
3491 // It does not know how many named arguments is being used and, on the
3492 // callsite all the arguments were saved. Since __gr_off is defined as
3493 // '0 - ((8 - named_gr) * 8)', the idea is to just propagate the variadic
3494 // argument by ignoring the bytes of shadow from named arguments.
3495 Value *GrRegSaveAreaShadowPtrOff =
3496 IRB.CreateAdd(GrArgSize, GrOffSaveArea);
3497
3498 Value *GrRegSaveAreaShadowPtr =
3499 MSV.getShadowPtr(GrRegSaveAreaPtr, IRB.getInt8Ty(), IRB);
3500
3501 Value *GrSrcPtr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
3502 GrRegSaveAreaShadowPtrOff);
3503 Value *GrCopySize = IRB.CreateSub(GrArgSize, GrRegSaveAreaShadowPtrOff);
3504
3505 IRB.CreateMemCpy(GrRegSaveAreaShadowPtr, GrSrcPtr, GrCopySize, 8);
3506
3507 // Again, but for FP/SIMD values.
3508 Value *VrRegSaveAreaShadowPtrOff =
3509 IRB.CreateAdd(VrArgSize, VrOffSaveArea);
3510
3511 Value *VrRegSaveAreaShadowPtr =
3512 MSV.getShadowPtr(VrRegSaveAreaPtr, IRB.getInt8Ty(), IRB);
3513
3514 Value *VrSrcPtr = IRB.CreateInBoundsGEP(
3515 IRB.getInt8Ty(),
3516 IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
3517 IRB.getInt32(AArch64VrBegOffset)),
3518 VrRegSaveAreaShadowPtrOff);
3519 Value *VrCopySize = IRB.CreateSub(VrArgSize, VrRegSaveAreaShadowPtrOff);
3520
3521 IRB.CreateMemCpy(VrRegSaveAreaShadowPtr, VrSrcPtr, VrCopySize, 8);
3522
3523 // And finally for remaining arguments.
3524 Value *StackSaveAreaShadowPtr =
3525 MSV.getShadowPtr(StackSaveAreaPtr, IRB.getInt8Ty(), IRB);
3526
3527 Value *StackSrcPtr =
3528 IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
3529 IRB.getInt32(AArch64VAEndOffset));
3530
3531 IRB.CreateMemCpy(StackSaveAreaShadowPtr, StackSrcPtr,
3532 VAArgOverflowSize, 16);
3533 }
3534 }
3535};
3536
Marcin Koscielnickia4fcd362016-05-13 23:55:33 +00003537/// \brief PowerPC64-specific implementation of VarArgHelper.
3538struct VarArgPowerPC64Helper : public VarArgHelper {
3539 Function &F;
3540 MemorySanitizer &MS;
3541 MemorySanitizerVisitor &MSV;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003542 Value *VAArgTLSCopy = nullptr;
3543 Value *VAArgSize = nullptr;
Marcin Koscielnickia4fcd362016-05-13 23:55:33 +00003544
3545 SmallVector<CallInst*, 16> VAStartInstrumentationList;
3546
3547 VarArgPowerPC64Helper(Function &F, MemorySanitizer &MS,
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003548 MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
Marcin Koscielnickia4fcd362016-05-13 23:55:33 +00003549
3550 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
3551 // For PowerPC, we need to deal with alignment of stack arguments -
3552 // they are mostly aligned to 8 bytes, but vectors and i128 arrays
3553 // are aligned to 16 bytes, byvals can be aligned to 8 or 16 bytes,
3554 // and QPX vectors are aligned to 32 bytes. For that reason, we
3555 // compute current offset from stack pointer (which is always properly
3556 // aligned), and offset for the first vararg, then subtract them.
3557 unsigned VAArgBase;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003558 Triple TargetTriple(F.getParent()->getTargetTriple());
Marcin Koscielnickia4fcd362016-05-13 23:55:33 +00003559 // Parameter save area starts at 48 bytes from frame pointer for ABIv1,
3560 // and 32 bytes for ABIv2. This is usually determined by target
3561 // endianness, but in theory could be overriden by function attribute.
3562 // For simplicity, we ignore it here (it'd only matter for QPX vectors).
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003563 if (TargetTriple.getArch() == Triple::ppc64)
Marcin Koscielnickia4fcd362016-05-13 23:55:33 +00003564 VAArgBase = 48;
3565 else
3566 VAArgBase = 32;
3567 unsigned VAArgOffset = VAArgBase;
3568 const DataLayout &DL = F.getParent()->getDataLayout();
3569 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
3570 ArgIt != End; ++ArgIt) {
3571 Value *A = *ArgIt;
3572 unsigned ArgNo = CS.getArgumentNo(ArgIt);
3573 bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
Reid Klecknerfb502d22017-04-14 20:19:02 +00003574 bool IsByVal = CS.paramHasAttr(ArgNo, Attribute::ByVal);
Marcin Koscielnickia4fcd362016-05-13 23:55:33 +00003575 if (IsByVal) {
3576 assert(A->getType()->isPointerTy());
3577 Type *RealTy = A->getType()->getPointerElementType();
3578 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
Reid Kleckner859f8b52017-04-28 20:34:27 +00003579 uint64_t ArgAlign = CS.getParamAlignment(ArgNo);
Marcin Koscielnickia4fcd362016-05-13 23:55:33 +00003580 if (ArgAlign < 8)
3581 ArgAlign = 8;
3582 VAArgOffset = alignTo(VAArgOffset, ArgAlign);
3583 if (!IsFixed) {
3584 Value *Base = getShadowPtrForVAArgument(RealTy, IRB,
3585 VAArgOffset - VAArgBase);
3586 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
3587 ArgSize, kShadowTLSAlignment);
3588 }
3589 VAArgOffset += alignTo(ArgSize, 8);
3590 } else {
3591 Value *Base;
3592 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
3593 uint64_t ArgAlign = 8;
3594 if (A->getType()->isArrayTy()) {
3595 // Arrays are aligned to element size, except for long double
3596 // arrays, which are aligned to 8 bytes.
3597 Type *ElementTy = A->getType()->getArrayElementType();
3598 if (!ElementTy->isPPC_FP128Ty())
3599 ArgAlign = DL.getTypeAllocSize(ElementTy);
3600 } else if (A->getType()->isVectorTy()) {
3601 // Vectors are naturally aligned.
3602 ArgAlign = DL.getTypeAllocSize(A->getType());
3603 }
3604 if (ArgAlign < 8)
3605 ArgAlign = 8;
3606 VAArgOffset = alignTo(VAArgOffset, ArgAlign);
3607 if (DL.isBigEndian()) {
3608 // Adjusting the shadow for argument with size < 8 to match the placement
3609 // of bits in big endian system
3610 if (ArgSize < 8)
3611 VAArgOffset += (8 - ArgSize);
3612 }
3613 if (!IsFixed) {
3614 Base = getShadowPtrForVAArgument(A->getType(), IRB,
3615 VAArgOffset - VAArgBase);
3616 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
3617 }
3618 VAArgOffset += ArgSize;
3619 VAArgOffset = alignTo(VAArgOffset, 8);
3620 }
3621 if (IsFixed)
3622 VAArgBase = VAArgOffset;
3623 }
3624
3625 Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(),
3626 VAArgOffset - VAArgBase);
3627 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
3628 // a new class member i.e. it is the total size of all VarArgs.
3629 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
3630 }
3631
3632 /// \brief Compute the shadow address for a given va_arg.
3633 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3634 int ArgOffset) {
3635 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3636 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3637 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3638 "_msarg");
3639 }
3640
3641 void visitVAStartInst(VAStartInst &I) override {
3642 IRBuilder<> IRB(&I);
3643 VAStartInstrumentationList.push_back(&I);
3644 Value *VAListTag = I.getArgOperand(0);
3645 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3646 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3647 /* size */8, /* alignment */8, false);
3648 }
3649
3650 void visitVACopyInst(VACopyInst &I) override {
3651 IRBuilder<> IRB(&I);
3652 Value *VAListTag = I.getArgOperand(0);
3653 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3654 // Unpoison the whole __va_list_tag.
3655 // FIXME: magic ABI constants.
3656 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3657 /* size */8, /* alignment */8, false);
3658 }
3659
3660 void finalizeInstrumentation() override {
3661 assert(!VAArgSize && !VAArgTLSCopy &&
3662 "finalizeInstrumentation called twice");
3663 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
3664 VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3665 Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
3666 VAArgSize);
3667
3668 if (!VAStartInstrumentationList.empty()) {
3669 // If there is a va_start in this function, make a backup copy of
3670 // va_arg_tls somewhere in the function entry block.
3671 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3672 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
3673 }
3674
3675 // Instrument va_start.
3676 // Copy va_list shadow from the backup copy of the TLS contents.
3677 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3678 CallInst *OrigInst = VAStartInstrumentationList[i];
3679 IRBuilder<> IRB(OrigInst->getNextNode());
3680 Value *VAListTag = OrigInst->getArgOperand(0);
3681 Value *RegSaveAreaPtrPtr =
3682 IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3683 Type::getInt64PtrTy(*MS.C));
3684 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3685 Value *RegSaveAreaShadowPtr =
3686 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
3687 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
3688 }
3689 }
3690};
3691
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003692/// \brief A no-op implementation of VarArgHelper.
3693struct VarArgNoOpHelper : public VarArgHelper {
3694 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
3695 MemorySanitizerVisitor &MSV) {}
3696
Craig Topper3e4c6972014-03-05 09:10:37 +00003697 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003698
Craig Topper3e4c6972014-03-05 09:10:37 +00003699 void visitVAStartInst(VAStartInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003700
Craig Topper3e4c6972014-03-05 09:10:37 +00003701 void visitVACopyInst(VACopyInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003702
Craig Topper3e4c6972014-03-05 09:10:37 +00003703 void finalizeInstrumentation() override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003704};
3705
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003706} // end anonymous namespace
3707
3708static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
3709 MemorySanitizerVisitor &Visitor) {
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003710 // VarArg handling is only implemented on AMD64. False positives are possible
3711 // on other platforms.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003712 Triple TargetTriple(Func.getParent()->getTargetTriple());
3713 if (TargetTriple.getArch() == Triple::x86_64)
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003714 return new VarArgAMD64Helper(Func, Msan, Visitor);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003715 else if (TargetTriple.getArch() == Triple::mips64 ||
3716 TargetTriple.getArch() == Triple::mips64el)
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003717 return new VarArgMIPS64Helper(Func, Msan, Visitor);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003718 else if (TargetTriple.getArch() == Triple::aarch64)
Adhemerval Zanellad2b10c52015-12-14 14:14:15 +00003719 return new VarArgAArch64Helper(Func, Msan, Visitor);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00003720 else if (TargetTriple.getArch() == Triple::ppc64 ||
3721 TargetTriple.getArch() == Triple::ppc64le)
Marcin Koscielnickia4fcd362016-05-13 23:55:33 +00003722 return new VarArgPowerPC64Helper(Func, Msan, Visitor);
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003723 else
3724 return new VarArgNoOpHelper(Func, Msan, Visitor);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003725}
3726
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003727bool MemorySanitizer::runOnFunction(Function &F) {
Ismail Pazarbasie5048e12015-05-07 21:41:52 +00003728 if (&F == MsanCtorFunction)
3729 return false;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003730 MemorySanitizerVisitor Visitor(F, *this);
3731
3732 // Clear out readonly/readnone attributes.
3733 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003734 B.addAttribute(Attribute::ReadOnly)
3735 .addAttribute(Attribute::ReadNone);
Reid Kleckneree4930b2017-05-02 22:07:37 +00003736 F.removeAttributes(AttributeList::FunctionIndex, B);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003737
3738 return Visitor.runOnFunction();
3739}