blob: e36637a4fd8d2f8073212e0c380f69ea2085308d [file] [log] [blame]
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001//===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file is a part of MemorySanitizer, a detector of uninitialized
11/// reads.
12///
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000013/// The algorithm of the tool is similar to Memcheck
14/// (http://goo.gl/QKbem). We associate a few shadow bits with every
15/// byte of the application memory, poison the shadow of the malloc-ed
16/// or alloca-ed memory, load the shadow bits on every memory read,
17/// propagate the shadow bits through some of the arithmetic
18/// instruction (including MOV), store the shadow bits on every memory
19/// write, report a bug on some other instructions (e.g. JMP) if the
20/// associated shadow is poisoned.
21///
22/// But there are differences too. The first and the major one:
23/// compiler instrumentation instead of binary instrumentation. This
24/// gives us much better register allocation, possible compiler
25/// optimizations and a fast start-up. But this brings the major issue
26/// as well: msan needs to see all program events, including system
27/// calls and reads/writes in system libraries, so we either need to
28/// compile *everything* with msan or use a binary translation
29/// component (e.g. DynamoRIO) to instrument pre-built libraries.
30/// Another difference from Memcheck is that we use 8 shadow bits per
31/// byte of application memory and use a direct shadow mapping. This
32/// greatly simplifies the instrumentation code and avoids races on
33/// shadow updates (Memcheck is single-threaded so races are not a
34/// concern there. Memcheck uses 2 shadow bits per byte with a slow
35/// path storage that uses 8 bits per byte).
36///
37/// The default value of shadow is 0, which means "clean" (not poisoned).
38///
39/// Every module initializer should call __msan_init to ensure that the
40/// shadow memory is ready. On error, __msan_warning is called. Since
41/// parameters and return values may be passed via registers, we have a
42/// specialized thread-local shadow for return values
43/// (__msan_retval_tls) and parameters (__msan_param_tls).
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +000044///
45/// Origin tracking.
46///
47/// MemorySanitizer can track origins (allocation points) of all uninitialized
48/// values. This behavior is controlled with a flag (msan-track-origins) and is
49/// disabled by default.
50///
51/// Origins are 4-byte values created and interpreted by the runtime library.
52/// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
53/// of application memory. Propagation of origins is basically a bunch of
54/// "select" instructions that pick the origin of a dirty argument, if an
55/// instruction has one.
56///
57/// Every 4 aligned, consecutive bytes of application memory have one origin
58/// value associated with them. If these bytes contain uninitialized data
59/// coming from 2 different allocations, the last store wins. Because of this,
60/// MemorySanitizer reports can show unrelated origins, but this is unlikely in
Alexey Samsonov3efc87e2012-12-28 09:30:44 +000061/// practice.
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +000062///
63/// Origins are meaningless for fully initialized values, so MemorySanitizer
64/// avoids storing origin to memory when a fully initialized value is stored.
65/// This way it avoids needless overwritting origin of the 4-byte region on
66/// a short (i.e. 1 byte) clean store, and it is also good for performance.
Evgeniy Stepanov5522a702013-09-24 11:20:27 +000067///
68/// Atomic handling.
69///
70/// Ideally, every atomic store of application value should update the
71/// corresponding shadow location in an atomic way. Unfortunately, atomic store
72/// of two disjoint locations can not be done without severe slowdown.
73///
74/// Therefore, we implement an approximation that may err on the safe side.
75/// In this implementation, every atomically accessed location in the program
76/// may only change from (partially) uninitialized to fully initialized, but
77/// not the other way around. We load the shadow _after_ the application load,
78/// and we store the shadow _before_ the app store. Also, we always store clean
79/// shadow (if the application store is atomic). This way, if the store-load
80/// pair constitutes a happens-before arc, shadow store and load are correctly
81/// ordered such that the load will get either the value that was stored, or
82/// some later value (which is always clean).
83///
84/// This does not work very well with Compare-And-Swap (CAS) and
85/// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
86/// must store the new shadow before the app operation, and load the shadow
87/// after the app operation. Computers don't work this way. Current
88/// implementation ignores the load aspect of CAS/RMW, always returning a clean
89/// value. It implements the store part as a simple atomic store by storing a
90/// clean shadow.
91
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000092//===----------------------------------------------------------------------===//
93
Chandler Carruthed0881b2012-12-03 16:50:05 +000094#include "llvm/Transforms/Instrumentation.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000095#include "llvm/ADT/DepthFirstIterator.h"
96#include "llvm/ADT/SmallString.h"
97#include "llvm/ADT/SmallVector.h"
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +000098#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +000099#include "llvm/ADT/Triple.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000100#include "llvm/IR/DataLayout.h"
101#include "llvm/IR/Function.h"
102#include "llvm/IR/IRBuilder.h"
103#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +0000104#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000105#include "llvm/IR/IntrinsicInst.h"
106#include "llvm/IR/LLVMContext.h"
107#include "llvm/IR/MDBuilder.h"
108#include "llvm/IR/Module.h"
109#include "llvm/IR/Type.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +0000110#include "llvm/IR/ValueMap.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000111#include "llvm/Support/CommandLine.h"
112#include "llvm/Support/Compiler.h"
113#include "llvm/Support/Debug.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000114#include "llvm/Support/raw_ostream.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000115#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +0000116#include "llvm/Transforms/Utils/Local.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000117#include "llvm/Transforms/Utils/ModuleUtils.h"
118
119using namespace llvm;
120
Chandler Carruth964daaa2014-04-22 02:55:47 +0000121#define DEBUG_TYPE "msan"
122
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000123static const unsigned kOriginSize = 4;
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +0000124static const unsigned kMinOriginAlignment = 4;
125static const unsigned kShadowTLSAlignment = 8;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000126
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000127// These constants must be kept in sync with the ones in msan.h.
128static const unsigned kParamTLSSize = 800;
129static const unsigned kRetvalTLSSize = 800;
130
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000131// Accesses sizes are powers of two: 1, 2, 4, 8.
132static const size_t kNumberOfAccessSizes = 4;
133
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +0000134/// \brief Track origins of uninitialized values.
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000135///
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +0000136/// Adds a section to MemorySanitizer report that points to the allocation
137/// (stack or heap) the uninitialized bits came from originally.
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000138static cl::opt<int> ClTrackOrigins("msan-track-origins",
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000139 cl::desc("Track origins (allocation sites) of poisoned memory"),
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000140 cl::Hidden, cl::init(0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000141static cl::opt<bool> ClKeepGoing("msan-keep-going",
142 cl::desc("keep going after reporting a UMR"),
143 cl::Hidden, cl::init(false));
144static cl::opt<bool> ClPoisonStack("msan-poison-stack",
145 cl::desc("poison uninitialized stack variables"),
146 cl::Hidden, cl::init(true));
147static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
148 cl::desc("poison uninitialized stack variables with a call"),
149 cl::Hidden, cl::init(false));
150static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
151 cl::desc("poison uninitialized stack variables with the given patter"),
152 cl::Hidden, cl::init(0xff));
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000153static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
154 cl::desc("poison undef temps"),
155 cl::Hidden, cl::init(true));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000156
157static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
158 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
159 cl::Hidden, cl::init(true));
160
Evgeniy Stepanovfac84032013-01-25 15:31:10 +0000161static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
162 cl::desc("exact handling of relational integer ICmp"),
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +0000163 cl::Hidden, cl::init(false));
Evgeniy Stepanovfac84032013-01-25 15:31:10 +0000164
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000165// This flag controls whether we check the shadow of the address
166// operand of load or store. Such bugs are very rare, since load from
167// a garbage address typically results in SEGV, but still happen
168// (e.g. only lower bits of address are garbage, or the access happens
169// early at program startup where malloc-ed memory is more likely to
170// be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
171static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
172 cl::desc("report accesses through a pointer which has poisoned shadow"),
173 cl::Hidden, cl::init(true));
174
175static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
176 cl::desc("print out instructions with default strict semantics"),
177 cl::Hidden, cl::init(false));
178
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000179static cl::opt<int> ClInstrumentationWithCallThreshold(
180 "msan-instrumentation-with-call-threshold",
181 cl::desc(
182 "If the function being instrumented requires more than "
183 "this number of checks and origin stores, use callbacks instead of "
184 "inline checks (-1 means never use callbacks)."),
Evgeniy Stepanov3939f542014-04-21 15:04:05 +0000185 cl::Hidden, cl::init(3500));
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000186
Evgeniy Stepanov7db296e2014-10-23 01:05:46 +0000187// This is an experiment to enable handling of cases where shadow is a non-zero
188// compile-time constant. For some unexplainable reason they were silently
189// ignored in the instrumentation.
190static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
191 cl::desc("Insert checks for constant shadow values"),
192 cl::Hidden, cl::init(false));
193
Ismail Pazarbasie5048e12015-05-07 21:41:52 +0000194static const char *const kMsanModuleCtorName = "msan.module_ctor";
195static const char *const kMsanInitName = "__msan_init";
196
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000197namespace {
198
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000199// Memory map parameters used in application-to-shadow address calculation.
200// Offset = (Addr & ~AndMask) ^ XorMask
201// Shadow = ShadowBase + Offset
202// Origin = OriginBase + Offset
203struct MemoryMapParams {
204 uint64_t AndMask;
205 uint64_t XorMask;
206 uint64_t ShadowBase;
207 uint64_t OriginBase;
208};
209
210struct PlatformMemoryMapParams {
211 const MemoryMapParams *bits32;
212 const MemoryMapParams *bits64;
213};
214
215// i386 Linux
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000216static const MemoryMapParams Linux_I386_MemoryMapParams = {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000217 0x000080000000, // AndMask
218 0, // XorMask (not used)
219 0, // ShadowBase (not used)
220 0x000040000000, // OriginBase
221};
222
223// x86_64 Linux
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000224static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000225 0x400000000000, // AndMask
226 0, // XorMask (not used)
227 0, // ShadowBase (not used)
228 0x200000000000, // OriginBase
229};
230
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000231// mips64 Linux
232static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
233 0x004000000000, // AndMask
234 0, // XorMask (not used)
235 0, // ShadowBase (not used)
236 0x002000000000, // OriginBase
237};
238
Jay Foad7a28cdc2015-06-25 10:34:29 +0000239// ppc64 Linux
240static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
241 0x200000000000, // AndMask
242 0x100000000000, // XorMask
243 0x080000000000, // ShadowBase
244 0x1C0000000000, // OriginBase
245};
246
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000247// i386 FreeBSD
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000248static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000249 0x000180000000, // AndMask
250 0x000040000000, // XorMask
251 0x000020000000, // ShadowBase
252 0x000700000000, // OriginBase
253};
254
255// x86_64 FreeBSD
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000256static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000257 0xc00000000000, // AndMask
258 0x200000000000, // XorMask
259 0x100000000000, // ShadowBase
260 0x380000000000, // OriginBase
261};
262
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000263static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
264 &Linux_I386_MemoryMapParams,
265 &Linux_X86_64_MemoryMapParams,
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000266};
267
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000268static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
269 NULL,
270 &Linux_MIPS64_MemoryMapParams,
271};
272
Jay Foad7a28cdc2015-06-25 10:34:29 +0000273static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
274 NULL,
275 &Linux_PowerPC64_MemoryMapParams,
276};
277
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000278static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
279 &FreeBSD_I386_MemoryMapParams,
280 &FreeBSD_X86_64_MemoryMapParams,
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000281};
282
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000283/// \brief An instrumentation pass implementing detection of uninitialized
284/// reads.
285///
286/// MemorySanitizer: instrument the code in module to find
287/// uninitialized reads.
288class MemorySanitizer : public FunctionPass {
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000289 public:
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000290 MemorySanitizer(int TrackOrigins = 0)
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000291 : FunctionPass(ID),
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000292 TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
Evgeniy Stepanove402d9e2014-11-27 14:54:02 +0000293 WarningFn(nullptr) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000294 const char *getPassName() const override { return "MemorySanitizer"; }
295 bool runOnFunction(Function &F) override;
296 bool doInitialization(Module &M) override;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000297 static char ID; // Pass identification, replacement for typeid.
298
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000299 private:
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000300 void initializeCallbacks(Module &M);
301
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000302 /// \brief Track origins (allocation points) of uninitialized values.
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000303 int TrackOrigins;
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000304
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000305 LLVMContext *C;
306 Type *IntptrTy;
307 Type *OriginTy;
308 /// \brief Thread-local shadow storage for function parameters.
309 GlobalVariable *ParamTLS;
310 /// \brief Thread-local origin storage for function parameters.
311 GlobalVariable *ParamOriginTLS;
312 /// \brief Thread-local shadow storage for function return value.
313 GlobalVariable *RetvalTLS;
314 /// \brief Thread-local origin storage for function return value.
315 GlobalVariable *RetvalOriginTLS;
316 /// \brief Thread-local shadow storage for in-register va_arg function
317 /// parameters (x86_64-specific).
318 GlobalVariable *VAArgTLS;
319 /// \brief Thread-local shadow storage for va_arg overflow area
320 /// (x86_64-specific).
321 GlobalVariable *VAArgOverflowSizeTLS;
322 /// \brief Thread-local space used to pass origin value to the UMR reporting
323 /// function.
324 GlobalVariable *OriginTLS;
325
326 /// \brief The run-time callback to print a warning.
327 Value *WarningFn;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000328 // These arrays are indexed by log2(AccessSize).
329 Value *MaybeWarningFn[kNumberOfAccessSizes];
330 Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
331
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000332 /// \brief Run-time helper that generates a new origin value for a stack
333 /// allocation.
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +0000334 Value *MsanSetAllocaOrigin4Fn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000335 /// \brief Run-time helper that poisons stack on function entry.
336 Value *MsanPoisonStackFn;
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000337 /// \brief Run-time helper that records a store (or any event) of an
338 /// uninitialized value and returns an updated origin id encoding this info.
339 Value *MsanChainOriginFn;
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000340 /// \brief MSan runtime replacements for memmove, memcpy and memset.
341 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000342
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000343 /// \brief Memory map parameters used in application-to-shadow calculation.
344 const MemoryMapParams *MapParams;
345
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000346 MDNode *ColdCallWeights;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000347 /// \brief Branch weights for origin store.
348 MDNode *OriginStoreWeights;
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000349 /// \brief An empty volatile inline asm that prevents callback merge.
350 InlineAsm *EmptyAsm;
Ismail Pazarbasie5048e12015-05-07 21:41:52 +0000351 Function *MsanCtorFunction;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000352
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000353 friend struct MemorySanitizerVisitor;
354 friend struct VarArgAMD64Helper;
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +0000355 friend struct VarArgMIPS64Helper;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000356};
357} // namespace
358
359char MemorySanitizer::ID = 0;
360INITIALIZE_PASS(MemorySanitizer, "msan",
361 "MemorySanitizer: detects uninitialized reads.",
362 false, false)
363
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000364FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
365 return new MemorySanitizer(TrackOrigins);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000366}
367
368/// \brief Create a non-const global initialized with the given string.
369///
370/// Creates a writable global for Str so that we can pass it to the
371/// run-time lib. Runtime uses first 4 bytes of the string to store the
372/// frame ID, so the string needs to be mutable.
373static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
374 StringRef Str) {
375 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
376 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
377 GlobalValue::PrivateLinkage, StrConst, "");
378}
379
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000380
381/// \brief Insert extern declaration of runtime-provided functions and globals.
382void MemorySanitizer::initializeCallbacks(Module &M) {
383 // Only do this once.
384 if (WarningFn)
385 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000386
387 IRBuilder<> IRB(*C);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000388 // Create the callback.
389 // FIXME: this function should have "Cold" calling conv,
390 // which is not yet implemented.
391 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
392 : "__msan_warning_noreturn";
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000393 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000394
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000395 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
396 AccessSizeIndex++) {
397 unsigned AccessSize = 1 << AccessSizeIndex;
398 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
399 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
400 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000401 IRB.getInt32Ty(), nullptr);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000402
403 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
404 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
405 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000406 IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000407 }
408
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +0000409 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
410 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000411 IRB.getInt8PtrTy(), IntptrTy, nullptr);
David Blaikiea92765c2014-11-14 00:41:42 +0000412 MsanPoisonStackFn =
413 M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
414 IRB.getInt8PtrTy(), IntptrTy, nullptr);
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000415 MsanChainOriginFn = M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000416 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000417 MemmoveFn = M.getOrInsertFunction(
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000418 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000419 IRB.getInt8PtrTy(), IntptrTy, nullptr);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000420 MemcpyFn = M.getOrInsertFunction(
421 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000422 IntptrTy, nullptr);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000423 MemsetFn = M.getOrInsertFunction(
424 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000425 IntptrTy, nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000426
427 // Create globals.
428 RetvalTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000429 M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000430 GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000431 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000432 RetvalOriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000433 M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
434 "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000435
436 ParamTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000437 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000438 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000439 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000440 ParamOriginTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000441 M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
442 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
443 nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000444
445 VAArgTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000446 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000447 GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000448 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000449 VAArgOverflowSizeTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000450 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
451 "__msan_va_arg_overflow_size_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000452 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000453 OriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000454 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
455 "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000456
457 // We insert an empty inline asm after __msan_report* to avoid callback merge.
458 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
459 StringRef(""), StringRef(""),
460 /*hasSideEffects=*/true);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000461}
462
463/// \brief Module-level initialization.
464///
465/// inserts a call to __msan_init to the module's constructor list.
466bool MemorySanitizer::doInitialization(Module &M) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000467 auto &DL = M.getDataLayout();
Rafael Espindola93512512014-02-25 17:30:31 +0000468
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000469 Triple TargetTriple(M.getTargetTriple());
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000470 switch (TargetTriple.getOS()) {
471 case Triple::FreeBSD:
472 switch (TargetTriple.getArch()) {
473 case Triple::x86_64:
474 MapParams = FreeBSD_X86_MemoryMapParams.bits64;
475 break;
476 case Triple::x86:
477 MapParams = FreeBSD_X86_MemoryMapParams.bits32;
478 break;
479 default:
480 report_fatal_error("unsupported architecture");
481 }
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000482 break;
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000483 case Triple::Linux:
484 switch (TargetTriple.getArch()) {
485 case Triple::x86_64:
486 MapParams = Linux_X86_MemoryMapParams.bits64;
487 break;
488 case Triple::x86:
489 MapParams = Linux_X86_MemoryMapParams.bits32;
490 break;
491 case Triple::mips64:
492 case Triple::mips64el:
493 MapParams = Linux_MIPS_MemoryMapParams.bits64;
494 break;
Jay Foad7a28cdc2015-06-25 10:34:29 +0000495 case Triple::ppc64:
496 case Triple::ppc64le:
497 MapParams = Linux_PowerPC_MemoryMapParams.bits64;
498 break;
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000499 default:
500 report_fatal_error("unsupported architecture");
501 }
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000502 break;
503 default:
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000504 report_fatal_error("unsupported operating system");
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000505 }
506
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000507 C = &(M.getContext());
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000508 IRBuilder<> IRB(*C);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000509 IntptrTy = IRB.getIntPtrTy(DL);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000510 OriginTy = IRB.getInt32Ty();
511
512 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000513 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000514
Ismail Pazarbasie5048e12015-05-07 21:41:52 +0000515 std::tie(MsanCtorFunction, std::ignore) =
516 createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
517 /*InitArgTypes=*/{},
518 /*InitArgs=*/{});
519
520 appendToGlobalCtors(M, MsanCtorFunction, 0);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000521
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000522 if (TrackOrigins)
523 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
524 IRB.getInt32(TrackOrigins), "__msan_track_origins");
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000525
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000526 if (ClKeepGoing)
527 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
528 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
Evgeniy Stepanovdcf6bcb2013-01-22 13:26:53 +0000529
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000530 return true;
531}
532
533namespace {
534
535/// \brief A helper class that handles instrumentation of VarArg
536/// functions on a particular platform.
537///
538/// Implementations are expected to insert the instrumentation
539/// necessary to propagate argument shadow through VarArg function
540/// calls. Visit* methods are called during an InstVisitor pass over
541/// the function, and should avoid creating new basic blocks. A new
542/// instance of this class is created for each instrumented function.
543struct VarArgHelper {
544 /// \brief Visit a CallSite.
545 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
546
547 /// \brief Visit a va_start call.
548 virtual void visitVAStartInst(VAStartInst &I) = 0;
549
550 /// \brief Visit a va_copy call.
551 virtual void visitVACopyInst(VACopyInst &I) = 0;
552
553 /// \brief Finalize function instrumentation.
554 ///
555 /// This method is called after visiting all interesting (see above)
556 /// instructions in a function.
557 virtual void finalizeInstrumentation() = 0;
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000558
559 virtual ~VarArgHelper() {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000560};
561
562struct MemorySanitizerVisitor;
563
564VarArgHelper*
565CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
566 MemorySanitizerVisitor &Visitor);
567
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000568unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
569 if (TypeSize <= 8) return 0;
570 return Log2_32_Ceil(TypeSize / 8);
571}
572
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000573/// This class does all the work for a given function. Store and Load
574/// instructions store and load corresponding shadow and origin
575/// values. Most instructions propagate shadow from arguments to their
576/// return values. Certain instructions (most importantly, BranchInst)
577/// test their argument shadow and print reports (with a runtime call) if it's
578/// non-zero.
579struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
580 Function &F;
581 MemorySanitizer &MS;
582 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
583 ValueMap<Value*, Value*> ShadowMap, OriginMap;
Ahmed Charles56440fd2014-03-06 05:51:42 +0000584 std::unique_ptr<VarArgHelper> VAHelper;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000585
586 // The following flags disable parts of MSan instrumentation based on
587 // blacklist contents and command-line options.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000588 bool InsertChecks;
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000589 bool PropagateShadow;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000590 bool PoisonStack;
591 bool PoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000592 bool CheckReturnValue;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000593
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000594 struct ShadowOriginAndInsertPoint {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000595 Value *Shadow;
596 Value *Origin;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000597 Instruction *OrigIns;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000598 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000599 : Shadow(S), Origin(O), OrigIns(I) { }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000600 };
601 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000602 SmallVector<Instruction*, 16> StoreList;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000603
604 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000605 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +0000606 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000607 InsertChecks = SanitizeFunction;
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000608 PropagateShadow = SanitizeFunction;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000609 PoisonStack = SanitizeFunction && ClPoisonStack;
610 PoisonUndef = SanitizeFunction && ClPoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000611 // FIXME: Consider using SpecialCaseList to specify a list of functions that
612 // must always return fully initialized values. For now, we hardcode "main".
613 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000614
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000615 DEBUG(if (!InsertChecks)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000616 dbgs() << "MemorySanitizer is not inserting checks into '"
617 << F.getName() << "'\n");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000618 }
619
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000620 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
621 if (MS.TrackOrigins <= 1) return V;
622 return IRB.CreateCall(MS.MsanChainOriginFn, V);
623 }
624
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000625 Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000626 const DataLayout &DL = F.getParent()->getDataLayout();
627 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000628 if (IntptrSize == kOriginSize) return Origin;
629 assert(IntptrSize == kOriginSize * 2);
630 Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
631 return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
632 }
633
634 /// \brief Fill memory range with the given origin value.
635 void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
636 unsigned Size, unsigned Alignment) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000637 const DataLayout &DL = F.getParent()->getDataLayout();
638 unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
639 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000640 assert(IntptrAlignment >= kMinOriginAlignment);
641 assert(IntptrSize >= kOriginSize);
642
643 unsigned Ofs = 0;
644 unsigned CurrentAlignment = Alignment;
645 if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
646 Value *IntptrOrigin = originToIntptr(IRB, Origin);
647 Value *IntptrOriginPtr =
648 IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
649 for (unsigned i = 0; i < Size / IntptrSize; ++i) {
David Blaikie95d3e532015-04-03 23:03:54 +0000650 Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
651 : IntptrOriginPtr;
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000652 IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
653 Ofs += IntptrSize / kOriginSize;
654 CurrentAlignment = IntptrAlignment;
655 }
656 }
657
658 for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
David Blaikie95d3e532015-04-03 23:03:54 +0000659 Value *GEP =
660 i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000661 IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
662 CurrentAlignment = kMinOriginAlignment;
663 }
664 }
665
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000666 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
667 unsigned Alignment, bool AsCall) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000668 const DataLayout &DL = F.getParent()->getDataLayout();
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000669 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000670 unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000671 if (isa<StructType>(Shadow->getType())) {
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000672 paintOrigin(IRB, updateOrigin(Origin, IRB),
673 getOriginPtr(Addr, IRB, Alignment), StoreSize,
674 OriginAlignment);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000675 } else {
676 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000677 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
678 if (ConstantShadow) {
679 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000680 paintOrigin(IRB, updateOrigin(Origin, IRB),
681 getOriginPtr(Addr, IRB, Alignment), StoreSize,
682 OriginAlignment);
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000683 return;
684 }
685
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000686 unsigned TypeSizeInBits =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000687 DL.getTypeSizeInBits(ConvertedShadow->getType());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000688 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
689 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
690 Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
691 Value *ConvertedShadow2 = IRB.CreateZExt(
692 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
David Blaikieff6409d2015-05-18 22:13:54 +0000693 IRB.CreateCall(Fn, {ConvertedShadow2,
694 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
695 Origin});
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000696 } else {
697 Value *Cmp = IRB.CreateICmpNE(
698 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
699 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
700 Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
701 IRBuilder<> IRBNew(CheckTerm);
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000702 paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
703 getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
704 OriginAlignment);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000705 }
706 }
707 }
708
709 void materializeStores(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000710 for (auto Inst : StoreList) {
711 StoreInst &SI = *dyn_cast<StoreInst>(Inst);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000712
Alexey Samsonova02e6642014-05-29 18:40:48 +0000713 IRBuilder<> IRB(&SI);
714 Value *Val = SI.getValueOperand();
715 Value *Addr = SI.getPointerOperand();
716 Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000717 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
718
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000719 StoreInst *NewSI =
Alexey Samsonova02e6642014-05-29 18:40:48 +0000720 IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000721 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
NAKAMURA Takumie0b1b462012-12-06 13:38:00 +0000722 (void)NewSI;
Evgeniy Stepanovc4415592013-01-22 12:30:52 +0000723
Alexey Samsonova02e6642014-05-29 18:40:48 +0000724 if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000725
Alexey Samsonova02e6642014-05-29 18:40:48 +0000726 if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +0000727
Evgeniy Stepanov4e120572015-02-06 21:47:39 +0000728 if (MS.TrackOrigins && !SI.isAtomic())
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000729 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI.getAlignment(),
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000730 InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000731 }
732 }
733
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000734 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
735 bool AsCall) {
736 IRBuilder<> IRB(OrigIns);
737 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
738 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
739 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000740
741 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
742 if (ConstantShadow) {
743 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
744 if (MS.TrackOrigins) {
745 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
746 MS.OriginTLS);
747 }
David Blaikieff6409d2015-05-18 22:13:54 +0000748 IRB.CreateCall(MS.WarningFn, {});
749 IRB.CreateCall(MS.EmptyAsm, {});
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000750 // FIXME: Insert UnreachableInst if !ClKeepGoing?
751 // This may invalidate some of the following checks and needs to be done
752 // at the very end.
753 }
754 return;
755 }
756
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000757 const DataLayout &DL = OrigIns->getModule()->getDataLayout();
758
759 unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000760 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
761 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
762 Value *Fn = MS.MaybeWarningFn[SizeIndex];
763 Value *ConvertedShadow2 =
764 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
David Blaikieff6409d2015-05-18 22:13:54 +0000765 IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000766 ? Origin
David Blaikieff6409d2015-05-18 22:13:54 +0000767 : (Value *)IRB.getInt32(0)});
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000768 } else {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000769 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
770 getCleanShadow(ConvertedShadow), "_mscmp");
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000771 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
772 Cmp, OrigIns,
773 /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000774
775 IRB.SetInsertPoint(CheckTerm);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000776 if (MS.TrackOrigins) {
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000777 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000778 MS.OriginTLS);
779 }
David Blaikieff6409d2015-05-18 22:13:54 +0000780 IRB.CreateCall(MS.WarningFn, {});
781 IRB.CreateCall(MS.EmptyAsm, {});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000782 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
783 }
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000784 }
785
786 void materializeChecks(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000787 for (const auto &ShadowData : InstrumentationList) {
788 Instruction *OrigIns = ShadowData.OrigIns;
789 Value *Shadow = ShadowData.Shadow;
790 Value *Origin = ShadowData.Origin;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000791 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
792 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000793 DEBUG(dbgs() << "DONE:\n" << F);
794 }
795
796 /// \brief Add MemorySanitizer instrumentation to a function.
797 bool runOnFunction() {
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000798 MS.initializeCallbacks(*F.getParent());
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +0000799
800 // In the presence of unreachable blocks, we may see Phi nodes with
801 // incoming nodes from such blocks. Since InstVisitor skips unreachable
802 // blocks, such nodes will not have any shadow value associated with them.
803 // It's easier to remove unreachable blocks than deal with missing shadow.
804 removeUnreachableBlocks(F);
805
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000806 // Iterate all BBs in depth-first order and create shadow instructions
807 // for all instructions (where applicable).
808 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
David Blaikieceec2bd2014-04-11 01:50:01 +0000809 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000810 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000811
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000812
813 // Finalize PHI nodes.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000814 for (PHINode *PN : ShadowPHINodes) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000815 PHINode *PNS = cast<PHINode>(getShadow(PN));
Craig Topperf40110f2014-04-25 05:29:35 +0000816 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000817 size_t NumValues = PN->getNumIncomingValues();
818 for (size_t v = 0; v < NumValues; v++) {
819 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000820 if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000821 }
822 }
823
824 VAHelper->finalizeInstrumentation();
825
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000826 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
827 InstrumentationList.size() + StoreList.size() >
828 (unsigned)ClInstrumentationWithCallThreshold;
829
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000830 // Delayed instrumentation of StoreInst.
Evgeniy Stepanov47ac9ba2012-12-06 11:58:59 +0000831 // This may add new checks to be inserted later.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000832 materializeStores(InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000833
834 // Insert shadow value checks.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000835 materializeChecks(InstrumentWithCalls);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000836
837 return true;
838 }
839
840 /// \brief Compute the shadow type that corresponds to a given Value.
841 Type *getShadowTy(Value *V) {
842 return getShadowTy(V->getType());
843 }
844
845 /// \brief Compute the shadow type that corresponds to a given Type.
846 Type *getShadowTy(Type *OrigTy) {
847 if (!OrigTy->isSized()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000848 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000849 }
850 // For integer type, shadow is the same as the original type.
851 // This may return weird-sized types like i1.
852 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
853 return IT;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000854 const DataLayout &DL = F.getParent()->getDataLayout();
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000855 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000856 uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000857 return VectorType::get(IntegerType::get(*MS.C, EltSize),
858 VT->getNumElements());
859 }
Evgeniy Stepanov5997feb2014-07-31 11:02:27 +0000860 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
861 return ArrayType::get(getShadowTy(AT->getElementType()),
862 AT->getNumElements());
863 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000864 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
865 SmallVector<Type*, 4> Elements;
866 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
867 Elements.push_back(getShadowTy(ST->getElementType(i)));
868 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
869 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
870 return Res;
871 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000872 uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000873 return IntegerType::get(*MS.C, TypeSize);
874 }
875
876 /// \brief Flatten a vector type.
877 Type *getShadowTyNoVec(Type *ty) {
878 if (VectorType *vt = dyn_cast<VectorType>(ty))
879 return IntegerType::get(*MS.C, vt->getBitWidth());
880 return ty;
881 }
882
883 /// \brief Convert a shadow value to it's flattened variant.
884 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
885 Type *Ty = V->getType();
886 Type *NoVecTy = getShadowTyNoVec(Ty);
887 if (Ty == NoVecTy) return V;
888 return IRB.CreateBitCast(V, NoVecTy);
889 }
890
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000891 /// \brief Compute the integer shadow offset that corresponds to a given
892 /// application address.
893 ///
894 /// Offset = (Addr & ~AndMask) ^ XorMask
895 Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
896 uint64_t AndMask = MS.MapParams->AndMask;
897 assert(AndMask != 0 && "AndMask shall be specified");
898 Value *OffsetLong =
899 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
900 ConstantInt::get(MS.IntptrTy, ~AndMask));
901
902 uint64_t XorMask = MS.MapParams->XorMask;
903 if (XorMask != 0)
904 OffsetLong = IRB.CreateXor(OffsetLong,
905 ConstantInt::get(MS.IntptrTy, XorMask));
906 return OffsetLong;
907 }
908
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000909 /// \brief Compute the shadow address that corresponds to a given application
910 /// address.
911 ///
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000912 /// Shadow = ShadowBase + Offset
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000913 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
914 IRBuilder<> &IRB) {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000915 Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
916 uint64_t ShadowBase = MS.MapParams->ShadowBase;
917 if (ShadowBase != 0)
918 ShadowLong =
919 IRB.CreateAdd(ShadowLong,
920 ConstantInt::get(MS.IntptrTy, ShadowBase));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000921 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
922 }
923
924 /// \brief Compute the origin address that corresponds to a given application
925 /// address.
926 ///
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000927 /// OriginAddr = (OriginBase + Offset) & ~3ULL
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000928 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000929 Value *OriginLong = getShadowPtrOffset(Addr, IRB);
930 uint64_t OriginBase = MS.MapParams->OriginBase;
931 if (OriginBase != 0)
932 OriginLong =
933 IRB.CreateAdd(OriginLong,
934 ConstantInt::get(MS.IntptrTy, OriginBase));
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000935 if (Alignment < kMinOriginAlignment) {
936 uint64_t Mask = kMinOriginAlignment - 1;
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000937 OriginLong = IRB.CreateAnd(OriginLong,
938 ConstantInt::get(MS.IntptrTy, ~Mask));
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000939 }
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000940 return IRB.CreateIntToPtr(OriginLong,
941 PointerType::get(IRB.getInt32Ty(), 0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000942 }
943
944 /// \brief Compute the shadow address for a given function argument.
945 ///
946 /// Shadow = ParamTLS+ArgOffset.
947 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
948 int ArgOffset) {
949 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
950 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
951 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
952 "_msarg");
953 }
954
955 /// \brief Compute the origin address for a given function argument.
956 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
957 int ArgOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +0000958 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000959 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
960 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
961 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
962 "_msarg_o");
963 }
964
965 /// \brief Compute the shadow address for a retval.
966 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
967 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
968 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
969 "_msret");
970 }
971
972 /// \brief Compute the origin address for a retval.
973 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
974 // We keep a single origin for the entire retval. Might be too optimistic.
975 return MS.RetvalOriginTLS;
976 }
977
978 /// \brief Set SV to be the shadow value for V.
979 void setShadow(Value *V, Value *SV) {
980 assert(!ShadowMap.count(V) && "Values may only have one shadow");
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000981 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000982 }
983
984 /// \brief Set Origin to be the origin value for V.
985 void setOrigin(Value *V, Value *Origin) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000986 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000987 assert(!OriginMap.count(V) && "Values may only have one origin");
988 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
989 OriginMap[V] = Origin;
990 }
991
992 /// \brief Create a clean shadow value for a given value.
993 ///
994 /// Clean shadow (all zeroes) means all bits of the value are defined
995 /// (initialized).
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000996 Constant *getCleanShadow(Value *V) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000997 Type *ShadowTy = getShadowTy(V);
998 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000999 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001000 return Constant::getNullValue(ShadowTy);
1001 }
1002
1003 /// \brief Create a dirty shadow of a given shadow type.
1004 Constant *getPoisonedShadow(Type *ShadowTy) {
1005 assert(ShadowTy);
1006 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
1007 return Constant::getAllOnesValue(ShadowTy);
Evgeniy Stepanov5997feb2014-07-31 11:02:27 +00001008 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
1009 SmallVector<Constant *, 4> Vals(AT->getNumElements(),
1010 getPoisonedShadow(AT->getElementType()));
1011 return ConstantArray::get(AT, Vals);
1012 }
1013 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
1014 SmallVector<Constant *, 4> Vals;
1015 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1016 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1017 return ConstantStruct::get(ST, Vals);
1018 }
1019 llvm_unreachable("Unexpected shadow type");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001020 }
1021
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +00001022 /// \brief Create a dirty shadow for a given value.
1023 Constant *getPoisonedShadow(Value *V) {
1024 Type *ShadowTy = getShadowTy(V);
1025 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +00001026 return nullptr;
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +00001027 return getPoisonedShadow(ShadowTy);
1028 }
1029
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001030 /// \brief Create a clean (zero) origin.
1031 Value *getCleanOrigin() {
1032 return Constant::getNullValue(MS.OriginTy);
1033 }
1034
1035 /// \brief Get the shadow value for a given Value.
1036 ///
1037 /// This function either returns the value set earlier with setShadow,
1038 /// or extracts if from ParamTLS (for function arguments).
1039 Value *getShadow(Value *V) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001040 if (!PropagateShadow) return getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001041 if (Instruction *I = dyn_cast<Instruction>(V)) {
1042 // For instructions the shadow is already stored in the map.
1043 Value *Shadow = ShadowMap[V];
1044 if (!Shadow) {
1045 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001046 (void)I;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001047 assert(Shadow && "No shadow for a value");
1048 }
1049 return Shadow;
1050 }
1051 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00001052 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001053 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001054 (void)U;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001055 return AllOnes;
1056 }
1057 if (Argument *A = dyn_cast<Argument>(V)) {
1058 // For arguments we compute the shadow on demand and store it in the map.
1059 Value **ShadowPtr = &ShadowMap[V];
1060 if (*ShadowPtr)
1061 return *ShadowPtr;
1062 Function *F = A->getParent();
1063 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
1064 unsigned ArgOffset = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001065 const DataLayout &DL = F->getParent()->getDataLayout();
Alexey Samsonova02e6642014-05-29 18:40:48 +00001066 for (auto &FArg : F->args()) {
1067 if (!FArg.getType()->isSized()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001068 DEBUG(dbgs() << "Arg is not sized\n");
1069 continue;
1070 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001071 unsigned Size =
1072 FArg.hasByValAttr()
1073 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
1074 : DL.getTypeAllocSize(FArg.getType());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001075 if (A == &FArg) {
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001076 bool Overflow = ArgOffset + Size > kParamTLSSize;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001077 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1078 if (FArg.hasByValAttr()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001079 // ByVal pointer itself has clean shadow. We copy the actual
1080 // argument shadow to the underlying memory.
Evgeniy Stepanovfca01232013-05-28 13:07:43 +00001081 // Figure out maximal valid memcpy alignment.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001082 unsigned ArgAlign = FArg.getParamAlignment();
Evgeniy Stepanovfca01232013-05-28 13:07:43 +00001083 if (ArgAlign == 0) {
1084 Type *EltType = A->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001085 ArgAlign = DL.getABITypeAlignment(EltType);
Evgeniy Stepanovfca01232013-05-28 13:07:43 +00001086 }
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001087 if (Overflow) {
1088 // ParamTLS overflow.
1089 EntryIRB.CreateMemSet(
1090 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
1091 Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
1092 } else {
1093 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1094 Value *Cpy = EntryIRB.CreateMemCpy(
1095 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
1096 CopyAlign);
1097 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
1098 (void)Cpy;
1099 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001100 *ShadowPtr = getCleanShadow(V);
1101 } else {
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001102 if (Overflow) {
1103 // ParamTLS overflow.
1104 *ShadowPtr = getCleanShadow(V);
1105 } else {
1106 *ShadowPtr =
1107 EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1108 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001109 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001110 DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001111 **ShadowPtr << "\n");
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001112 if (MS.TrackOrigins && !Overflow) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001113 Value *OriginPtr =
1114 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001115 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00001116 } else {
1117 setOrigin(A, getCleanOrigin());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001118 }
1119 }
David Majnemerf3cadce2014-10-20 06:13:33 +00001120 ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001121 }
1122 assert(*ShadowPtr && "Could not find shadow for an argument");
1123 return *ShadowPtr;
1124 }
1125 // For everything else the shadow is zero.
1126 return getCleanShadow(V);
1127 }
1128
1129 /// \brief Get the shadow for i-th argument of the instruction I.
1130 Value *getShadow(Instruction *I, int i) {
1131 return getShadow(I->getOperand(i));
1132 }
1133
1134 /// \brief Get the origin for a value.
1135 Value *getOrigin(Value *V) {
Craig Topperf40110f2014-04-25 05:29:35 +00001136 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00001137 if (!PropagateShadow) return getCleanOrigin();
1138 if (isa<Constant>(V)) return getCleanOrigin();
1139 assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1140 "Unexpected value type in getOrigin()");
1141 Value *Origin = OriginMap[V];
1142 assert(Origin && "Missing origin");
1143 return Origin;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001144 }
1145
1146 /// \brief Get the origin for i-th argument of the instruction I.
1147 Value *getOrigin(Instruction *I, int i) {
1148 return getOrigin(I->getOperand(i));
1149 }
1150
1151 /// \brief Remember the place where a shadow check should be inserted.
1152 ///
1153 /// This location will be later instrumented with a check that will print a
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001154 /// UMR warning in runtime if the shadow value is not 0.
1155 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1156 assert(Shadow);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001157 if (!InsertChecks) return;
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001158#ifndef NDEBUG
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001159 Type *ShadowTy = Shadow->getType();
1160 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1161 "Can only insert checks for integer and vector shadow types");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001162#endif
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001163 InstrumentationList.push_back(
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001164 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1165 }
1166
1167 /// \brief Remember the place where a shadow check should be inserted.
1168 ///
1169 /// This location will be later instrumented with a check that will print a
1170 /// UMR warning in runtime if the value is not fully defined.
1171 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1172 assert(Val);
Evgeniy Stepanovd337a592014-10-24 23:34:15 +00001173 Value *Shadow, *Origin;
1174 if (ClCheckConstantShadow) {
1175 Shadow = getShadow(Val);
1176 if (!Shadow) return;
1177 Origin = getOrigin(Val);
1178 } else {
1179 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1180 if (!Shadow) return;
1181 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1182 }
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001183 insertShadowCheck(Shadow, Origin, OrigIns);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001184 }
1185
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001186 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1187 switch (a) {
1188 case NotAtomic:
1189 return NotAtomic;
1190 case Unordered:
1191 case Monotonic:
1192 case Release:
1193 return Release;
1194 case Acquire:
1195 case AcquireRelease:
1196 return AcquireRelease;
1197 case SequentiallyConsistent:
1198 return SequentiallyConsistent;
1199 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001200 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001201 }
1202
1203 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1204 switch (a) {
1205 case NotAtomic:
1206 return NotAtomic;
1207 case Unordered:
1208 case Monotonic:
1209 case Acquire:
1210 return Acquire;
1211 case Release:
1212 case AcquireRelease:
1213 return AcquireRelease;
1214 case SequentiallyConsistent:
1215 return SequentiallyConsistent;
1216 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001217 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001218 }
1219
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001220 // ------------------- Visitors.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001221
1222 /// \brief Instrument LoadInst
1223 ///
1224 /// Loads the corresponding shadow and (optionally) origin.
1225 /// Optionally, checks that the load address is fully defined.
1226 void visitLoadInst(LoadInst &I) {
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001227 assert(I.getType()->isSized() && "Load type must have size");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001228 IRBuilder<> IRB(I.getNextNode());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001229 Type *ShadowTy = getShadowTy(&I);
1230 Value *Addr = I.getPointerOperand();
Kostya Serebryany543f3db2014-12-03 23:28:26 +00001231 if (PropagateShadow && !I.getMetadata("nosanitize")) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001232 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1233 setShadow(&I,
1234 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1235 } else {
1236 setShadow(&I, getCleanShadow(&I));
1237 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001238
1239 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001240 insertShadowCheck(I.getPointerOperand(), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001241
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001242 if (I.isAtomic())
1243 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1244
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001245 if (MS.TrackOrigins) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001246 if (PropagateShadow) {
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00001247 unsigned Alignment = I.getAlignment();
1248 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1249 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
1250 OriginAlignment));
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001251 } else {
1252 setOrigin(&I, getCleanOrigin());
1253 }
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001254 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001255 }
1256
1257 /// \brief Instrument StoreInst
1258 ///
1259 /// Stores the corresponding shadow and (optionally) origin.
1260 /// Optionally, checks that the store address is fully defined.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001261 void visitStoreInst(StoreInst &I) {
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +00001262 StoreList.push_back(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001263 }
1264
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001265 void handleCASOrRMW(Instruction &I) {
1266 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1267
1268 IRBuilder<> IRB(&I);
1269 Value *Addr = I.getOperand(0);
1270 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1271
1272 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001273 insertShadowCheck(Addr, &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001274
1275 // Only test the conditional argument of cmpxchg instruction.
1276 // The other argument can potentially be uninitialized, but we can not
1277 // detect this situation reliably without possible false positives.
1278 if (isa<AtomicCmpXchgInst>(I))
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001279 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001280
1281 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1282
1283 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00001284 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001285 }
1286
1287 void visitAtomicRMWInst(AtomicRMWInst &I) {
1288 handleCASOrRMW(I);
1289 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1290 }
1291
1292 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1293 handleCASOrRMW(I);
Tim Northovere94a5182014-03-11 10:48:52 +00001294 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001295 }
1296
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001297 // Vector manipulation.
1298 void visitExtractElementInst(ExtractElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001299 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001300 IRBuilder<> IRB(&I);
1301 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1302 "_msprop"));
1303 setOrigin(&I, getOrigin(&I, 0));
1304 }
1305
1306 void visitInsertElementInst(InsertElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001307 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001308 IRBuilder<> IRB(&I);
1309 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1310 I.getOperand(2), "_msprop"));
1311 setOriginForNaryOp(I);
1312 }
1313
1314 void visitShuffleVectorInst(ShuffleVectorInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001315 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001316 IRBuilder<> IRB(&I);
1317 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1318 I.getOperand(2), "_msprop"));
1319 setOriginForNaryOp(I);
1320 }
1321
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001322 // Casts.
1323 void visitSExtInst(SExtInst &I) {
1324 IRBuilder<> IRB(&I);
1325 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1326 setOrigin(&I, getOrigin(&I, 0));
1327 }
1328
1329 void visitZExtInst(ZExtInst &I) {
1330 IRBuilder<> IRB(&I);
1331 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1332 setOrigin(&I, getOrigin(&I, 0));
1333 }
1334
1335 void visitTruncInst(TruncInst &I) {
1336 IRBuilder<> IRB(&I);
1337 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1338 setOrigin(&I, getOrigin(&I, 0));
1339 }
1340
1341 void visitBitCastInst(BitCastInst &I) {
Evgeniy Stepanov24ac55d2015-08-14 22:03:50 +00001342 // Special case: if this is the bitcast (there is exactly 1 allowed) between
1343 // a musttail call and a ret, don't instrument. New instructions are not
1344 // allowed after a musttail call.
1345 if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
1346 if (CI->isMustTailCall())
1347 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001348 IRBuilder<> IRB(&I);
1349 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1350 setOrigin(&I, getOrigin(&I, 0));
1351 }
1352
1353 void visitPtrToIntInst(PtrToIntInst &I) {
1354 IRBuilder<> IRB(&I);
1355 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1356 "_msprop_ptrtoint"));
1357 setOrigin(&I, getOrigin(&I, 0));
1358 }
1359
1360 void visitIntToPtrInst(IntToPtrInst &I) {
1361 IRBuilder<> IRB(&I);
1362 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1363 "_msprop_inttoptr"));
1364 setOrigin(&I, getOrigin(&I, 0));
1365 }
1366
1367 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1368 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1369 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1370 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1371 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1372 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1373
1374 /// \brief Propagate shadow for bitwise AND.
1375 ///
1376 /// This code is exact, i.e. if, for example, a bit in the left argument
1377 /// is defined and 0, then neither the value not definedness of the
1378 /// corresponding bit in B don't affect the resulting shadow.
1379 void visitAnd(BinaryOperator &I) {
1380 IRBuilder<> IRB(&I);
1381 // "And" of 0 and a poisoned value results in unpoisoned value.
1382 // 1&1 => 1; 0&1 => 0; p&1 => p;
1383 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1384 // 1&p => p; 0&p => 0; p&p => p;
1385 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1386 Value *S1 = getShadow(&I, 0);
1387 Value *S2 = getShadow(&I, 1);
1388 Value *V1 = I.getOperand(0);
1389 Value *V2 = I.getOperand(1);
1390 if (V1->getType() != S1->getType()) {
1391 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1392 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1393 }
1394 Value *S1S2 = IRB.CreateAnd(S1, S2);
1395 Value *V1S2 = IRB.CreateAnd(V1, S2);
1396 Value *S1V2 = IRB.CreateAnd(S1, V2);
1397 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1398 setOriginForNaryOp(I);
1399 }
1400
1401 void visitOr(BinaryOperator &I) {
1402 IRBuilder<> IRB(&I);
1403 // "Or" of 1 and a poisoned value results in unpoisoned value.
1404 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1405 // 1|0 => 1; 0|0 => 0; p|0 => p;
1406 // 1|p => 1; 0|p => p; p|p => p;
1407 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1408 Value *S1 = getShadow(&I, 0);
1409 Value *S2 = getShadow(&I, 1);
1410 Value *V1 = IRB.CreateNot(I.getOperand(0));
1411 Value *V2 = IRB.CreateNot(I.getOperand(1));
1412 if (V1->getType() != S1->getType()) {
1413 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1414 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1415 }
1416 Value *S1S2 = IRB.CreateAnd(S1, S2);
1417 Value *V1S2 = IRB.CreateAnd(V1, S2);
1418 Value *S1V2 = IRB.CreateAnd(S1, V2);
1419 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1420 setOriginForNaryOp(I);
1421 }
1422
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001423 /// \brief Default propagation of shadow and/or origin.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001424 ///
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001425 /// This class implements the general case of shadow propagation, used in all
1426 /// cases where we don't know and/or don't care about what the operation
1427 /// actually does. It converts all input shadow values to a common type
1428 /// (extending or truncating as necessary), and bitwise OR's them.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001429 ///
1430 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1431 /// fully initialized), and less prone to false positives.
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001432 ///
1433 /// This class also implements the general case of origin propagation. For a
1434 /// Nary operation, result origin is set to the origin of an argument that is
1435 /// not entirely initialized. If there is more than one such arguments, the
1436 /// rightmost of them is picked. It does not matter which one is picked if all
1437 /// arguments are initialized.
1438 template <bool CombineShadow>
1439 class Combiner {
1440 Value *Shadow;
1441 Value *Origin;
1442 IRBuilder<> &IRB;
1443 MemorySanitizerVisitor *MSV;
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001444
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001445 public:
1446 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
Craig Topperf40110f2014-04-25 05:29:35 +00001447 Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001448
1449 /// \brief Add a pair of shadow and origin values to the mix.
1450 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1451 if (CombineShadow) {
1452 assert(OpShadow);
1453 if (!Shadow)
1454 Shadow = OpShadow;
1455 else {
1456 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1457 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1458 }
1459 }
1460
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001461 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001462 assert(OpOrigin);
1463 if (!Origin) {
1464 Origin = OpOrigin;
1465 } else {
Evgeniy Stepanov70d1b0a2014-06-09 14:29:34 +00001466 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1467 // No point in adding something that might result in 0 origin value.
1468 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1469 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1470 Value *Cond =
1471 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1472 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1473 }
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001474 }
1475 }
1476 return *this;
1477 }
1478
1479 /// \brief Add an application value to the mix.
1480 Combiner &Add(Value *V) {
1481 Value *OpShadow = MSV->getShadow(V);
Craig Topperf40110f2014-04-25 05:29:35 +00001482 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001483 return Add(OpShadow, OpOrigin);
1484 }
1485
1486 /// \brief Set the current combined values as the given instruction's shadow
1487 /// and origin.
1488 void Done(Instruction *I) {
1489 if (CombineShadow) {
1490 assert(Shadow);
1491 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1492 MSV->setShadow(I, Shadow);
1493 }
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001494 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001495 assert(Origin);
1496 MSV->setOrigin(I, Origin);
1497 }
1498 }
1499 };
1500
1501 typedef Combiner<true> ShadowAndOriginCombiner;
1502 typedef Combiner<false> OriginCombiner;
1503
1504 /// \brief Propagate origin for arbitrary operation.
1505 void setOriginForNaryOp(Instruction &I) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001506 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001507 IRBuilder<> IRB(&I);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001508 OriginCombiner OC(this, IRB);
1509 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1510 OC.Add(OI->get());
1511 OC.Done(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001512 }
1513
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001514 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +00001515 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1516 "Vector of pointers is not a valid shadow type");
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001517 return Ty->isVectorTy() ?
1518 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1519 Ty->getPrimitiveSizeInBits();
1520 }
1521
1522 /// \brief Cast between two shadow types, extending or truncating as
1523 /// necessary.
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001524 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1525 bool Signed = false) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001526 Type *srcTy = V->getType();
1527 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001528 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001529 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1530 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001531 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001532 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1533 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1534 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1535 Value *V2 =
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001536 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001537 return IRB.CreateBitCast(V2, dstTy);
1538 // TODO: handle struct types.
1539 }
1540
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00001541 /// \brief Cast an application value to the type of its own shadow.
1542 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1543 Type *ShadowTy = getShadowTy(V);
1544 if (V->getType() == ShadowTy)
1545 return V;
1546 if (V->getType()->isPtrOrPtrVectorTy())
1547 return IRB.CreatePtrToInt(V, ShadowTy);
1548 else
1549 return IRB.CreateBitCast(V, ShadowTy);
1550 }
1551
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001552 /// \brief Propagate shadow for arbitrary operation.
1553 void handleShadowOr(Instruction &I) {
1554 IRBuilder<> IRB(&I);
1555 ShadowAndOriginCombiner SC(this, IRB);
1556 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1557 SC.Add(OI->get());
1558 SC.Done(&I);
1559 }
1560
Evgeniy Stepanovdf187fe2014-06-17 09:23:12 +00001561 // \brief Handle multiplication by constant.
1562 //
1563 // Handle a special case of multiplication by constant that may have one or
1564 // more zeros in the lower bits. This makes corresponding number of lower bits
1565 // of the result zero as well. We model it by shifting the other operand
1566 // shadow left by the required number of bits. Effectively, we transform
1567 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1568 // We use multiplication by 2**N instead of shift to cover the case of
1569 // multiplication by 0, which may occur in some elements of a vector operand.
1570 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1571 Value *OtherArg) {
1572 Constant *ShadowMul;
1573 Type *Ty = ConstArg->getType();
1574 if (Ty->isVectorTy()) {
1575 unsigned NumElements = Ty->getVectorNumElements();
1576 Type *EltTy = Ty->getSequentialElementType();
1577 SmallVector<Constant *, 16> Elements;
1578 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1579 ConstantInt *Elt =
1580 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1581 APInt V = Elt->getValue();
1582 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1583 Elements.push_back(ConstantInt::get(EltTy, V2));
1584 }
1585 ShadowMul = ConstantVector::get(Elements);
1586 } else {
1587 ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1588 APInt V = Elt->getValue();
1589 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1590 ShadowMul = ConstantInt::get(Elt->getType(), V2);
1591 }
1592
1593 IRBuilder<> IRB(&I);
1594 setShadow(&I,
1595 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1596 setOrigin(&I, getOrigin(OtherArg));
1597 }
1598
1599 void visitMul(BinaryOperator &I) {
1600 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1601 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1602 if (constOp0 && !constOp1)
1603 handleMulByConstant(I, constOp0, I.getOperand(1));
1604 else if (constOp1 && !constOp0)
1605 handleMulByConstant(I, constOp1, I.getOperand(0));
1606 else
1607 handleShadowOr(I);
1608 }
1609
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001610 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1611 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1612 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1613 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1614 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1615 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001616
1617 void handleDiv(Instruction &I) {
1618 IRBuilder<> IRB(&I);
1619 // Strict on the second argument.
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001620 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001621 setShadow(&I, getShadow(&I, 0));
1622 setOrigin(&I, getOrigin(&I, 0));
1623 }
1624
1625 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1626 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1627 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1628 void visitURem(BinaryOperator &I) { handleDiv(I); }
1629 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1630 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1631
1632 /// \brief Instrument == and != comparisons.
1633 ///
1634 /// Sometimes the comparison result is known even if some of the bits of the
1635 /// arguments are not.
1636 void handleEqualityComparison(ICmpInst &I) {
1637 IRBuilder<> IRB(&I);
1638 Value *A = I.getOperand(0);
1639 Value *B = I.getOperand(1);
1640 Value *Sa = getShadow(A);
1641 Value *Sb = getShadow(B);
Evgeniy Stepanovd14e47b2013-01-15 16:44:52 +00001642
1643 // Get rid of pointers and vectors of pointers.
1644 // For ints (and vectors of ints), types of A and Sa match,
1645 // and this is a no-op.
1646 A = IRB.CreatePointerCast(A, Sa->getType());
1647 B = IRB.CreatePointerCast(B, Sb->getType());
1648
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001649 // A == B <==> (C = A^B) == 0
1650 // A != B <==> (C = A^B) != 0
1651 // Sc = Sa | Sb
1652 Value *C = IRB.CreateXor(A, B);
1653 Value *Sc = IRB.CreateOr(Sa, Sb);
1654 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1655 // Result is defined if one of the following is true
1656 // * there is a defined 1 bit in C
1657 // * C is fully defined
1658 // Si = !(C & ~Sc) && Sc
1659 Value *Zero = Constant::getNullValue(Sc->getType());
1660 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1661 Value *Si =
1662 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1663 IRB.CreateICmpEQ(
1664 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1665 Si->setName("_msprop_icmp");
1666 setShadow(&I, Si);
1667 setOriginForNaryOp(I);
1668 }
1669
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001670 /// \brief Build the lowest possible value of V, taking into account V's
1671 /// uninitialized bits.
1672 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1673 bool isSigned) {
1674 if (isSigned) {
1675 // Split shadow into sign bit and other bits.
1676 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1677 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1678 // Maximise the undefined shadow bit, minimize other undefined bits.
1679 return
1680 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1681 } else {
1682 // Minimize undefined bits.
1683 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1684 }
1685 }
1686
1687 /// \brief Build the highest possible value of V, taking into account V's
1688 /// uninitialized bits.
1689 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1690 bool isSigned) {
1691 if (isSigned) {
1692 // Split shadow into sign bit and other bits.
1693 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1694 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1695 // Minimise the undefined shadow bit, maximise other undefined bits.
1696 return
1697 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1698 } else {
1699 // Maximize undefined bits.
1700 return IRB.CreateOr(A, Sa);
1701 }
1702 }
1703
1704 /// \brief Instrument relational comparisons.
1705 ///
1706 /// This function does exact shadow propagation for all relational
1707 /// comparisons of integers, pointers and vectors of those.
1708 /// FIXME: output seems suboptimal when one of the operands is a constant
1709 void handleRelationalComparisonExact(ICmpInst &I) {
1710 IRBuilder<> IRB(&I);
1711 Value *A = I.getOperand(0);
1712 Value *B = I.getOperand(1);
1713 Value *Sa = getShadow(A);
1714 Value *Sb = getShadow(B);
1715
1716 // Get rid of pointers and vectors of pointers.
1717 // For ints (and vectors of ints), types of A and Sa match,
1718 // and this is a no-op.
1719 A = IRB.CreatePointerCast(A, Sa->getType());
1720 B = IRB.CreatePointerCast(B, Sb->getType());
1721
Evgeniy Stepanov2cb0fa12013-01-25 15:35:29 +00001722 // Let [a0, a1] be the interval of possible values of A, taking into account
1723 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1724 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001725 bool IsSigned = I.isSigned();
1726 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1727 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1728 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1729 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1730 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1731 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1732 Value *Si = IRB.CreateXor(S1, S2);
1733 setShadow(&I, Si);
1734 setOriginForNaryOp(I);
1735 }
1736
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001737 /// \brief Instrument signed relational comparisons.
1738 ///
1739 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1740 /// propagating the highest bit of the shadow. Everything else is delegated
1741 /// to handleShadowOr().
1742 void handleSignedRelationalComparison(ICmpInst &I) {
1743 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1744 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +00001745 Value* op = nullptr;
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001746 CmpInst::Predicate pre = I.getPredicate();
1747 if (constOp0 && constOp0->isNullValue() &&
1748 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1749 op = I.getOperand(1);
1750 } else if (constOp1 && constOp1->isNullValue() &&
1751 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1752 op = I.getOperand(0);
1753 }
1754 if (op) {
1755 IRBuilder<> IRB(&I);
1756 Value* Shadow =
1757 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1758 setShadow(&I, Shadow);
1759 setOrigin(&I, getOrigin(op));
1760 } else {
1761 handleShadowOr(I);
1762 }
1763 }
1764
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001765 void visitICmpInst(ICmpInst &I) {
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001766 if (!ClHandleICmp) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001767 handleShadowOr(I);
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001768 return;
1769 }
1770 if (I.isEquality()) {
1771 handleEqualityComparison(I);
1772 return;
1773 }
1774
1775 assert(I.isRelational());
1776 if (ClHandleICmpExact) {
1777 handleRelationalComparisonExact(I);
1778 return;
1779 }
1780 if (I.isSigned()) {
1781 handleSignedRelationalComparison(I);
1782 return;
1783 }
1784
1785 assert(I.isUnsigned());
1786 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1787 handleRelationalComparisonExact(I);
1788 return;
1789 }
1790
1791 handleShadowOr(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001792 }
1793
1794 void visitFCmpInst(FCmpInst &I) {
1795 handleShadowOr(I);
1796 }
1797
1798 void handleShift(BinaryOperator &I) {
1799 IRBuilder<> IRB(&I);
1800 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1801 // Otherwise perform the same shift on S1.
1802 Value *S1 = getShadow(&I, 0);
1803 Value *S2 = getShadow(&I, 1);
1804 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1805 S2->getType());
1806 Value *V2 = I.getOperand(1);
1807 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1808 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1809 setOriginForNaryOp(I);
1810 }
1811
1812 void visitShl(BinaryOperator &I) { handleShift(I); }
1813 void visitAShr(BinaryOperator &I) { handleShift(I); }
1814 void visitLShr(BinaryOperator &I) { handleShift(I); }
1815
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001816 /// \brief Instrument llvm.memmove
1817 ///
1818 /// At this point we don't know if llvm.memmove will be inlined or not.
1819 /// If we don't instrument it and it gets inlined,
1820 /// our interceptor will not kick in and we will lose the memmove.
1821 /// If we instrument the call here, but it does not get inlined,
1822 /// we will memove the shadow twice: which is bad in case
1823 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1824 ///
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001825 /// Similar situation exists for memcpy and memset.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001826 void visitMemMoveInst(MemMoveInst &I) {
1827 IRBuilder<> IRB(&I);
David Blaikieff6409d2015-05-18 22:13:54 +00001828 IRB.CreateCall(
1829 MS.MemmoveFn,
1830 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1831 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1832 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001833 I.eraseFromParent();
1834 }
1835
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001836 // Similar to memmove: avoid copying shadow twice.
1837 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1838 // FIXME: consider doing manual inline for small constant sizes and proper
1839 // alignment.
1840 void visitMemCpyInst(MemCpyInst &I) {
1841 IRBuilder<> IRB(&I);
David Blaikieff6409d2015-05-18 22:13:54 +00001842 IRB.CreateCall(
1843 MS.MemcpyFn,
1844 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1845 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1846 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001847 I.eraseFromParent();
1848 }
1849
1850 // Same as memcpy.
1851 void visitMemSetInst(MemSetInst &I) {
1852 IRBuilder<> IRB(&I);
David Blaikieff6409d2015-05-18 22:13:54 +00001853 IRB.CreateCall(
1854 MS.MemsetFn,
1855 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1856 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1857 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001858 I.eraseFromParent();
1859 }
1860
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001861 void visitVAStartInst(VAStartInst &I) {
1862 VAHelper->visitVAStartInst(I);
1863 }
1864
1865 void visitVACopyInst(VACopyInst &I) {
1866 VAHelper->visitVACopyInst(I);
1867 }
1868
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001869 enum IntrinsicKind {
1870 IK_DoesNotAccessMemory,
1871 IK_OnlyReadsMemory,
1872 IK_WritesMemory
1873 };
1874
1875 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
Chandler Carruth194f59c2015-07-22 23:15:57 +00001876 const int FMRB_DoesNotAccessMemory = IK_DoesNotAccessMemory;
1877 const int FMRB_OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1878 const int FMRB_OnlyReadsMemory = IK_OnlyReadsMemory;
1879 const int FMRB_OnlyAccessesArgumentPointees = IK_WritesMemory;
1880 const int FMRB_UnknownModRefBehavior = IK_WritesMemory;
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001881#define GET_INTRINSIC_MODREF_BEHAVIOR
Chandler Carruth194f59c2015-07-22 23:15:57 +00001882#define FunctionModRefBehavior IntrinsicKind
Chandler Carruthdb25c6c2013-01-02 12:09:16 +00001883#include "llvm/IR/Intrinsics.gen"
Chandler Carruth194f59c2015-07-22 23:15:57 +00001884#undef FunctionModRefBehavior
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001885#undef GET_INTRINSIC_MODREF_BEHAVIOR
1886 }
1887
1888 /// \brief Handle vector store-like intrinsics.
1889 ///
1890 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1891 /// has 1 pointer argument and 1 vector argument, returns void.
1892 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1893 IRBuilder<> IRB(&I);
1894 Value* Addr = I.getArgOperand(0);
1895 Value *Shadow = getShadow(&I, 1);
1896 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1897
1898 // We don't know the pointer alignment (could be unaligned SSE store!).
1899 // Have to assume to worst case.
1900 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1901
1902 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001903 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001904
1905 // FIXME: use ClStoreCleanOrigin
1906 // FIXME: factor out common code from materializeStores
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001907 if (MS.TrackOrigins)
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00001908 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001909 return true;
1910 }
1911
1912 /// \brief Handle vector load-like intrinsics.
1913 ///
1914 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1915 /// has 1 pointer argument, returns a vector.
1916 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1917 IRBuilder<> IRB(&I);
1918 Value *Addr = I.getArgOperand(0);
1919
1920 Type *ShadowTy = getShadowTy(&I);
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001921 if (PropagateShadow) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001922 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1923 // We don't know the pointer alignment (could be unaligned SSE load!).
1924 // Have to assume to worst case.
1925 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1926 } else {
1927 setShadow(&I, getCleanShadow(&I));
1928 }
1929
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001930 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001931 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001932
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001933 if (MS.TrackOrigins) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001934 if (PropagateShadow)
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00001935 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001936 else
1937 setOrigin(&I, getCleanOrigin());
1938 }
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001939 return true;
1940 }
1941
1942 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1943 ///
1944 /// Instrument intrinsics with any number of arguments of the same type,
1945 /// equal to the return type. The type should be simple (no aggregates or
1946 /// pointers; vectors are fine).
1947 /// Caller guarantees that this intrinsic does not access memory.
1948 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1949 Type *RetTy = I.getType();
1950 if (!(RetTy->isIntOrIntVectorTy() ||
1951 RetTy->isFPOrFPVectorTy() ||
1952 RetTy->isX86_MMXTy()))
1953 return false;
1954
1955 unsigned NumArgOperands = I.getNumArgOperands();
1956
1957 for (unsigned i = 0; i < NumArgOperands; ++i) {
1958 Type *Ty = I.getArgOperand(i)->getType();
1959 if (Ty != RetTy)
1960 return false;
1961 }
1962
1963 IRBuilder<> IRB(&I);
1964 ShadowAndOriginCombiner SC(this, IRB);
1965 for (unsigned i = 0; i < NumArgOperands; ++i)
1966 SC.Add(I.getArgOperand(i));
1967 SC.Done(&I);
1968
1969 return true;
1970 }
1971
1972 /// \brief Heuristically instrument unknown intrinsics.
1973 ///
1974 /// The main purpose of this code is to do something reasonable with all
1975 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1976 /// We recognize several classes of intrinsics by their argument types and
1977 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1978 /// sure that we know what the intrinsic does.
1979 ///
1980 /// We special-case intrinsics where this approach fails. See llvm.bswap
1981 /// handling as an example of that.
1982 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1983 unsigned NumArgOperands = I.getNumArgOperands();
1984 if (NumArgOperands == 0)
1985 return false;
1986
1987 Intrinsic::ID iid = I.getIntrinsicID();
1988 IntrinsicKind IK = getIntrinsicKind(iid);
1989 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1990 bool WritesMemory = IK == IK_WritesMemory;
1991 assert(!(OnlyReadsMemory && WritesMemory));
1992
1993 if (NumArgOperands == 2 &&
1994 I.getArgOperand(0)->getType()->isPointerTy() &&
1995 I.getArgOperand(1)->getType()->isVectorTy() &&
1996 I.getType()->isVoidTy() &&
1997 WritesMemory) {
1998 // This looks like a vector store.
1999 return handleVectorStoreIntrinsic(I);
2000 }
2001
2002 if (NumArgOperands == 1 &&
2003 I.getArgOperand(0)->getType()->isPointerTy() &&
2004 I.getType()->isVectorTy() &&
2005 OnlyReadsMemory) {
2006 // This looks like a vector load.
2007 return handleVectorLoadIntrinsic(I);
2008 }
2009
2010 if (!OnlyReadsMemory && !WritesMemory)
2011 if (maybeHandleSimpleNomemIntrinsic(I))
2012 return true;
2013
2014 // FIXME: detect and handle SSE maskstore/maskload
2015 return false;
2016 }
2017
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002018 void handleBswap(IntrinsicInst &I) {
2019 IRBuilder<> IRB(&I);
2020 Value *Op = I.getArgOperand(0);
2021 Type *OpType = Op->getType();
2022 Function *BswapFunc = Intrinsic::getDeclaration(
Craig Toppere1d12942014-08-27 05:25:25 +00002023 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002024 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2025 setOrigin(&I, getOrigin(Op));
2026 }
2027
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002028 // \brief Instrument vector convert instrinsic.
2029 //
2030 // This function instruments intrinsics like cvtsi2ss:
2031 // %Out = int_xxx_cvtyyy(%ConvertOp)
2032 // or
2033 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2034 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2035 // number \p Out elements, and (if has 2 arguments) copies the rest of the
2036 // elements from \p CopyOp.
2037 // In most cases conversion involves floating-point value which may trigger a
2038 // hardware exception when not fully initialized. For this reason we require
2039 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2040 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2041 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2042 // return a fully initialized value.
2043 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2044 IRBuilder<> IRB(&I);
2045 Value *CopyOp, *ConvertOp;
2046
2047 switch (I.getNumArgOperands()) {
Igor Bregerdfcc3d32015-06-17 07:23:57 +00002048 case 3:
2049 assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002050 case 2:
2051 CopyOp = I.getArgOperand(0);
2052 ConvertOp = I.getArgOperand(1);
2053 break;
2054 case 1:
2055 ConvertOp = I.getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002056 CopyOp = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002057 break;
2058 default:
2059 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2060 }
2061
2062 // The first *NumUsedElements* elements of ConvertOp are converted to the
2063 // same number of output elements. The rest of the output is copied from
2064 // CopyOp, or (if not available) filled with zeroes.
2065 // Combine shadow for elements of ConvertOp that are used in this operation,
2066 // and insert a check.
2067 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2068 // int->any conversion.
2069 Value *ConvertShadow = getShadow(ConvertOp);
Craig Topperf40110f2014-04-25 05:29:35 +00002070 Value *AggShadow = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002071 if (ConvertOp->getType()->isVectorTy()) {
2072 AggShadow = IRB.CreateExtractElement(
2073 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2074 for (int i = 1; i < NumUsedElements; ++i) {
2075 Value *MoreShadow = IRB.CreateExtractElement(
2076 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2077 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2078 }
2079 } else {
2080 AggShadow = ConvertShadow;
2081 }
2082 assert(AggShadow->getType()->isIntegerTy());
2083 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2084
2085 // Build result shadow by zero-filling parts of CopyOp shadow that come from
2086 // ConvertOp.
2087 if (CopyOp) {
2088 assert(CopyOp->getType() == I.getType());
2089 assert(CopyOp->getType()->isVectorTy());
2090 Value *ResultShadow = getShadow(CopyOp);
2091 Type *EltTy = ResultShadow->getType()->getVectorElementType();
2092 for (int i = 0; i < NumUsedElements; ++i) {
2093 ResultShadow = IRB.CreateInsertElement(
2094 ResultShadow, ConstantInt::getNullValue(EltTy),
2095 ConstantInt::get(IRB.getInt32Ty(), i));
2096 }
2097 setShadow(&I, ResultShadow);
2098 setOrigin(&I, getOrigin(CopyOp));
2099 } else {
2100 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00002101 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002102 }
2103 }
2104
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002105 // Given a scalar or vector, extract lower 64 bits (or less), and return all
2106 // zeroes if it is zero, and all ones otherwise.
2107 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2108 if (S->getType()->isVectorTy())
2109 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2110 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2111 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2112 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2113 }
2114
2115 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2116 Type *T = S->getType();
2117 assert(T->isVectorTy());
2118 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2119 return IRB.CreateSExt(S2, T);
2120 }
2121
2122 // \brief Instrument vector shift instrinsic.
2123 //
2124 // This function instruments intrinsics like int_x86_avx2_psll_w.
2125 // Intrinsic shifts %In by %ShiftSize bits.
2126 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2127 // size, and the rest is ignored. Behavior is defined even if shift size is
2128 // greater than register (or field) width.
2129 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2130 assert(I.getNumArgOperands() == 2);
2131 IRBuilder<> IRB(&I);
2132 // If any of the S2 bits are poisoned, the whole thing is poisoned.
2133 // Otherwise perform the same shift on S1.
2134 Value *S1 = getShadow(&I, 0);
2135 Value *S2 = getShadow(&I, 1);
2136 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2137 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2138 Value *V1 = I.getOperand(0);
2139 Value *V2 = I.getOperand(1);
David Blaikieff6409d2015-05-18 22:13:54 +00002140 Value *Shift = IRB.CreateCall(I.getCalledValue(),
2141 {IRB.CreateBitCast(S1, V1->getType()), V2});
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002142 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2143 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2144 setOriginForNaryOp(I);
2145 }
2146
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002147 // \brief Get an X86_MMX-sized vector type.
2148 Type *getMMXVectorTy(unsigned EltSizeInBits) {
2149 const unsigned X86_MMXSizeInBits = 64;
2150 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2151 X86_MMXSizeInBits / EltSizeInBits);
2152 }
2153
2154 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2155 // intrinsic.
2156 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2157 switch (id) {
2158 case llvm::Intrinsic::x86_sse2_packsswb_128:
2159 case llvm::Intrinsic::x86_sse2_packuswb_128:
2160 return llvm::Intrinsic::x86_sse2_packsswb_128;
2161
2162 case llvm::Intrinsic::x86_sse2_packssdw_128:
2163 case llvm::Intrinsic::x86_sse41_packusdw:
2164 return llvm::Intrinsic::x86_sse2_packssdw_128;
2165
2166 case llvm::Intrinsic::x86_avx2_packsswb:
2167 case llvm::Intrinsic::x86_avx2_packuswb:
2168 return llvm::Intrinsic::x86_avx2_packsswb;
2169
2170 case llvm::Intrinsic::x86_avx2_packssdw:
2171 case llvm::Intrinsic::x86_avx2_packusdw:
2172 return llvm::Intrinsic::x86_avx2_packssdw;
2173
2174 case llvm::Intrinsic::x86_mmx_packsswb:
2175 case llvm::Intrinsic::x86_mmx_packuswb:
2176 return llvm::Intrinsic::x86_mmx_packsswb;
2177
2178 case llvm::Intrinsic::x86_mmx_packssdw:
2179 return llvm::Intrinsic::x86_mmx_packssdw;
2180 default:
2181 llvm_unreachable("unexpected intrinsic id");
2182 }
2183 }
2184
Evgeniy Stepanov5d972932014-06-17 11:26:00 +00002185 // \brief Instrument vector pack instrinsic.
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002186 //
2187 // This function instruments intrinsics like x86_mmx_packsswb, that
Evgeniy Stepanov5d972932014-06-17 11:26:00 +00002188 // packs elements of 2 input vectors into half as many bits with saturation.
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002189 // Shadow is propagated with the signed variant of the same intrinsic applied
2190 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2191 // EltSizeInBits is used only for x86mmx arguments.
2192 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002193 assert(I.getNumArgOperands() == 2);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002194 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002195 IRBuilder<> IRB(&I);
2196 Value *S1 = getShadow(&I, 0);
2197 Value *S2 = getShadow(&I, 1);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002198 assert(isX86_MMX || S1->getType()->isVectorTy());
2199
2200 // SExt and ICmpNE below must apply to individual elements of input vectors.
2201 // In case of x86mmx arguments, cast them to appropriate vector types and
2202 // back.
2203 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2204 if (isX86_MMX) {
2205 S1 = IRB.CreateBitCast(S1, T);
2206 S2 = IRB.CreateBitCast(S2, T);
2207 }
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002208 Value *S1_ext = IRB.CreateSExt(
2209 IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2210 Value *S2_ext = IRB.CreateSExt(
2211 IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002212 if (isX86_MMX) {
2213 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2214 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2215 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2216 }
2217
2218 Function *ShadowFn = Intrinsic::getDeclaration(
2219 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2220
David Blaikieff6409d2015-05-18 22:13:54 +00002221 Value *S =
2222 IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002223 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002224 setShadow(&I, S);
2225 setOriginForNaryOp(I);
2226 }
2227
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002228 // \brief Instrument sum-of-absolute-differencies intrinsic.
2229 void handleVectorSadIntrinsic(IntrinsicInst &I) {
2230 const unsigned SignificantBitsPerResultElement = 16;
2231 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2232 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2233 unsigned ZeroBitsPerResultElement =
2234 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2235
2236 IRBuilder<> IRB(&I);
2237 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2238 S = IRB.CreateBitCast(S, ResTy);
2239 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2240 ResTy);
2241 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2242 S = IRB.CreateBitCast(S, getShadowTy(&I));
2243 setShadow(&I, S);
2244 setOriginForNaryOp(I);
2245 }
2246
2247 // \brief Instrument multiply-add intrinsic.
2248 void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2249 unsigned EltSizeInBits = 0) {
2250 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2251 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2252 IRBuilder<> IRB(&I);
2253 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2254 S = IRB.CreateBitCast(S, ResTy);
2255 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2256 ResTy);
2257 S = IRB.CreateBitCast(S, getShadowTy(&I));
2258 setShadow(&I, S);
2259 setOriginForNaryOp(I);
2260 }
2261
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002262 void visitIntrinsicInst(IntrinsicInst &I) {
2263 switch (I.getIntrinsicID()) {
2264 case llvm::Intrinsic::bswap:
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002265 handleBswap(I);
2266 break;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002267 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2268 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2269 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2270 case llvm::Intrinsic::x86_avx512_cvtss2usi:
2271 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2272 case llvm::Intrinsic::x86_avx512_cvttss2usi:
2273 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2274 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2275 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2276 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2277 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2278 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2279 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2280 case llvm::Intrinsic::x86_sse2_cvtsd2si:
2281 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2282 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2283 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2284 case llvm::Intrinsic::x86_sse2_cvtss2sd:
2285 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2286 case llvm::Intrinsic::x86_sse2_cvttsd2si:
2287 case llvm::Intrinsic::x86_sse_cvtsi2ss:
2288 case llvm::Intrinsic::x86_sse_cvtsi642ss:
2289 case llvm::Intrinsic::x86_sse_cvtss2si64:
2290 case llvm::Intrinsic::x86_sse_cvtss2si:
2291 case llvm::Intrinsic::x86_sse_cvttss2si64:
2292 case llvm::Intrinsic::x86_sse_cvttss2si:
2293 handleVectorConvertIntrinsic(I, 1);
2294 break;
2295 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2296 case llvm::Intrinsic::x86_sse2_cvtps2pd:
2297 case llvm::Intrinsic::x86_sse_cvtps2pi:
2298 case llvm::Intrinsic::x86_sse_cvttps2pi:
2299 handleVectorConvertIntrinsic(I, 2);
2300 break;
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002301 case llvm::Intrinsic::x86_avx2_psll_w:
2302 case llvm::Intrinsic::x86_avx2_psll_d:
2303 case llvm::Intrinsic::x86_avx2_psll_q:
2304 case llvm::Intrinsic::x86_avx2_pslli_w:
2305 case llvm::Intrinsic::x86_avx2_pslli_d:
2306 case llvm::Intrinsic::x86_avx2_pslli_q:
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002307 case llvm::Intrinsic::x86_avx2_psrl_w:
2308 case llvm::Intrinsic::x86_avx2_psrl_d:
2309 case llvm::Intrinsic::x86_avx2_psrl_q:
2310 case llvm::Intrinsic::x86_avx2_psra_w:
2311 case llvm::Intrinsic::x86_avx2_psra_d:
2312 case llvm::Intrinsic::x86_avx2_psrli_w:
2313 case llvm::Intrinsic::x86_avx2_psrli_d:
2314 case llvm::Intrinsic::x86_avx2_psrli_q:
2315 case llvm::Intrinsic::x86_avx2_psrai_w:
2316 case llvm::Intrinsic::x86_avx2_psrai_d:
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002317 case llvm::Intrinsic::x86_sse2_psll_w:
2318 case llvm::Intrinsic::x86_sse2_psll_d:
2319 case llvm::Intrinsic::x86_sse2_psll_q:
2320 case llvm::Intrinsic::x86_sse2_pslli_w:
2321 case llvm::Intrinsic::x86_sse2_pslli_d:
2322 case llvm::Intrinsic::x86_sse2_pslli_q:
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002323 case llvm::Intrinsic::x86_sse2_psrl_w:
2324 case llvm::Intrinsic::x86_sse2_psrl_d:
2325 case llvm::Intrinsic::x86_sse2_psrl_q:
2326 case llvm::Intrinsic::x86_sse2_psra_w:
2327 case llvm::Intrinsic::x86_sse2_psra_d:
2328 case llvm::Intrinsic::x86_sse2_psrli_w:
2329 case llvm::Intrinsic::x86_sse2_psrli_d:
2330 case llvm::Intrinsic::x86_sse2_psrli_q:
2331 case llvm::Intrinsic::x86_sse2_psrai_w:
2332 case llvm::Intrinsic::x86_sse2_psrai_d:
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002333 case llvm::Intrinsic::x86_mmx_psll_w:
2334 case llvm::Intrinsic::x86_mmx_psll_d:
2335 case llvm::Intrinsic::x86_mmx_psll_q:
2336 case llvm::Intrinsic::x86_mmx_pslli_w:
2337 case llvm::Intrinsic::x86_mmx_pslli_d:
2338 case llvm::Intrinsic::x86_mmx_pslli_q:
2339 case llvm::Intrinsic::x86_mmx_psrl_w:
2340 case llvm::Intrinsic::x86_mmx_psrl_d:
2341 case llvm::Intrinsic::x86_mmx_psrl_q:
2342 case llvm::Intrinsic::x86_mmx_psra_w:
2343 case llvm::Intrinsic::x86_mmx_psra_d:
2344 case llvm::Intrinsic::x86_mmx_psrli_w:
2345 case llvm::Intrinsic::x86_mmx_psrli_d:
2346 case llvm::Intrinsic::x86_mmx_psrli_q:
2347 case llvm::Intrinsic::x86_mmx_psrai_w:
2348 case llvm::Intrinsic::x86_mmx_psrai_d:
2349 handleVectorShiftIntrinsic(I, /* Variable */ false);
2350 break;
2351 case llvm::Intrinsic::x86_avx2_psllv_d:
2352 case llvm::Intrinsic::x86_avx2_psllv_d_256:
2353 case llvm::Intrinsic::x86_avx2_psllv_q:
2354 case llvm::Intrinsic::x86_avx2_psllv_q_256:
2355 case llvm::Intrinsic::x86_avx2_psrlv_d:
2356 case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2357 case llvm::Intrinsic::x86_avx2_psrlv_q:
2358 case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2359 case llvm::Intrinsic::x86_avx2_psrav_d:
2360 case llvm::Intrinsic::x86_avx2_psrav_d_256:
2361 handleVectorShiftIntrinsic(I, /* Variable */ true);
2362 break;
2363
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002364 case llvm::Intrinsic::x86_sse2_packsswb_128:
2365 case llvm::Intrinsic::x86_sse2_packssdw_128:
2366 case llvm::Intrinsic::x86_sse2_packuswb_128:
2367 case llvm::Intrinsic::x86_sse41_packusdw:
2368 case llvm::Intrinsic::x86_avx2_packsswb:
2369 case llvm::Intrinsic::x86_avx2_packssdw:
2370 case llvm::Intrinsic::x86_avx2_packuswb:
2371 case llvm::Intrinsic::x86_avx2_packusdw:
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002372 handleVectorPackIntrinsic(I);
2373 break;
2374
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002375 case llvm::Intrinsic::x86_mmx_packsswb:
2376 case llvm::Intrinsic::x86_mmx_packuswb:
2377 handleVectorPackIntrinsic(I, 16);
2378 break;
2379
2380 case llvm::Intrinsic::x86_mmx_packssdw:
2381 handleVectorPackIntrinsic(I, 32);
2382 break;
2383
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002384 case llvm::Intrinsic::x86_mmx_psad_bw:
2385 case llvm::Intrinsic::x86_sse2_psad_bw:
2386 case llvm::Intrinsic::x86_avx2_psad_bw:
2387 handleVectorSadIntrinsic(I);
2388 break;
2389
2390 case llvm::Intrinsic::x86_sse2_pmadd_wd:
2391 case llvm::Intrinsic::x86_avx2_pmadd_wd:
2392 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2393 case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2394 handleVectorPmaddIntrinsic(I);
2395 break;
2396
2397 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2398 handleVectorPmaddIntrinsic(I, 8);
2399 break;
2400
2401 case llvm::Intrinsic::x86_mmx_pmadd_wd:
2402 handleVectorPmaddIntrinsic(I, 16);
2403 break;
2404
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002405 default:
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002406 if (!handleUnknownIntrinsic(I))
2407 visitInstruction(I);
Evgeniy Stepanov88b8dce2012-12-17 16:30:05 +00002408 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002409 }
2410 }
2411
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002412 void visitCallSite(CallSite CS) {
2413 Instruction &I = *CS.getInstruction();
2414 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2415 if (CS.isCall()) {
Evgeniy Stepanov7ad7e832012-11-29 14:32:03 +00002416 CallInst *Call = cast<CallInst>(&I);
2417
2418 // For inline asm, do the usual thing: check argument shadow and mark all
2419 // outputs as clean. Note that any side effects of the inline asm that are
2420 // not immediately visible in its constraints are not handled.
2421 if (Call->isInlineAsm()) {
2422 visitInstruction(I);
2423 return;
2424 }
2425
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002426 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002427
2428 // We are going to insert code that relies on the fact that the callee
2429 // will become a non-readonly function after it is instrumented by us. To
2430 // prevent this code from being optimized out, mark that function
2431 // non-readonly in advance.
2432 if (Function *Func = Call->getCalledFunction()) {
2433 // Clear out readonly/readnone attributes.
2434 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002435 B.addAttribute(Attribute::ReadOnly)
2436 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00002437 Func->removeAttributes(AttributeSet::FunctionIndex,
2438 AttributeSet::get(Func->getContext(),
2439 AttributeSet::FunctionIndex,
2440 B));
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002441 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002442 }
2443 IRBuilder<> IRB(&I);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002444
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002445 unsigned ArgOffset = 0;
2446 DEBUG(dbgs() << " CallSite: " << I << "\n");
2447 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2448 ArgIt != End; ++ArgIt) {
2449 Value *A = *ArgIt;
2450 unsigned i = ArgIt - CS.arg_begin();
2451 if (!A->getType()->isSized()) {
2452 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2453 continue;
2454 }
2455 unsigned Size = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00002456 Value *Store = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002457 // Compute the Shadow for arg even if it is ByVal, because
2458 // in that case getShadow() will copy the actual arg shadow to
2459 // __msan_param_tls.
2460 Value *ArgShadow = getShadow(A);
2461 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2462 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2463 " Shadow: " << *ArgShadow << "\n");
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002464 bool ArgIsInitialized = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002465 const DataLayout &DL = F.getParent()->getDataLayout();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002466 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002467 assert(A->getType()->isPointerTy() &&
2468 "ByVal argument is not a pointer!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002469 Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00002470 if (ArgOffset + Size > kParamTLSSize) break;
Evgeniy Stepanove08633e2014-10-17 23:29:44 +00002471 unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2472 unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002473 Store = IRB.CreateMemCpy(ArgShadowBase,
2474 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2475 Size, Alignment);
2476 } else {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002477 Size = DL.getTypeAllocSize(A->getType());
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00002478 if (ArgOffset + Size > kParamTLSSize) break;
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002479 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2480 kShadowTLSAlignment);
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002481 Constant *Cst = dyn_cast<Constant>(ArgShadow);
2482 if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002483 }
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002484 if (MS.TrackOrigins && !ArgIsInitialized)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +00002485 IRB.CreateStore(getOrigin(A),
2486 getOriginPtrForArgument(A, IRB, ArgOffset));
Edwin Vane82f80d42013-01-29 17:42:24 +00002487 (void)Store;
Craig Toppere73658d2014-04-28 04:05:08 +00002488 assert(Size != 0 && Store != nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002489 DEBUG(dbgs() << " Param:" << *Store << "\n");
David Majnemerf3cadce2014-10-20 06:13:33 +00002490 ArgOffset += RoundUpToAlignment(Size, 8);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002491 }
2492 DEBUG(dbgs() << " done with call args\n");
2493
2494 FunctionType *FT =
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002495 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002496 if (FT->isVarArg()) {
2497 VAHelper->visitCallSite(CS, IRB);
2498 }
2499
2500 // Now, get the shadow for the RetVal.
2501 if (!I.getType()->isSized()) return;
Evgeniy Stepanov24ac55d2015-08-14 22:03:50 +00002502 // Don't emit the epilogue for musttail call returns.
2503 if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002504 IRBuilder<> IRBBefore(&I);
Alp Tokercb402912014-01-24 17:20:08 +00002505 // Until we have full dynamic coverage, make sure the retval shadow is 0.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002506 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002507 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
Craig Topperf40110f2014-04-25 05:29:35 +00002508 Instruction *NextInsn = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002509 if (CS.isCall()) {
2510 NextInsn = I.getNextNode();
2511 } else {
2512 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2513 if (!NormalDest->getSinglePredecessor()) {
2514 // FIXME: this case is tricky, so we are just conservative here.
2515 // Perhaps we need to split the edge between this BB and NormalDest,
2516 // but a naive attempt to use SplitEdge leads to a crash.
2517 setShadow(&I, getCleanShadow(&I));
2518 setOrigin(&I, getCleanOrigin());
2519 return;
2520 }
2521 NextInsn = NormalDest->getFirstInsertionPt();
2522 assert(NextInsn &&
2523 "Could not find insertion point for retval shadow load");
2524 }
2525 IRBuilder<> IRBAfter(NextInsn);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002526 Value *RetvalShadow =
2527 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2528 kShadowTLSAlignment, "_msret");
2529 setShadow(&I, RetvalShadow);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002530 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002531 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2532 }
2533
Evgeniy Stepanov24ac55d2015-08-14 22:03:50 +00002534 bool isAMustTailRetVal(Value *RetVal) {
2535 if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
2536 RetVal = I->getOperand(0);
2537 }
2538 if (auto *I = dyn_cast<CallInst>(RetVal)) {
2539 return I->isMustTailCall();
2540 }
2541 return false;
2542 }
2543
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002544 void visitReturnInst(ReturnInst &I) {
2545 IRBuilder<> IRB(&I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002546 Value *RetVal = I.getReturnValue();
2547 if (!RetVal) return;
Evgeniy Stepanov24ac55d2015-08-14 22:03:50 +00002548 // Don't emit the epilogue for musttail call returns.
2549 if (isAMustTailRetVal(RetVal)) return;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002550 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2551 if (CheckReturnValue) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002552 insertShadowCheck(RetVal, &I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002553 Value *Shadow = getCleanShadow(RetVal);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002554 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002555 } else {
2556 Value *Shadow = getShadow(RetVal);
2557 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2558 // FIXME: make it conditional if ClStoreCleanOrigin==0
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002559 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002560 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2561 }
2562 }
2563
2564 void visitPHINode(PHINode &I) {
2565 IRBuilder<> IRB(&I);
Evgeniy Stepanovd948a5f2014-07-07 13:28:31 +00002566 if (!PropagateShadow) {
2567 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00002568 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanovd948a5f2014-07-07 13:28:31 +00002569 return;
2570 }
2571
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002572 ShadowPHINodes.push_back(&I);
2573 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2574 "_msphi_s"));
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002575 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002576 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2577 "_msphi_o"));
2578 }
2579
2580 void visitAllocaInst(AllocaInst &I) {
2581 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00002582 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002583 IRBuilder<> IRB(I.getNextNode());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002584 const DataLayout &DL = F.getParent()->getDataLayout();
2585 uint64_t Size = DL.getTypeAllocSize(I.getAllocatedType());
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002586 if (PoisonStack && ClPoisonStackWithCall) {
David Blaikieff6409d2015-05-18 22:13:54 +00002587 IRB.CreateCall(MS.MsanPoisonStackFn,
2588 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2589 ConstantInt::get(MS.IntptrTy, Size)});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002590 } else {
2591 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002592 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2593 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002594 }
2595
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002596 if (PoisonStack && MS.TrackOrigins) {
Alp Tokere69170a2014-06-26 22:52:05 +00002597 SmallString<2048> StackDescriptionStorage;
2598 raw_svector_ostream StackDescription(StackDescriptionStorage);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002599 // We create a string with a description of the stack allocation and
2600 // pass it into __msan_set_alloca_origin.
2601 // It will be printed by the run-time if stack-originated UMR is found.
2602 // The first 4 bytes of the string are set to '----' and will be replaced
2603 // by __msan_va_arg_overflow_size_tls at the first call.
2604 StackDescription << "----" << I.getName() << "@" << F.getName();
2605 Value *Descr =
2606 createPrivateNonConstGlobalForString(*F.getParent(),
2607 StackDescription.str());
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002608
David Blaikieff6409d2015-05-18 22:13:54 +00002609 IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
2610 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002611 ConstantInt::get(MS.IntptrTy, Size),
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002612 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
David Blaikieff6409d2015-05-18 22:13:54 +00002613 IRB.CreatePointerCast(&F, MS.IntptrTy)});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002614 }
2615 }
2616
2617 void visitSelectInst(SelectInst& I) {
2618 IRBuilder<> IRB(&I);
Evgeniy Stepanov566f5912013-09-03 10:04:11 +00002619 // a = select b, c, d
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002620 Value *B = I.getCondition();
2621 Value *C = I.getTrueValue();
2622 Value *D = I.getFalseValue();
2623 Value *Sb = getShadow(B);
2624 Value *Sc = getShadow(C);
2625 Value *Sd = getShadow(D);
2626
2627 // Result shadow if condition shadow is 0.
2628 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2629 Value *Sa1;
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002630 if (I.getType()->isAggregateType()) {
2631 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2632 // an extra "select". This results in much more compact IR.
2633 // Sa = select Sb, poisoned, (select b, Sc, Sd)
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002634 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002635 } else {
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002636 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2637 // If Sb (condition is poisoned), look for bits in c and d that are equal
2638 // and both unpoisoned.
2639 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2640
2641 // Cast arguments to shadow-compatible type.
2642 C = CreateAppToShadowCast(IRB, C);
2643 D = CreateAppToShadowCast(IRB, D);
2644
2645 // Result shadow if condition shadow is 1.
2646 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002647 }
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002648 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2649 setShadow(&I, Sa);
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002650 if (MS.TrackOrigins) {
2651 // Origins are always i32, so any vector conditions must be flattened.
2652 // FIXME: consider tracking vector origins for app vectors?
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002653 if (B->getType()->isVectorTy()) {
2654 Type *FlatTy = getShadowTyNoVec(B->getType());
2655 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002656 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002657 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002658 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002659 }
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002660 // a = select b, c, d
2661 // Oa = Sb ? Ob : (b ? Oc : Od)
Evgeniy Stepanova0b68992014-11-28 11:17:58 +00002662 setOrigin(
2663 &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2664 IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2665 getOrigin(I.getFalseValue()))));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002666 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002667 }
2668
2669 void visitLandingPadInst(LandingPadInst &I) {
2670 // Do nothing.
2671 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2672 setShadow(&I, getCleanShadow(&I));
2673 setOrigin(&I, getCleanOrigin());
2674 }
2675
David Majnemer654e1302015-07-31 17:58:14 +00002676 void visitCleanupPadInst(CleanupPadInst &I) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002677 setShadow(&I, getCleanShadow(&I));
2678 setOrigin(&I, getCleanOrigin());
David Majnemer654e1302015-07-31 17:58:14 +00002679 }
2680
2681 void visitCatchPad(CatchPadInst &I) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002682 setShadow(&I, getCleanShadow(&I));
2683 setOrigin(&I, getCleanOrigin());
David Majnemer654e1302015-07-31 17:58:14 +00002684 }
2685
2686 void visitTerminatePad(TerminatePadInst &I) {
2687 DEBUG(dbgs() << "TerminatePad: " << I << "\n");
2688 // Nothing to do here.
2689 }
2690
2691 void visitCatchEndPadInst(CatchEndPadInst &I) {
2692 DEBUG(dbgs() << "CatchEndPad: " << I << "\n");
2693 // Nothing to do here.
2694 }
2695
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002696 void visitGetElementPtrInst(GetElementPtrInst &I) {
2697 handleShadowOr(I);
2698 }
2699
2700 void visitExtractValueInst(ExtractValueInst &I) {
2701 IRBuilder<> IRB(&I);
2702 Value *Agg = I.getAggregateOperand();
2703 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2704 Value *AggShadow = getShadow(Agg);
2705 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2706 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2707 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2708 setShadow(&I, ResShadow);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002709 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002710 }
2711
2712 void visitInsertValueInst(InsertValueInst &I) {
2713 IRBuilder<> IRB(&I);
2714 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2715 Value *AggShadow = getShadow(I.getAggregateOperand());
2716 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2717 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2718 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2719 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2720 DEBUG(dbgs() << " Res: " << *Res << "\n");
2721 setShadow(&I, Res);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002722 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002723 }
2724
2725 void dumpInst(Instruction &I) {
2726 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2727 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2728 } else {
2729 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2730 }
2731 errs() << "QQQ " << I << "\n";
2732 }
2733
2734 void visitResumeInst(ResumeInst &I) {
2735 DEBUG(dbgs() << "Resume: " << I << "\n");
2736 // Nothing to do here.
2737 }
2738
David Majnemer654e1302015-07-31 17:58:14 +00002739 void visitCleanupReturnInst(CleanupReturnInst &CRI) {
2740 DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
2741 // Nothing to do here.
2742 }
2743
2744 void visitCatchReturnInst(CatchReturnInst &CRI) {
2745 DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
2746 // Nothing to do here.
2747 }
2748
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002749 void visitInstruction(Instruction &I) {
2750 // Everything else: stop propagating and check for poisoned shadow.
2751 if (ClDumpStrictInstructions)
2752 dumpInst(I);
2753 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2754 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002755 insertShadowCheck(I.getOperand(i), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002756 setShadow(&I, getCleanShadow(&I));
2757 setOrigin(&I, getCleanOrigin());
2758 }
2759};
2760
2761/// \brief AMD64-specific implementation of VarArgHelper.
2762struct VarArgAMD64Helper : public VarArgHelper {
2763 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2764 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002765 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002766 static const unsigned AMD64FpEndOffset = 176;
2767
2768 Function &F;
2769 MemorySanitizer &MS;
2770 MemorySanitizerVisitor &MSV;
2771 Value *VAArgTLSCopy;
2772 Value *VAArgOverflowSize;
2773
2774 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2775
2776 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2777 MemorySanitizerVisitor &MSV)
Craig Topperf40110f2014-04-25 05:29:35 +00002778 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2779 VAArgOverflowSize(nullptr) {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002780
2781 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2782
2783 ArgKind classifyArgument(Value* arg) {
2784 // A very rough approximation of X86_64 argument classification rules.
2785 Type *T = arg->getType();
2786 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2787 return AK_FloatingPoint;
2788 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2789 return AK_GeneralPurpose;
2790 if (T->isPointerTy())
2791 return AK_GeneralPurpose;
2792 return AK_Memory;
2793 }
2794
2795 // For VarArg functions, store the argument shadow in an ABI-specific format
2796 // that corresponds to va_list layout.
2797 // We do this because Clang lowers va_arg in the frontend, and this pass
2798 // only sees the low level code that deals with va_list internals.
2799 // A much easier alternative (provided that Clang emits va_arg instructions)
2800 // would have been to associate each live instance of va_list with a copy of
2801 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2802 // order.
Craig Topper3e4c6972014-03-05 09:10:37 +00002803 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002804 unsigned GpOffset = 0;
2805 unsigned FpOffset = AMD64GpEndOffset;
2806 unsigned OverflowOffset = AMD64FpEndOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002807 const DataLayout &DL = F.getParent()->getDataLayout();
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002808 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2809 ArgIt != End; ++ArgIt) {
2810 Value *A = *ArgIt;
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002811 unsigned ArgNo = CS.getArgumentNo(ArgIt);
2812 bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2813 if (IsByVal) {
2814 // ByVal arguments always go to the overflow area.
2815 assert(A->getType()->isPointerTy());
2816 Type *RealTy = A->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002817 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002818 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
David Majnemerf3cadce2014-10-20 06:13:33 +00002819 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002820 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2821 ArgSize, kShadowTLSAlignment);
2822 } else {
2823 ArgKind AK = classifyArgument(A);
2824 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2825 AK = AK_Memory;
2826 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2827 AK = AK_Memory;
2828 Value *Base;
2829 switch (AK) {
2830 case AK_GeneralPurpose:
2831 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2832 GpOffset += 8;
2833 break;
2834 case AK_FloatingPoint:
2835 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2836 FpOffset += 16;
2837 break;
2838 case AK_Memory:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002839 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002840 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
David Majnemerf3cadce2014-10-20 06:13:33 +00002841 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002842 }
2843 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002844 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002845 }
2846 Constant *OverflowSize =
2847 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2848 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2849 }
2850
2851 /// \brief Compute the shadow address for a given va_arg.
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002852 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002853 int ArgOffset) {
2854 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2855 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002856 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002857 "_msarg");
2858 }
2859
Craig Topper3e4c6972014-03-05 09:10:37 +00002860 void visitVAStartInst(VAStartInst &I) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002861 IRBuilder<> IRB(&I);
2862 VAStartInstrumentationList.push_back(&I);
2863 Value *VAListTag = I.getArgOperand(0);
2864 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2865
2866 // Unpoison the whole __va_list_tag.
2867 // FIXME: magic ABI constants.
2868 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00002869 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002870 }
2871
Craig Topper3e4c6972014-03-05 09:10:37 +00002872 void visitVACopyInst(VACopyInst &I) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002873 IRBuilder<> IRB(&I);
2874 Value *VAListTag = I.getArgOperand(0);
2875 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2876
2877 // Unpoison the whole __va_list_tag.
2878 // FIXME: magic ABI constants.
2879 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00002880 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002881 }
2882
Craig Topper3e4c6972014-03-05 09:10:37 +00002883 void finalizeInstrumentation() override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002884 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2885 "finalizeInstrumentation called twice");
2886 if (!VAStartInstrumentationList.empty()) {
2887 // If there is a va_start in this function, make a backup copy of
2888 // va_arg_tls somewhere in the function entry block.
2889 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2890 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2891 Value *CopySize =
2892 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2893 VAArgOverflowSize);
2894 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2895 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2896 }
2897
2898 // Instrument va_start.
2899 // Copy va_list shadow from the backup copy of the TLS contents.
2900 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2901 CallInst *OrigInst = VAStartInstrumentationList[i];
2902 IRBuilder<> IRB(OrigInst->getNextNode());
2903 Value *VAListTag = OrigInst->getArgOperand(0);
2904
2905 Value *RegSaveAreaPtrPtr =
2906 IRB.CreateIntToPtr(
2907 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2908 ConstantInt::get(MS.IntptrTy, 16)),
2909 Type::getInt64PtrTy(*MS.C));
2910 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2911 Value *RegSaveAreaShadowPtr =
2912 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2913 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2914 AMD64FpEndOffset, 16);
2915
2916 Value *OverflowArgAreaPtrPtr =
2917 IRB.CreateIntToPtr(
2918 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2919 ConstantInt::get(MS.IntptrTy, 8)),
2920 Type::getInt64PtrTy(*MS.C));
2921 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2922 Value *OverflowArgAreaShadowPtr =
2923 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
David Blaikie95d3e532015-04-03 23:03:54 +00002924 Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
2925 AMD64FpEndOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002926 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2927 }
2928 }
2929};
2930
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00002931/// \brief MIPS64-specific implementation of VarArgHelper.
2932struct VarArgMIPS64Helper : public VarArgHelper {
2933 Function &F;
2934 MemorySanitizer &MS;
2935 MemorySanitizerVisitor &MSV;
2936 Value *VAArgTLSCopy;
2937 Value *VAArgSize;
2938
2939 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2940
2941 VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
2942 MemorySanitizerVisitor &MSV)
2943 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2944 VAArgSize(nullptr) {}
2945
2946 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2947 unsigned VAArgOffset = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002948 const DataLayout &DL = F.getParent()->getDataLayout();
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00002949 for (CallSite::arg_iterator ArgIt = CS.arg_begin() + 1, End = CS.arg_end();
2950 ArgIt != End; ++ArgIt) {
2951 Value *A = *ArgIt;
2952 Value *Base;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002953 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00002954#if defined(__MIPSEB__) || defined(MIPSEB)
2955 // Adjusting the shadow for argument with size < 8 to match the placement
2956 // of bits in big endian system
2957 if (ArgSize < 8)
2958 VAArgOffset += (8 - ArgSize);
2959#endif
2960 Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
2961 VAArgOffset += ArgSize;
2962 VAArgOffset = RoundUpToAlignment(VAArgOffset, 8);
2963 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2964 }
2965
2966 Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
2967 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
2968 // a new class member i.e. it is the total size of all VarArgs.
2969 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
2970 }
2971
2972 /// \brief Compute the shadow address for a given va_arg.
2973 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2974 int ArgOffset) {
2975 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2976 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2977 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2978 "_msarg");
2979 }
2980
2981 void visitVAStartInst(VAStartInst &I) override {
2982 IRBuilder<> IRB(&I);
2983 VAStartInstrumentationList.push_back(&I);
2984 Value *VAListTag = I.getArgOperand(0);
2985 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2986 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2987 /* size */8, /* alignment */8, false);
2988 }
2989
2990 void visitVACopyInst(VACopyInst &I) override {
2991 IRBuilder<> IRB(&I);
2992 Value *VAListTag = I.getArgOperand(0);
2993 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2994 // Unpoison the whole __va_list_tag.
2995 // FIXME: magic ABI constants.
2996 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2997 /* size */8, /* alignment */8, false);
2998 }
2999
3000 void finalizeInstrumentation() override {
3001 assert(!VAArgSize && !VAArgTLSCopy &&
3002 "finalizeInstrumentation called twice");
3003 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
3004 VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3005 Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
3006 VAArgSize);
3007
3008 if (!VAStartInstrumentationList.empty()) {
3009 // If there is a va_start in this function, make a backup copy of
3010 // va_arg_tls somewhere in the function entry block.
3011 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3012 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
3013 }
3014
3015 // Instrument va_start.
3016 // Copy va_list shadow from the backup copy of the TLS contents.
3017 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3018 CallInst *OrigInst = VAStartInstrumentationList[i];
3019 IRBuilder<> IRB(OrigInst->getNextNode());
3020 Value *VAListTag = OrigInst->getArgOperand(0);
3021 Value *RegSaveAreaPtrPtr =
3022 IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3023 Type::getInt64PtrTy(*MS.C));
3024 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3025 Value *RegSaveAreaShadowPtr =
3026 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
3027 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
3028 }
3029 }
3030};
3031
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003032/// \brief A no-op implementation of VarArgHelper.
3033struct VarArgNoOpHelper : public VarArgHelper {
3034 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
3035 MemorySanitizerVisitor &MSV) {}
3036
Craig Topper3e4c6972014-03-05 09:10:37 +00003037 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003038
Craig Topper3e4c6972014-03-05 09:10:37 +00003039 void visitVAStartInst(VAStartInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003040
Craig Topper3e4c6972014-03-05 09:10:37 +00003041 void visitVACopyInst(VACopyInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003042
Craig Topper3e4c6972014-03-05 09:10:37 +00003043 void finalizeInstrumentation() override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003044};
3045
3046VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003047 MemorySanitizerVisitor &Visitor) {
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003048 // VarArg handling is only implemented on AMD64. False positives are possible
3049 // on other platforms.
3050 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
3051 if (TargetTriple.getArch() == llvm::Triple::x86_64)
3052 return new VarArgAMD64Helper(Func, Msan, Visitor);
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00003053 else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
3054 TargetTriple.getArch() == llvm::Triple::mips64el)
3055 return new VarArgMIPS64Helper(Func, Msan, Visitor);
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00003056 else
3057 return new VarArgNoOpHelper(Func, Msan, Visitor);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003058}
3059
3060} // namespace
3061
3062bool MemorySanitizer::runOnFunction(Function &F) {
Ismail Pazarbasie5048e12015-05-07 21:41:52 +00003063 if (&F == MsanCtorFunction)
3064 return false;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003065 MemorySanitizerVisitor Visitor(F, *this);
3066
3067 // Clear out readonly/readnone attributes.
3068 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003069 B.addAttribute(Attribute::ReadOnly)
3070 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00003071 F.removeAttributes(AttributeSet::FunctionIndex,
3072 AttributeSet::get(F.getContext(),
3073 AttributeSet::FunctionIndex, B));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003074
3075 return Visitor.runOnFunction();
3076}