blob: 63eee2f7153af55c6514037cf9bceebd507539b2 [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
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000239// i386 FreeBSD
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000240static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000241 0x000180000000, // AndMask
242 0x000040000000, // XorMask
243 0x000020000000, // ShadowBase
244 0x000700000000, // OriginBase
245};
246
247// x86_64 FreeBSD
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000248static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000249 0xc00000000000, // AndMask
250 0x200000000000, // XorMask
251 0x100000000000, // ShadowBase
252 0x380000000000, // OriginBase
253};
254
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000255static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
256 &Linux_I386_MemoryMapParams,
257 &Linux_X86_64_MemoryMapParams,
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000258};
259
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000260static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
261 NULL,
262 &Linux_MIPS64_MemoryMapParams,
263};
264
265static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
266 &FreeBSD_I386_MemoryMapParams,
267 &FreeBSD_X86_64_MemoryMapParams,
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000268};
269
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000270/// \brief An instrumentation pass implementing detection of uninitialized
271/// reads.
272///
273/// MemorySanitizer: instrument the code in module to find
274/// uninitialized reads.
275class MemorySanitizer : public FunctionPass {
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000276 public:
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000277 MemorySanitizer(int TrackOrigins = 0)
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000278 : FunctionPass(ID),
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000279 TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
Evgeniy Stepanove402d9e2014-11-27 14:54:02 +0000280 WarningFn(nullptr) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000281 const char *getPassName() const override { return "MemorySanitizer"; }
282 bool runOnFunction(Function &F) override;
283 bool doInitialization(Module &M) override;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000284 static char ID; // Pass identification, replacement for typeid.
285
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000286 private:
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000287 void initializeCallbacks(Module &M);
288
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000289 /// \brief Track origins (allocation points) of uninitialized values.
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000290 int TrackOrigins;
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000291
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000292 LLVMContext *C;
293 Type *IntptrTy;
294 Type *OriginTy;
295 /// \brief Thread-local shadow storage for function parameters.
296 GlobalVariable *ParamTLS;
297 /// \brief Thread-local origin storage for function parameters.
298 GlobalVariable *ParamOriginTLS;
299 /// \brief Thread-local shadow storage for function return value.
300 GlobalVariable *RetvalTLS;
301 /// \brief Thread-local origin storage for function return value.
302 GlobalVariable *RetvalOriginTLS;
303 /// \brief Thread-local shadow storage for in-register va_arg function
304 /// parameters (x86_64-specific).
305 GlobalVariable *VAArgTLS;
306 /// \brief Thread-local shadow storage for va_arg overflow area
307 /// (x86_64-specific).
308 GlobalVariable *VAArgOverflowSizeTLS;
309 /// \brief Thread-local space used to pass origin value to the UMR reporting
310 /// function.
311 GlobalVariable *OriginTLS;
312
313 /// \brief The run-time callback to print a warning.
314 Value *WarningFn;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000315 // These arrays are indexed by log2(AccessSize).
316 Value *MaybeWarningFn[kNumberOfAccessSizes];
317 Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
318
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000319 /// \brief Run-time helper that generates a new origin value for a stack
320 /// allocation.
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +0000321 Value *MsanSetAllocaOrigin4Fn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000322 /// \brief Run-time helper that poisons stack on function entry.
323 Value *MsanPoisonStackFn;
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000324 /// \brief Run-time helper that records a store (or any event) of an
325 /// uninitialized value and returns an updated origin id encoding this info.
326 Value *MsanChainOriginFn;
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000327 /// \brief MSan runtime replacements for memmove, memcpy and memset.
328 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000329
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000330 /// \brief Memory map parameters used in application-to-shadow calculation.
331 const MemoryMapParams *MapParams;
332
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000333 MDNode *ColdCallWeights;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000334 /// \brief Branch weights for origin store.
335 MDNode *OriginStoreWeights;
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000336 /// \brief An empty volatile inline asm that prevents callback merge.
337 InlineAsm *EmptyAsm;
Ismail Pazarbasie5048e12015-05-07 21:41:52 +0000338 Function *MsanCtorFunction;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000339
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000340 friend struct MemorySanitizerVisitor;
341 friend struct VarArgAMD64Helper;
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +0000342 friend struct VarArgMIPS64Helper;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000343};
344} // namespace
345
346char MemorySanitizer::ID = 0;
347INITIALIZE_PASS(MemorySanitizer, "msan",
348 "MemorySanitizer: detects uninitialized reads.",
349 false, false)
350
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000351FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
352 return new MemorySanitizer(TrackOrigins);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000353}
354
355/// \brief Create a non-const global initialized with the given string.
356///
357/// Creates a writable global for Str so that we can pass it to the
358/// run-time lib. Runtime uses first 4 bytes of the string to store the
359/// frame ID, so the string needs to be mutable.
360static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
361 StringRef Str) {
362 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
363 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
364 GlobalValue::PrivateLinkage, StrConst, "");
365}
366
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000367
368/// \brief Insert extern declaration of runtime-provided functions and globals.
369void MemorySanitizer::initializeCallbacks(Module &M) {
370 // Only do this once.
371 if (WarningFn)
372 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000373
374 IRBuilder<> IRB(*C);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000375 // Create the callback.
376 // FIXME: this function should have "Cold" calling conv,
377 // which is not yet implemented.
378 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
379 : "__msan_warning_noreturn";
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000380 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000381
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000382 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
383 AccessSizeIndex++) {
384 unsigned AccessSize = 1 << AccessSizeIndex;
385 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
386 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
387 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000388 IRB.getInt32Ty(), nullptr);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000389
390 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
391 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
392 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000393 IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000394 }
395
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +0000396 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
397 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000398 IRB.getInt8PtrTy(), IntptrTy, nullptr);
David Blaikiea92765c2014-11-14 00:41:42 +0000399 MsanPoisonStackFn =
400 M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
401 IRB.getInt8PtrTy(), IntptrTy, nullptr);
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000402 MsanChainOriginFn = M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000403 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000404 MemmoveFn = M.getOrInsertFunction(
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000405 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000406 IRB.getInt8PtrTy(), IntptrTy, nullptr);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000407 MemcpyFn = M.getOrInsertFunction(
408 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000409 IntptrTy, nullptr);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000410 MemsetFn = M.getOrInsertFunction(
411 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000412 IntptrTy, nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000413
414 // Create globals.
415 RetvalTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000416 M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000417 GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000418 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000419 RetvalOriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000420 M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
421 "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000422
423 ParamTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000424 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000425 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000426 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000427 ParamOriginTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000428 M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
429 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
430 nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000431
432 VAArgTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000433 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000434 GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000435 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000436 VAArgOverflowSizeTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000437 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
438 "__msan_va_arg_overflow_size_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000439 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000440 OriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000441 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
442 "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000443
444 // We insert an empty inline asm after __msan_report* to avoid callback merge.
445 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
446 StringRef(""), StringRef(""),
447 /*hasSideEffects=*/true);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000448}
449
450/// \brief Module-level initialization.
451///
452/// inserts a call to __msan_init to the module's constructor list.
453bool MemorySanitizer::doInitialization(Module &M) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000454 auto &DL = M.getDataLayout();
Rafael Espindola93512512014-02-25 17:30:31 +0000455
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000456 Triple TargetTriple(M.getTargetTriple());
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000457 switch (TargetTriple.getOS()) {
458 case Triple::FreeBSD:
459 switch (TargetTriple.getArch()) {
460 case Triple::x86_64:
461 MapParams = FreeBSD_X86_MemoryMapParams.bits64;
462 break;
463 case Triple::x86:
464 MapParams = FreeBSD_X86_MemoryMapParams.bits32;
465 break;
466 default:
467 report_fatal_error("unsupported architecture");
468 }
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000469 break;
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000470 case Triple::Linux:
471 switch (TargetTriple.getArch()) {
472 case Triple::x86_64:
473 MapParams = Linux_X86_MemoryMapParams.bits64;
474 break;
475 case Triple::x86:
476 MapParams = Linux_X86_MemoryMapParams.bits32;
477 break;
478 case Triple::mips64:
479 case Triple::mips64el:
480 MapParams = Linux_MIPS_MemoryMapParams.bits64;
481 break;
482 default:
483 report_fatal_error("unsupported architecture");
484 }
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000485 break;
486 default:
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000487 report_fatal_error("unsupported operating system");
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000488 }
489
Mohit K. Bhakkad46ad7f72015-01-20 13:05:42 +0000490 C = &(M.getContext());
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000491 IRBuilder<> IRB(*C);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000492 IntptrTy = IRB.getIntPtrTy(DL);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000493 OriginTy = IRB.getInt32Ty();
494
495 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000496 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000497
Ismail Pazarbasie5048e12015-05-07 21:41:52 +0000498 std::tie(MsanCtorFunction, std::ignore) =
499 createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
500 /*InitArgTypes=*/{},
501 /*InitArgs=*/{});
502
503 appendToGlobalCtors(M, MsanCtorFunction, 0);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000504
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000505 if (TrackOrigins)
506 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
507 IRB.getInt32(TrackOrigins), "__msan_track_origins");
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000508
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000509 if (ClKeepGoing)
510 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
511 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
Evgeniy Stepanovdcf6bcb2013-01-22 13:26:53 +0000512
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000513 return true;
514}
515
516namespace {
517
518/// \brief A helper class that handles instrumentation of VarArg
519/// functions on a particular platform.
520///
521/// Implementations are expected to insert the instrumentation
522/// necessary to propagate argument shadow through VarArg function
523/// calls. Visit* methods are called during an InstVisitor pass over
524/// the function, and should avoid creating new basic blocks. A new
525/// instance of this class is created for each instrumented function.
526struct VarArgHelper {
527 /// \brief Visit a CallSite.
528 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
529
530 /// \brief Visit a va_start call.
531 virtual void visitVAStartInst(VAStartInst &I) = 0;
532
533 /// \brief Visit a va_copy call.
534 virtual void visitVACopyInst(VACopyInst &I) = 0;
535
536 /// \brief Finalize function instrumentation.
537 ///
538 /// This method is called after visiting all interesting (see above)
539 /// instructions in a function.
540 virtual void finalizeInstrumentation() = 0;
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000541
542 virtual ~VarArgHelper() {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000543};
544
545struct MemorySanitizerVisitor;
546
547VarArgHelper*
548CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
549 MemorySanitizerVisitor &Visitor);
550
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000551unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
552 if (TypeSize <= 8) return 0;
553 return Log2_32_Ceil(TypeSize / 8);
554}
555
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000556/// This class does all the work for a given function. Store and Load
557/// instructions store and load corresponding shadow and origin
558/// values. Most instructions propagate shadow from arguments to their
559/// return values. Certain instructions (most importantly, BranchInst)
560/// test their argument shadow and print reports (with a runtime call) if it's
561/// non-zero.
562struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
563 Function &F;
564 MemorySanitizer &MS;
565 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
566 ValueMap<Value*, Value*> ShadowMap, OriginMap;
Ahmed Charles56440fd2014-03-06 05:51:42 +0000567 std::unique_ptr<VarArgHelper> VAHelper;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000568
569 // The following flags disable parts of MSan instrumentation based on
570 // blacklist contents and command-line options.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000571 bool InsertChecks;
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000572 bool PropagateShadow;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000573 bool PoisonStack;
574 bool PoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000575 bool CheckReturnValue;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000576
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000577 struct ShadowOriginAndInsertPoint {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000578 Value *Shadow;
579 Value *Origin;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000580 Instruction *OrigIns;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000581 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000582 : Shadow(S), Origin(O), OrigIns(I) { }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000583 };
584 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000585 SmallVector<Instruction*, 16> StoreList;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000586
587 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000588 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +0000589 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000590 InsertChecks = SanitizeFunction;
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000591 PropagateShadow = SanitizeFunction;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000592 PoisonStack = SanitizeFunction && ClPoisonStack;
593 PoisonUndef = SanitizeFunction && ClPoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000594 // FIXME: Consider using SpecialCaseList to specify a list of functions that
595 // must always return fully initialized values. For now, we hardcode "main".
596 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000597
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000598 DEBUG(if (!InsertChecks)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000599 dbgs() << "MemorySanitizer is not inserting checks into '"
600 << F.getName() << "'\n");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000601 }
602
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000603 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
604 if (MS.TrackOrigins <= 1) return V;
605 return IRB.CreateCall(MS.MsanChainOriginFn, V);
606 }
607
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000608 Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000609 const DataLayout &DL = F.getParent()->getDataLayout();
610 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000611 if (IntptrSize == kOriginSize) return Origin;
612 assert(IntptrSize == kOriginSize * 2);
613 Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
614 return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
615 }
616
617 /// \brief Fill memory range with the given origin value.
618 void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
619 unsigned Size, unsigned Alignment) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000620 const DataLayout &DL = F.getParent()->getDataLayout();
621 unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
622 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000623 assert(IntptrAlignment >= kMinOriginAlignment);
624 assert(IntptrSize >= kOriginSize);
625
626 unsigned Ofs = 0;
627 unsigned CurrentAlignment = Alignment;
628 if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
629 Value *IntptrOrigin = originToIntptr(IRB, Origin);
630 Value *IntptrOriginPtr =
631 IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
632 for (unsigned i = 0; i < Size / IntptrSize; ++i) {
David Blaikie95d3e532015-04-03 23:03:54 +0000633 Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
634 : IntptrOriginPtr;
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000635 IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
636 Ofs += IntptrSize / kOriginSize;
637 CurrentAlignment = IntptrAlignment;
638 }
639 }
640
641 for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
David Blaikie95d3e532015-04-03 23:03:54 +0000642 Value *GEP =
643 i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000644 IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
645 CurrentAlignment = kMinOriginAlignment;
646 }
647 }
648
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000649 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
650 unsigned Alignment, bool AsCall) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000651 const DataLayout &DL = F.getParent()->getDataLayout();
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000652 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000653 unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000654 if (isa<StructType>(Shadow->getType())) {
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000655 paintOrigin(IRB, updateOrigin(Origin, IRB),
656 getOriginPtr(Addr, IRB, Alignment), StoreSize,
657 OriginAlignment);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000658 } else {
659 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000660 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
661 if (ConstantShadow) {
662 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000663 paintOrigin(IRB, updateOrigin(Origin, IRB),
664 getOriginPtr(Addr, IRB, Alignment), StoreSize,
665 OriginAlignment);
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000666 return;
667 }
668
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000669 unsigned TypeSizeInBits =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000670 DL.getTypeSizeInBits(ConvertedShadow->getType());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000671 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
672 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
673 Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
674 Value *ConvertedShadow2 = IRB.CreateZExt(
675 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
David Blaikieff6409d2015-05-18 22:13:54 +0000676 IRB.CreateCall(Fn, {ConvertedShadow2,
677 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
678 Origin});
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000679 } else {
680 Value *Cmp = IRB.CreateICmpNE(
681 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
682 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
683 Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
684 IRBuilder<> IRBNew(CheckTerm);
Evgeniy Stepanov79ca0fd2015-01-21 13:21:31 +0000685 paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
686 getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
687 OriginAlignment);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000688 }
689 }
690 }
691
692 void materializeStores(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000693 for (auto Inst : StoreList) {
694 StoreInst &SI = *dyn_cast<StoreInst>(Inst);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000695
Alexey Samsonova02e6642014-05-29 18:40:48 +0000696 IRBuilder<> IRB(&SI);
697 Value *Val = SI.getValueOperand();
698 Value *Addr = SI.getPointerOperand();
699 Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000700 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
701
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000702 StoreInst *NewSI =
Alexey Samsonova02e6642014-05-29 18:40:48 +0000703 IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000704 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
NAKAMURA Takumie0b1b462012-12-06 13:38:00 +0000705 (void)NewSI;
Evgeniy Stepanovc4415592013-01-22 12:30:52 +0000706
Alexey Samsonova02e6642014-05-29 18:40:48 +0000707 if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000708
Alexey Samsonova02e6642014-05-29 18:40:48 +0000709 if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +0000710
Evgeniy Stepanov4e120572015-02-06 21:47:39 +0000711 if (MS.TrackOrigins && !SI.isAtomic())
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000712 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI.getAlignment(),
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000713 InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000714 }
715 }
716
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000717 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
718 bool AsCall) {
719 IRBuilder<> IRB(OrigIns);
720 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
721 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
722 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000723
724 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
725 if (ConstantShadow) {
726 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
727 if (MS.TrackOrigins) {
728 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
729 MS.OriginTLS);
730 }
David Blaikieff6409d2015-05-18 22:13:54 +0000731 IRB.CreateCall(MS.WarningFn, {});
732 IRB.CreateCall(MS.EmptyAsm, {});
Evgeniy Stepanovc5b974e2015-01-20 15:21:35 +0000733 // FIXME: Insert UnreachableInst if !ClKeepGoing?
734 // This may invalidate some of the following checks and needs to be done
735 // at the very end.
736 }
737 return;
738 }
739
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000740 const DataLayout &DL = OrigIns->getModule()->getDataLayout();
741
742 unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000743 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
744 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
745 Value *Fn = MS.MaybeWarningFn[SizeIndex];
746 Value *ConvertedShadow2 =
747 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
David Blaikieff6409d2015-05-18 22:13:54 +0000748 IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000749 ? Origin
David Blaikieff6409d2015-05-18 22:13:54 +0000750 : (Value *)IRB.getInt32(0)});
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000751 } else {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000752 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
753 getCleanShadow(ConvertedShadow), "_mscmp");
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000754 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
755 Cmp, OrigIns,
756 /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000757
758 IRB.SetInsertPoint(CheckTerm);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000759 if (MS.TrackOrigins) {
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000760 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000761 MS.OriginTLS);
762 }
David Blaikieff6409d2015-05-18 22:13:54 +0000763 IRB.CreateCall(MS.WarningFn, {});
764 IRB.CreateCall(MS.EmptyAsm, {});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000765 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
766 }
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000767 }
768
769 void materializeChecks(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000770 for (const auto &ShadowData : InstrumentationList) {
771 Instruction *OrigIns = ShadowData.OrigIns;
772 Value *Shadow = ShadowData.Shadow;
773 Value *Origin = ShadowData.Origin;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000774 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
775 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000776 DEBUG(dbgs() << "DONE:\n" << F);
777 }
778
779 /// \brief Add MemorySanitizer instrumentation to a function.
780 bool runOnFunction() {
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000781 MS.initializeCallbacks(*F.getParent());
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +0000782
783 // In the presence of unreachable blocks, we may see Phi nodes with
784 // incoming nodes from such blocks. Since InstVisitor skips unreachable
785 // blocks, such nodes will not have any shadow value associated with them.
786 // It's easier to remove unreachable blocks than deal with missing shadow.
787 removeUnreachableBlocks(F);
788
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000789 // Iterate all BBs in depth-first order and create shadow instructions
790 // for all instructions (where applicable).
791 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
David Blaikieceec2bd2014-04-11 01:50:01 +0000792 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000793 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000794
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000795
796 // Finalize PHI nodes.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000797 for (PHINode *PN : ShadowPHINodes) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000798 PHINode *PNS = cast<PHINode>(getShadow(PN));
Craig Topperf40110f2014-04-25 05:29:35 +0000799 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000800 size_t NumValues = PN->getNumIncomingValues();
801 for (size_t v = 0; v < NumValues; v++) {
802 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000803 if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000804 }
805 }
806
807 VAHelper->finalizeInstrumentation();
808
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000809 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
810 InstrumentationList.size() + StoreList.size() >
811 (unsigned)ClInstrumentationWithCallThreshold;
812
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000813 // Delayed instrumentation of StoreInst.
Evgeniy Stepanov47ac9ba2012-12-06 11:58:59 +0000814 // This may add new checks to be inserted later.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000815 materializeStores(InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000816
817 // Insert shadow value checks.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000818 materializeChecks(InstrumentWithCalls);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000819
820 return true;
821 }
822
823 /// \brief Compute the shadow type that corresponds to a given Value.
824 Type *getShadowTy(Value *V) {
825 return getShadowTy(V->getType());
826 }
827
828 /// \brief Compute the shadow type that corresponds to a given Type.
829 Type *getShadowTy(Type *OrigTy) {
830 if (!OrigTy->isSized()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000831 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000832 }
833 // For integer type, shadow is the same as the original type.
834 // This may return weird-sized types like i1.
835 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
836 return IT;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000837 const DataLayout &DL = F.getParent()->getDataLayout();
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000838 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000839 uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000840 return VectorType::get(IntegerType::get(*MS.C, EltSize),
841 VT->getNumElements());
842 }
Evgeniy Stepanov5997feb2014-07-31 11:02:27 +0000843 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
844 return ArrayType::get(getShadowTy(AT->getElementType()),
845 AT->getNumElements());
846 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000847 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
848 SmallVector<Type*, 4> Elements;
849 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
850 Elements.push_back(getShadowTy(ST->getElementType(i)));
851 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
852 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
853 return Res;
854 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000855 uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000856 return IntegerType::get(*MS.C, TypeSize);
857 }
858
859 /// \brief Flatten a vector type.
860 Type *getShadowTyNoVec(Type *ty) {
861 if (VectorType *vt = dyn_cast<VectorType>(ty))
862 return IntegerType::get(*MS.C, vt->getBitWidth());
863 return ty;
864 }
865
866 /// \brief Convert a shadow value to it's flattened variant.
867 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
868 Type *Ty = V->getType();
869 Type *NoVecTy = getShadowTyNoVec(Ty);
870 if (Ty == NoVecTy) return V;
871 return IRB.CreateBitCast(V, NoVecTy);
872 }
873
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000874 /// \brief Compute the integer shadow offset that corresponds to a given
875 /// application address.
876 ///
877 /// Offset = (Addr & ~AndMask) ^ XorMask
878 Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
879 uint64_t AndMask = MS.MapParams->AndMask;
880 assert(AndMask != 0 && "AndMask shall be specified");
881 Value *OffsetLong =
882 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
883 ConstantInt::get(MS.IntptrTy, ~AndMask));
884
885 uint64_t XorMask = MS.MapParams->XorMask;
886 if (XorMask != 0)
887 OffsetLong = IRB.CreateXor(OffsetLong,
888 ConstantInt::get(MS.IntptrTy, XorMask));
889 return OffsetLong;
890 }
891
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000892 /// \brief Compute the shadow address that corresponds to a given application
893 /// address.
894 ///
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000895 /// Shadow = ShadowBase + Offset
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000896 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
897 IRBuilder<> &IRB) {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000898 Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
899 uint64_t ShadowBase = MS.MapParams->ShadowBase;
900 if (ShadowBase != 0)
901 ShadowLong =
902 IRB.CreateAdd(ShadowLong,
903 ConstantInt::get(MS.IntptrTy, ShadowBase));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000904 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
905 }
906
907 /// \brief Compute the origin address that corresponds to a given application
908 /// address.
909 ///
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000910 /// OriginAddr = (OriginBase + Offset) & ~3ULL
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000911 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000912 Value *OriginLong = getShadowPtrOffset(Addr, IRB);
913 uint64_t OriginBase = MS.MapParams->OriginBase;
914 if (OriginBase != 0)
915 OriginLong =
916 IRB.CreateAdd(OriginLong,
917 ConstantInt::get(MS.IntptrTy, OriginBase));
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000918 if (Alignment < kMinOriginAlignment) {
919 uint64_t Mask = kMinOriginAlignment - 1;
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000920 OriginLong = IRB.CreateAnd(OriginLong,
921 ConstantInt::get(MS.IntptrTy, ~Mask));
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +0000922 }
Viktor Kutuzovb4ffb5d2014-12-18 12:12:59 +0000923 return IRB.CreateIntToPtr(OriginLong,
924 PointerType::get(IRB.getInt32Ty(), 0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000925 }
926
927 /// \brief Compute the shadow address for a given function argument.
928 ///
929 /// Shadow = ParamTLS+ArgOffset.
930 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
931 int ArgOffset) {
932 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
933 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
934 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
935 "_msarg");
936 }
937
938 /// \brief Compute the origin address for a given function argument.
939 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
940 int ArgOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +0000941 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000942 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
943 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
944 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
945 "_msarg_o");
946 }
947
948 /// \brief Compute the shadow address for a retval.
949 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
950 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
951 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
952 "_msret");
953 }
954
955 /// \brief Compute the origin address for a retval.
956 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
957 // We keep a single origin for the entire retval. Might be too optimistic.
958 return MS.RetvalOriginTLS;
959 }
960
961 /// \brief Set SV to be the shadow value for V.
962 void setShadow(Value *V, Value *SV) {
963 assert(!ShadowMap.count(V) && "Values may only have one shadow");
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000964 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000965 }
966
967 /// \brief Set Origin to be the origin value for V.
968 void setOrigin(Value *V, Value *Origin) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000969 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000970 assert(!OriginMap.count(V) && "Values may only have one origin");
971 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
972 OriginMap[V] = Origin;
973 }
974
975 /// \brief Create a clean shadow value for a given value.
976 ///
977 /// Clean shadow (all zeroes) means all bits of the value are defined
978 /// (initialized).
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000979 Constant *getCleanShadow(Value *V) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000980 Type *ShadowTy = getShadowTy(V);
981 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000982 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000983 return Constant::getNullValue(ShadowTy);
984 }
985
986 /// \brief Create a dirty shadow of a given shadow type.
987 Constant *getPoisonedShadow(Type *ShadowTy) {
988 assert(ShadowTy);
989 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
990 return Constant::getAllOnesValue(ShadowTy);
Evgeniy Stepanov5997feb2014-07-31 11:02:27 +0000991 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
992 SmallVector<Constant *, 4> Vals(AT->getNumElements(),
993 getPoisonedShadow(AT->getElementType()));
994 return ConstantArray::get(AT, Vals);
995 }
996 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
997 SmallVector<Constant *, 4> Vals;
998 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
999 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1000 return ConstantStruct::get(ST, Vals);
1001 }
1002 llvm_unreachable("Unexpected shadow type");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001003 }
1004
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +00001005 /// \brief Create a dirty shadow for a given value.
1006 Constant *getPoisonedShadow(Value *V) {
1007 Type *ShadowTy = getShadowTy(V);
1008 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +00001009 return nullptr;
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +00001010 return getPoisonedShadow(ShadowTy);
1011 }
1012
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001013 /// \brief Create a clean (zero) origin.
1014 Value *getCleanOrigin() {
1015 return Constant::getNullValue(MS.OriginTy);
1016 }
1017
1018 /// \brief Get the shadow value for a given Value.
1019 ///
1020 /// This function either returns the value set earlier with setShadow,
1021 /// or extracts if from ParamTLS (for function arguments).
1022 Value *getShadow(Value *V) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001023 if (!PropagateShadow) return getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001024 if (Instruction *I = dyn_cast<Instruction>(V)) {
1025 // For instructions the shadow is already stored in the map.
1026 Value *Shadow = ShadowMap[V];
1027 if (!Shadow) {
1028 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001029 (void)I;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001030 assert(Shadow && "No shadow for a value");
1031 }
1032 return Shadow;
1033 }
1034 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00001035 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001036 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001037 (void)U;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001038 return AllOnes;
1039 }
1040 if (Argument *A = dyn_cast<Argument>(V)) {
1041 // For arguments we compute the shadow on demand and store it in the map.
1042 Value **ShadowPtr = &ShadowMap[V];
1043 if (*ShadowPtr)
1044 return *ShadowPtr;
1045 Function *F = A->getParent();
1046 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
1047 unsigned ArgOffset = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001048 const DataLayout &DL = F->getParent()->getDataLayout();
Alexey Samsonova02e6642014-05-29 18:40:48 +00001049 for (auto &FArg : F->args()) {
1050 if (!FArg.getType()->isSized()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001051 DEBUG(dbgs() << "Arg is not sized\n");
1052 continue;
1053 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001054 unsigned Size =
1055 FArg.hasByValAttr()
1056 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
1057 : DL.getTypeAllocSize(FArg.getType());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001058 if (A == &FArg) {
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001059 bool Overflow = ArgOffset + Size > kParamTLSSize;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001060 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1061 if (FArg.hasByValAttr()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001062 // ByVal pointer itself has clean shadow. We copy the actual
1063 // argument shadow to the underlying memory.
Evgeniy Stepanovfca01232013-05-28 13:07:43 +00001064 // Figure out maximal valid memcpy alignment.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001065 unsigned ArgAlign = FArg.getParamAlignment();
Evgeniy Stepanovfca01232013-05-28 13:07:43 +00001066 if (ArgAlign == 0) {
1067 Type *EltType = A->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001068 ArgAlign = DL.getABITypeAlignment(EltType);
Evgeniy Stepanovfca01232013-05-28 13:07:43 +00001069 }
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001070 if (Overflow) {
1071 // ParamTLS overflow.
1072 EntryIRB.CreateMemSet(
1073 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
1074 Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
1075 } else {
1076 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1077 Value *Cpy = EntryIRB.CreateMemCpy(
1078 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
1079 CopyAlign);
1080 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
1081 (void)Cpy;
1082 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001083 *ShadowPtr = getCleanShadow(V);
1084 } else {
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001085 if (Overflow) {
1086 // ParamTLS overflow.
1087 *ShadowPtr = getCleanShadow(V);
1088 } else {
1089 *ShadowPtr =
1090 EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1091 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001092 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001093 DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001094 **ShadowPtr << "\n");
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001095 if (MS.TrackOrigins && !Overflow) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001096 Value *OriginPtr =
1097 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001098 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00001099 } else {
1100 setOrigin(A, getCleanOrigin());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001101 }
1102 }
David Majnemerf3cadce2014-10-20 06:13:33 +00001103 ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001104 }
1105 assert(*ShadowPtr && "Could not find shadow for an argument");
1106 return *ShadowPtr;
1107 }
1108 // For everything else the shadow is zero.
1109 return getCleanShadow(V);
1110 }
1111
1112 /// \brief Get the shadow for i-th argument of the instruction I.
1113 Value *getShadow(Instruction *I, int i) {
1114 return getShadow(I->getOperand(i));
1115 }
1116
1117 /// \brief Get the origin for a value.
1118 Value *getOrigin(Value *V) {
Craig Topperf40110f2014-04-25 05:29:35 +00001119 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00001120 if (!PropagateShadow) return getCleanOrigin();
1121 if (isa<Constant>(V)) return getCleanOrigin();
1122 assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1123 "Unexpected value type in getOrigin()");
1124 Value *Origin = OriginMap[V];
1125 assert(Origin && "Missing origin");
1126 return Origin;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001127 }
1128
1129 /// \brief Get the origin for i-th argument of the instruction I.
1130 Value *getOrigin(Instruction *I, int i) {
1131 return getOrigin(I->getOperand(i));
1132 }
1133
1134 /// \brief Remember the place where a shadow check should be inserted.
1135 ///
1136 /// This location will be later instrumented with a check that will print a
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001137 /// UMR warning in runtime if the shadow value is not 0.
1138 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1139 assert(Shadow);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001140 if (!InsertChecks) return;
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001141#ifndef NDEBUG
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001142 Type *ShadowTy = Shadow->getType();
1143 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1144 "Can only insert checks for integer and vector shadow types");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001145#endif
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001146 InstrumentationList.push_back(
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001147 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1148 }
1149
1150 /// \brief Remember the place where a shadow check should be inserted.
1151 ///
1152 /// This location will be later instrumented with a check that will print a
1153 /// UMR warning in runtime if the value is not fully defined.
1154 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1155 assert(Val);
Evgeniy Stepanovd337a592014-10-24 23:34:15 +00001156 Value *Shadow, *Origin;
1157 if (ClCheckConstantShadow) {
1158 Shadow = getShadow(Val);
1159 if (!Shadow) return;
1160 Origin = getOrigin(Val);
1161 } else {
1162 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1163 if (!Shadow) return;
1164 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1165 }
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001166 insertShadowCheck(Shadow, Origin, OrigIns);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001167 }
1168
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001169 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1170 switch (a) {
1171 case NotAtomic:
1172 return NotAtomic;
1173 case Unordered:
1174 case Monotonic:
1175 case Release:
1176 return Release;
1177 case Acquire:
1178 case AcquireRelease:
1179 return AcquireRelease;
1180 case SequentiallyConsistent:
1181 return SequentiallyConsistent;
1182 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001183 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001184 }
1185
1186 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1187 switch (a) {
1188 case NotAtomic:
1189 return NotAtomic;
1190 case Unordered:
1191 case Monotonic:
1192 case Acquire:
1193 return Acquire;
1194 case Release:
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
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001203 // ------------------- Visitors.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001204
1205 /// \brief Instrument LoadInst
1206 ///
1207 /// Loads the corresponding shadow and (optionally) origin.
1208 /// Optionally, checks that the load address is fully defined.
1209 void visitLoadInst(LoadInst &I) {
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001210 assert(I.getType()->isSized() && "Load type must have size");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001211 IRBuilder<> IRB(I.getNextNode());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001212 Type *ShadowTy = getShadowTy(&I);
1213 Value *Addr = I.getPointerOperand();
Kostya Serebryany543f3db2014-12-03 23:28:26 +00001214 if (PropagateShadow && !I.getMetadata("nosanitize")) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001215 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1216 setShadow(&I,
1217 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1218 } else {
1219 setShadow(&I, getCleanShadow(&I));
1220 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001221
1222 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001223 insertShadowCheck(I.getPointerOperand(), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001224
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001225 if (I.isAtomic())
1226 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1227
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001228 if (MS.TrackOrigins) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001229 if (PropagateShadow) {
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00001230 unsigned Alignment = I.getAlignment();
1231 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1232 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
1233 OriginAlignment));
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001234 } else {
1235 setOrigin(&I, getCleanOrigin());
1236 }
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001237 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001238 }
1239
1240 /// \brief Instrument StoreInst
1241 ///
1242 /// Stores the corresponding shadow and (optionally) origin.
1243 /// Optionally, checks that the store address is fully defined.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001244 void visitStoreInst(StoreInst &I) {
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +00001245 StoreList.push_back(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001246 }
1247
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001248 void handleCASOrRMW(Instruction &I) {
1249 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1250
1251 IRBuilder<> IRB(&I);
1252 Value *Addr = I.getOperand(0);
1253 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1254
1255 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001256 insertShadowCheck(Addr, &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001257
1258 // Only test the conditional argument of cmpxchg instruction.
1259 // The other argument can potentially be uninitialized, but we can not
1260 // detect this situation reliably without possible false positives.
1261 if (isa<AtomicCmpXchgInst>(I))
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001262 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001263
1264 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1265
1266 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00001267 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001268 }
1269
1270 void visitAtomicRMWInst(AtomicRMWInst &I) {
1271 handleCASOrRMW(I);
1272 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1273 }
1274
1275 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1276 handleCASOrRMW(I);
Tim Northovere94a5182014-03-11 10:48:52 +00001277 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001278 }
1279
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001280 // Vector manipulation.
1281 void visitExtractElementInst(ExtractElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001282 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001283 IRBuilder<> IRB(&I);
1284 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1285 "_msprop"));
1286 setOrigin(&I, getOrigin(&I, 0));
1287 }
1288
1289 void visitInsertElementInst(InsertElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001290 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001291 IRBuilder<> IRB(&I);
1292 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1293 I.getOperand(2), "_msprop"));
1294 setOriginForNaryOp(I);
1295 }
1296
1297 void visitShuffleVectorInst(ShuffleVectorInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001298 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001299 IRBuilder<> IRB(&I);
1300 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1301 I.getOperand(2), "_msprop"));
1302 setOriginForNaryOp(I);
1303 }
1304
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001305 // Casts.
1306 void visitSExtInst(SExtInst &I) {
1307 IRBuilder<> IRB(&I);
1308 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1309 setOrigin(&I, getOrigin(&I, 0));
1310 }
1311
1312 void visitZExtInst(ZExtInst &I) {
1313 IRBuilder<> IRB(&I);
1314 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1315 setOrigin(&I, getOrigin(&I, 0));
1316 }
1317
1318 void visitTruncInst(TruncInst &I) {
1319 IRBuilder<> IRB(&I);
1320 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1321 setOrigin(&I, getOrigin(&I, 0));
1322 }
1323
1324 void visitBitCastInst(BitCastInst &I) {
1325 IRBuilder<> IRB(&I);
1326 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1327 setOrigin(&I, getOrigin(&I, 0));
1328 }
1329
1330 void visitPtrToIntInst(PtrToIntInst &I) {
1331 IRBuilder<> IRB(&I);
1332 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1333 "_msprop_ptrtoint"));
1334 setOrigin(&I, getOrigin(&I, 0));
1335 }
1336
1337 void visitIntToPtrInst(IntToPtrInst &I) {
1338 IRBuilder<> IRB(&I);
1339 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1340 "_msprop_inttoptr"));
1341 setOrigin(&I, getOrigin(&I, 0));
1342 }
1343
1344 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1345 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1346 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1347 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1348 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1349 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1350
1351 /// \brief Propagate shadow for bitwise AND.
1352 ///
1353 /// This code is exact, i.e. if, for example, a bit in the left argument
1354 /// is defined and 0, then neither the value not definedness of the
1355 /// corresponding bit in B don't affect the resulting shadow.
1356 void visitAnd(BinaryOperator &I) {
1357 IRBuilder<> IRB(&I);
1358 // "And" of 0 and a poisoned value results in unpoisoned value.
1359 // 1&1 => 1; 0&1 => 0; p&1 => p;
1360 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1361 // 1&p => p; 0&p => 0; p&p => p;
1362 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1363 Value *S1 = getShadow(&I, 0);
1364 Value *S2 = getShadow(&I, 1);
1365 Value *V1 = I.getOperand(0);
1366 Value *V2 = I.getOperand(1);
1367 if (V1->getType() != S1->getType()) {
1368 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1369 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1370 }
1371 Value *S1S2 = IRB.CreateAnd(S1, S2);
1372 Value *V1S2 = IRB.CreateAnd(V1, S2);
1373 Value *S1V2 = IRB.CreateAnd(S1, V2);
1374 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1375 setOriginForNaryOp(I);
1376 }
1377
1378 void visitOr(BinaryOperator &I) {
1379 IRBuilder<> IRB(&I);
1380 // "Or" of 1 and a poisoned value results in unpoisoned value.
1381 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1382 // 1|0 => 1; 0|0 => 0; p|0 => p;
1383 // 1|p => 1; 0|p => p; p|p => p;
1384 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1385 Value *S1 = getShadow(&I, 0);
1386 Value *S2 = getShadow(&I, 1);
1387 Value *V1 = IRB.CreateNot(I.getOperand(0));
1388 Value *V2 = IRB.CreateNot(I.getOperand(1));
1389 if (V1->getType() != S1->getType()) {
1390 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1391 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1392 }
1393 Value *S1S2 = IRB.CreateAnd(S1, S2);
1394 Value *V1S2 = IRB.CreateAnd(V1, S2);
1395 Value *S1V2 = IRB.CreateAnd(S1, V2);
1396 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1397 setOriginForNaryOp(I);
1398 }
1399
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001400 /// \brief Default propagation of shadow and/or origin.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001401 ///
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001402 /// This class implements the general case of shadow propagation, used in all
1403 /// cases where we don't know and/or don't care about what the operation
1404 /// actually does. It converts all input shadow values to a common type
1405 /// (extending or truncating as necessary), and bitwise OR's them.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001406 ///
1407 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1408 /// fully initialized), and less prone to false positives.
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001409 ///
1410 /// This class also implements the general case of origin propagation. For a
1411 /// Nary operation, result origin is set to the origin of an argument that is
1412 /// not entirely initialized. If there is more than one such arguments, the
1413 /// rightmost of them is picked. It does not matter which one is picked if all
1414 /// arguments are initialized.
1415 template <bool CombineShadow>
1416 class Combiner {
1417 Value *Shadow;
1418 Value *Origin;
1419 IRBuilder<> &IRB;
1420 MemorySanitizerVisitor *MSV;
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001421
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001422 public:
1423 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
Craig Topperf40110f2014-04-25 05:29:35 +00001424 Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001425
1426 /// \brief Add a pair of shadow and origin values to the mix.
1427 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1428 if (CombineShadow) {
1429 assert(OpShadow);
1430 if (!Shadow)
1431 Shadow = OpShadow;
1432 else {
1433 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1434 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1435 }
1436 }
1437
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001438 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001439 assert(OpOrigin);
1440 if (!Origin) {
1441 Origin = OpOrigin;
1442 } else {
Evgeniy Stepanov70d1b0a2014-06-09 14:29:34 +00001443 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1444 // No point in adding something that might result in 0 origin value.
1445 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1446 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1447 Value *Cond =
1448 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1449 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1450 }
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001451 }
1452 }
1453 return *this;
1454 }
1455
1456 /// \brief Add an application value to the mix.
1457 Combiner &Add(Value *V) {
1458 Value *OpShadow = MSV->getShadow(V);
Craig Topperf40110f2014-04-25 05:29:35 +00001459 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001460 return Add(OpShadow, OpOrigin);
1461 }
1462
1463 /// \brief Set the current combined values as the given instruction's shadow
1464 /// and origin.
1465 void Done(Instruction *I) {
1466 if (CombineShadow) {
1467 assert(Shadow);
1468 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1469 MSV->setShadow(I, Shadow);
1470 }
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001471 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001472 assert(Origin);
1473 MSV->setOrigin(I, Origin);
1474 }
1475 }
1476 };
1477
1478 typedef Combiner<true> ShadowAndOriginCombiner;
1479 typedef Combiner<false> OriginCombiner;
1480
1481 /// \brief Propagate origin for arbitrary operation.
1482 void setOriginForNaryOp(Instruction &I) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001483 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001484 IRBuilder<> IRB(&I);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001485 OriginCombiner OC(this, IRB);
1486 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1487 OC.Add(OI->get());
1488 OC.Done(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001489 }
1490
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001491 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +00001492 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1493 "Vector of pointers is not a valid shadow type");
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001494 return Ty->isVectorTy() ?
1495 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1496 Ty->getPrimitiveSizeInBits();
1497 }
1498
1499 /// \brief Cast between two shadow types, extending or truncating as
1500 /// necessary.
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001501 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1502 bool Signed = false) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001503 Type *srcTy = V->getType();
1504 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001505 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001506 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1507 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001508 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001509 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1510 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1511 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1512 Value *V2 =
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001513 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001514 return IRB.CreateBitCast(V2, dstTy);
1515 // TODO: handle struct types.
1516 }
1517
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00001518 /// \brief Cast an application value to the type of its own shadow.
1519 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1520 Type *ShadowTy = getShadowTy(V);
1521 if (V->getType() == ShadowTy)
1522 return V;
1523 if (V->getType()->isPtrOrPtrVectorTy())
1524 return IRB.CreatePtrToInt(V, ShadowTy);
1525 else
1526 return IRB.CreateBitCast(V, ShadowTy);
1527 }
1528
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001529 /// \brief Propagate shadow for arbitrary operation.
1530 void handleShadowOr(Instruction &I) {
1531 IRBuilder<> IRB(&I);
1532 ShadowAndOriginCombiner SC(this, IRB);
1533 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1534 SC.Add(OI->get());
1535 SC.Done(&I);
1536 }
1537
Evgeniy Stepanovdf187fe2014-06-17 09:23:12 +00001538 // \brief Handle multiplication by constant.
1539 //
1540 // Handle a special case of multiplication by constant that may have one or
1541 // more zeros in the lower bits. This makes corresponding number of lower bits
1542 // of the result zero as well. We model it by shifting the other operand
1543 // shadow left by the required number of bits. Effectively, we transform
1544 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1545 // We use multiplication by 2**N instead of shift to cover the case of
1546 // multiplication by 0, which may occur in some elements of a vector operand.
1547 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1548 Value *OtherArg) {
1549 Constant *ShadowMul;
1550 Type *Ty = ConstArg->getType();
1551 if (Ty->isVectorTy()) {
1552 unsigned NumElements = Ty->getVectorNumElements();
1553 Type *EltTy = Ty->getSequentialElementType();
1554 SmallVector<Constant *, 16> Elements;
1555 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1556 ConstantInt *Elt =
1557 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1558 APInt V = Elt->getValue();
1559 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1560 Elements.push_back(ConstantInt::get(EltTy, V2));
1561 }
1562 ShadowMul = ConstantVector::get(Elements);
1563 } else {
1564 ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1565 APInt V = Elt->getValue();
1566 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1567 ShadowMul = ConstantInt::get(Elt->getType(), V2);
1568 }
1569
1570 IRBuilder<> IRB(&I);
1571 setShadow(&I,
1572 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1573 setOrigin(&I, getOrigin(OtherArg));
1574 }
1575
1576 void visitMul(BinaryOperator &I) {
1577 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1578 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1579 if (constOp0 && !constOp1)
1580 handleMulByConstant(I, constOp0, I.getOperand(1));
1581 else if (constOp1 && !constOp0)
1582 handleMulByConstant(I, constOp1, I.getOperand(0));
1583 else
1584 handleShadowOr(I);
1585 }
1586
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001587 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1588 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1589 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1590 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1591 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1592 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001593
1594 void handleDiv(Instruction &I) {
1595 IRBuilder<> IRB(&I);
1596 // Strict on the second argument.
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001597 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001598 setShadow(&I, getShadow(&I, 0));
1599 setOrigin(&I, getOrigin(&I, 0));
1600 }
1601
1602 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1603 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1604 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1605 void visitURem(BinaryOperator &I) { handleDiv(I); }
1606 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1607 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1608
1609 /// \brief Instrument == and != comparisons.
1610 ///
1611 /// Sometimes the comparison result is known even if some of the bits of the
1612 /// arguments are not.
1613 void handleEqualityComparison(ICmpInst &I) {
1614 IRBuilder<> IRB(&I);
1615 Value *A = I.getOperand(0);
1616 Value *B = I.getOperand(1);
1617 Value *Sa = getShadow(A);
1618 Value *Sb = getShadow(B);
Evgeniy Stepanovd14e47b2013-01-15 16:44:52 +00001619
1620 // Get rid of pointers and vectors of pointers.
1621 // For ints (and vectors of ints), types of A and Sa match,
1622 // and this is a no-op.
1623 A = IRB.CreatePointerCast(A, Sa->getType());
1624 B = IRB.CreatePointerCast(B, Sb->getType());
1625
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001626 // A == B <==> (C = A^B) == 0
1627 // A != B <==> (C = A^B) != 0
1628 // Sc = Sa | Sb
1629 Value *C = IRB.CreateXor(A, B);
1630 Value *Sc = IRB.CreateOr(Sa, Sb);
1631 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1632 // Result is defined if one of the following is true
1633 // * there is a defined 1 bit in C
1634 // * C is fully defined
1635 // Si = !(C & ~Sc) && Sc
1636 Value *Zero = Constant::getNullValue(Sc->getType());
1637 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1638 Value *Si =
1639 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1640 IRB.CreateICmpEQ(
1641 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1642 Si->setName("_msprop_icmp");
1643 setShadow(&I, Si);
1644 setOriginForNaryOp(I);
1645 }
1646
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001647 /// \brief Build the lowest possible value of V, taking into account V's
1648 /// uninitialized bits.
1649 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1650 bool isSigned) {
1651 if (isSigned) {
1652 // Split shadow into sign bit and other bits.
1653 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1654 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1655 // Maximise the undefined shadow bit, minimize other undefined bits.
1656 return
1657 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1658 } else {
1659 // Minimize undefined bits.
1660 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1661 }
1662 }
1663
1664 /// \brief Build the highest possible value of V, taking into account V's
1665 /// uninitialized bits.
1666 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1667 bool isSigned) {
1668 if (isSigned) {
1669 // Split shadow into sign bit and other bits.
1670 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1671 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1672 // Minimise the undefined shadow bit, maximise other undefined bits.
1673 return
1674 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1675 } else {
1676 // Maximize undefined bits.
1677 return IRB.CreateOr(A, Sa);
1678 }
1679 }
1680
1681 /// \brief Instrument relational comparisons.
1682 ///
1683 /// This function does exact shadow propagation for all relational
1684 /// comparisons of integers, pointers and vectors of those.
1685 /// FIXME: output seems suboptimal when one of the operands is a constant
1686 void handleRelationalComparisonExact(ICmpInst &I) {
1687 IRBuilder<> IRB(&I);
1688 Value *A = I.getOperand(0);
1689 Value *B = I.getOperand(1);
1690 Value *Sa = getShadow(A);
1691 Value *Sb = getShadow(B);
1692
1693 // Get rid of pointers and vectors of pointers.
1694 // For ints (and vectors of ints), types of A and Sa match,
1695 // and this is a no-op.
1696 A = IRB.CreatePointerCast(A, Sa->getType());
1697 B = IRB.CreatePointerCast(B, Sb->getType());
1698
Evgeniy Stepanov2cb0fa12013-01-25 15:35:29 +00001699 // Let [a0, a1] be the interval of possible values of A, taking into account
1700 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1701 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001702 bool IsSigned = I.isSigned();
1703 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1704 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1705 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1706 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1707 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1708 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1709 Value *Si = IRB.CreateXor(S1, S2);
1710 setShadow(&I, Si);
1711 setOriginForNaryOp(I);
1712 }
1713
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001714 /// \brief Instrument signed relational comparisons.
1715 ///
1716 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1717 /// propagating the highest bit of the shadow. Everything else is delegated
1718 /// to handleShadowOr().
1719 void handleSignedRelationalComparison(ICmpInst &I) {
1720 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1721 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +00001722 Value* op = nullptr;
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001723 CmpInst::Predicate pre = I.getPredicate();
1724 if (constOp0 && constOp0->isNullValue() &&
1725 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1726 op = I.getOperand(1);
1727 } else if (constOp1 && constOp1->isNullValue() &&
1728 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1729 op = I.getOperand(0);
1730 }
1731 if (op) {
1732 IRBuilder<> IRB(&I);
1733 Value* Shadow =
1734 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1735 setShadow(&I, Shadow);
1736 setOrigin(&I, getOrigin(op));
1737 } else {
1738 handleShadowOr(I);
1739 }
1740 }
1741
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001742 void visitICmpInst(ICmpInst &I) {
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001743 if (!ClHandleICmp) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001744 handleShadowOr(I);
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001745 return;
1746 }
1747 if (I.isEquality()) {
1748 handleEqualityComparison(I);
1749 return;
1750 }
1751
1752 assert(I.isRelational());
1753 if (ClHandleICmpExact) {
1754 handleRelationalComparisonExact(I);
1755 return;
1756 }
1757 if (I.isSigned()) {
1758 handleSignedRelationalComparison(I);
1759 return;
1760 }
1761
1762 assert(I.isUnsigned());
1763 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1764 handleRelationalComparisonExact(I);
1765 return;
1766 }
1767
1768 handleShadowOr(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001769 }
1770
1771 void visitFCmpInst(FCmpInst &I) {
1772 handleShadowOr(I);
1773 }
1774
1775 void handleShift(BinaryOperator &I) {
1776 IRBuilder<> IRB(&I);
1777 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1778 // Otherwise perform the same shift on S1.
1779 Value *S1 = getShadow(&I, 0);
1780 Value *S2 = getShadow(&I, 1);
1781 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1782 S2->getType());
1783 Value *V2 = I.getOperand(1);
1784 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1785 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1786 setOriginForNaryOp(I);
1787 }
1788
1789 void visitShl(BinaryOperator &I) { handleShift(I); }
1790 void visitAShr(BinaryOperator &I) { handleShift(I); }
1791 void visitLShr(BinaryOperator &I) { handleShift(I); }
1792
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001793 /// \brief Instrument llvm.memmove
1794 ///
1795 /// At this point we don't know if llvm.memmove will be inlined or not.
1796 /// If we don't instrument it and it gets inlined,
1797 /// our interceptor will not kick in and we will lose the memmove.
1798 /// If we instrument the call here, but it does not get inlined,
1799 /// we will memove the shadow twice: which is bad in case
1800 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1801 ///
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001802 /// Similar situation exists for memcpy and memset.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001803 void visitMemMoveInst(MemMoveInst &I) {
1804 IRBuilder<> IRB(&I);
David Blaikieff6409d2015-05-18 22:13:54 +00001805 IRB.CreateCall(
1806 MS.MemmoveFn,
1807 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1808 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1809 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001810 I.eraseFromParent();
1811 }
1812
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001813 // Similar to memmove: avoid copying shadow twice.
1814 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1815 // FIXME: consider doing manual inline for small constant sizes and proper
1816 // alignment.
1817 void visitMemCpyInst(MemCpyInst &I) {
1818 IRBuilder<> IRB(&I);
David Blaikieff6409d2015-05-18 22:13:54 +00001819 IRB.CreateCall(
1820 MS.MemcpyFn,
1821 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1822 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1823 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001824 I.eraseFromParent();
1825 }
1826
1827 // Same as memcpy.
1828 void visitMemSetInst(MemSetInst &I) {
1829 IRBuilder<> IRB(&I);
David Blaikieff6409d2015-05-18 22:13:54 +00001830 IRB.CreateCall(
1831 MS.MemsetFn,
1832 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1833 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1834 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001835 I.eraseFromParent();
1836 }
1837
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001838 void visitVAStartInst(VAStartInst &I) {
1839 VAHelper->visitVAStartInst(I);
1840 }
1841
1842 void visitVACopyInst(VACopyInst &I) {
1843 VAHelper->visitVACopyInst(I);
1844 }
1845
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001846 enum IntrinsicKind {
1847 IK_DoesNotAccessMemory,
1848 IK_OnlyReadsMemory,
1849 IK_WritesMemory
1850 };
1851
1852 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1853 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1854 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1855 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1856 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1857 const int UnknownModRefBehavior = IK_WritesMemory;
1858#define GET_INTRINSIC_MODREF_BEHAVIOR
1859#define ModRefBehavior IntrinsicKind
Chandler Carruthdb25c6c2013-01-02 12:09:16 +00001860#include "llvm/IR/Intrinsics.gen"
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001861#undef ModRefBehavior
1862#undef GET_INTRINSIC_MODREF_BEHAVIOR
1863 }
1864
1865 /// \brief Handle vector store-like intrinsics.
1866 ///
1867 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1868 /// has 1 pointer argument and 1 vector argument, returns void.
1869 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1870 IRBuilder<> IRB(&I);
1871 Value* Addr = I.getArgOperand(0);
1872 Value *Shadow = getShadow(&I, 1);
1873 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1874
1875 // We don't know the pointer alignment (could be unaligned SSE store!).
1876 // Have to assume to worst case.
1877 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1878
1879 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001880 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001881
1882 // FIXME: use ClStoreCleanOrigin
1883 // FIXME: factor out common code from materializeStores
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001884 if (MS.TrackOrigins)
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00001885 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001886 return true;
1887 }
1888
1889 /// \brief Handle vector load-like intrinsics.
1890 ///
1891 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1892 /// has 1 pointer argument, returns a vector.
1893 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1894 IRBuilder<> IRB(&I);
1895 Value *Addr = I.getArgOperand(0);
1896
1897 Type *ShadowTy = getShadowTy(&I);
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001898 if (PropagateShadow) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001899 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1900 // We don't know the pointer alignment (could be unaligned SSE load!).
1901 // Have to assume to worst case.
1902 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1903 } else {
1904 setShadow(&I, getCleanShadow(&I));
1905 }
1906
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001907 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001908 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001909
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001910 if (MS.TrackOrigins) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001911 if (PropagateShadow)
Evgeniy Stepanovd85ddee2014-12-05 14:34:03 +00001912 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001913 else
1914 setOrigin(&I, getCleanOrigin());
1915 }
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001916 return true;
1917 }
1918
1919 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1920 ///
1921 /// Instrument intrinsics with any number of arguments of the same type,
1922 /// equal to the return type. The type should be simple (no aggregates or
1923 /// pointers; vectors are fine).
1924 /// Caller guarantees that this intrinsic does not access memory.
1925 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1926 Type *RetTy = I.getType();
1927 if (!(RetTy->isIntOrIntVectorTy() ||
1928 RetTy->isFPOrFPVectorTy() ||
1929 RetTy->isX86_MMXTy()))
1930 return false;
1931
1932 unsigned NumArgOperands = I.getNumArgOperands();
1933
1934 for (unsigned i = 0; i < NumArgOperands; ++i) {
1935 Type *Ty = I.getArgOperand(i)->getType();
1936 if (Ty != RetTy)
1937 return false;
1938 }
1939
1940 IRBuilder<> IRB(&I);
1941 ShadowAndOriginCombiner SC(this, IRB);
1942 for (unsigned i = 0; i < NumArgOperands; ++i)
1943 SC.Add(I.getArgOperand(i));
1944 SC.Done(&I);
1945
1946 return true;
1947 }
1948
1949 /// \brief Heuristically instrument unknown intrinsics.
1950 ///
1951 /// The main purpose of this code is to do something reasonable with all
1952 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1953 /// We recognize several classes of intrinsics by their argument types and
1954 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1955 /// sure that we know what the intrinsic does.
1956 ///
1957 /// We special-case intrinsics where this approach fails. See llvm.bswap
1958 /// handling as an example of that.
1959 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1960 unsigned NumArgOperands = I.getNumArgOperands();
1961 if (NumArgOperands == 0)
1962 return false;
1963
1964 Intrinsic::ID iid = I.getIntrinsicID();
1965 IntrinsicKind IK = getIntrinsicKind(iid);
1966 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1967 bool WritesMemory = IK == IK_WritesMemory;
1968 assert(!(OnlyReadsMemory && WritesMemory));
1969
1970 if (NumArgOperands == 2 &&
1971 I.getArgOperand(0)->getType()->isPointerTy() &&
1972 I.getArgOperand(1)->getType()->isVectorTy() &&
1973 I.getType()->isVoidTy() &&
1974 WritesMemory) {
1975 // This looks like a vector store.
1976 return handleVectorStoreIntrinsic(I);
1977 }
1978
1979 if (NumArgOperands == 1 &&
1980 I.getArgOperand(0)->getType()->isPointerTy() &&
1981 I.getType()->isVectorTy() &&
1982 OnlyReadsMemory) {
1983 // This looks like a vector load.
1984 return handleVectorLoadIntrinsic(I);
1985 }
1986
1987 if (!OnlyReadsMemory && !WritesMemory)
1988 if (maybeHandleSimpleNomemIntrinsic(I))
1989 return true;
1990
1991 // FIXME: detect and handle SSE maskstore/maskload
1992 return false;
1993 }
1994
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001995 void handleBswap(IntrinsicInst &I) {
1996 IRBuilder<> IRB(&I);
1997 Value *Op = I.getArgOperand(0);
1998 Type *OpType = Op->getType();
1999 Function *BswapFunc = Intrinsic::getDeclaration(
Craig Toppere1d12942014-08-27 05:25:25 +00002000 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002001 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2002 setOrigin(&I, getOrigin(Op));
2003 }
2004
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002005 // \brief Instrument vector convert instrinsic.
2006 //
2007 // This function instruments intrinsics like cvtsi2ss:
2008 // %Out = int_xxx_cvtyyy(%ConvertOp)
2009 // or
2010 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2011 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2012 // number \p Out elements, and (if has 2 arguments) copies the rest of the
2013 // elements from \p CopyOp.
2014 // In most cases conversion involves floating-point value which may trigger a
2015 // hardware exception when not fully initialized. For this reason we require
2016 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2017 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2018 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2019 // return a fully initialized value.
2020 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2021 IRBuilder<> IRB(&I);
2022 Value *CopyOp, *ConvertOp;
2023
2024 switch (I.getNumArgOperands()) {
Igor Bregerdfcc3d32015-06-17 07:23:57 +00002025 case 3:
2026 assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002027 case 2:
2028 CopyOp = I.getArgOperand(0);
2029 ConvertOp = I.getArgOperand(1);
2030 break;
2031 case 1:
2032 ConvertOp = I.getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002033 CopyOp = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002034 break;
2035 default:
2036 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2037 }
2038
2039 // The first *NumUsedElements* elements of ConvertOp are converted to the
2040 // same number of output elements. The rest of the output is copied from
2041 // CopyOp, or (if not available) filled with zeroes.
2042 // Combine shadow for elements of ConvertOp that are used in this operation,
2043 // and insert a check.
2044 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2045 // int->any conversion.
2046 Value *ConvertShadow = getShadow(ConvertOp);
Craig Topperf40110f2014-04-25 05:29:35 +00002047 Value *AggShadow = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002048 if (ConvertOp->getType()->isVectorTy()) {
2049 AggShadow = IRB.CreateExtractElement(
2050 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2051 for (int i = 1; i < NumUsedElements; ++i) {
2052 Value *MoreShadow = IRB.CreateExtractElement(
2053 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2054 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2055 }
2056 } else {
2057 AggShadow = ConvertShadow;
2058 }
2059 assert(AggShadow->getType()->isIntegerTy());
2060 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2061
2062 // Build result shadow by zero-filling parts of CopyOp shadow that come from
2063 // ConvertOp.
2064 if (CopyOp) {
2065 assert(CopyOp->getType() == I.getType());
2066 assert(CopyOp->getType()->isVectorTy());
2067 Value *ResultShadow = getShadow(CopyOp);
2068 Type *EltTy = ResultShadow->getType()->getVectorElementType();
2069 for (int i = 0; i < NumUsedElements; ++i) {
2070 ResultShadow = IRB.CreateInsertElement(
2071 ResultShadow, ConstantInt::getNullValue(EltTy),
2072 ConstantInt::get(IRB.getInt32Ty(), i));
2073 }
2074 setShadow(&I, ResultShadow);
2075 setOrigin(&I, getOrigin(CopyOp));
2076 } else {
2077 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00002078 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002079 }
2080 }
2081
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002082 // Given a scalar or vector, extract lower 64 bits (or less), and return all
2083 // zeroes if it is zero, and all ones otherwise.
2084 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2085 if (S->getType()->isVectorTy())
2086 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2087 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2088 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2089 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2090 }
2091
2092 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2093 Type *T = S->getType();
2094 assert(T->isVectorTy());
2095 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2096 return IRB.CreateSExt(S2, T);
2097 }
2098
2099 // \brief Instrument vector shift instrinsic.
2100 //
2101 // This function instruments intrinsics like int_x86_avx2_psll_w.
2102 // Intrinsic shifts %In by %ShiftSize bits.
2103 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2104 // size, and the rest is ignored. Behavior is defined even if shift size is
2105 // greater than register (or field) width.
2106 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2107 assert(I.getNumArgOperands() == 2);
2108 IRBuilder<> IRB(&I);
2109 // If any of the S2 bits are poisoned, the whole thing is poisoned.
2110 // Otherwise perform the same shift on S1.
2111 Value *S1 = getShadow(&I, 0);
2112 Value *S2 = getShadow(&I, 1);
2113 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2114 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2115 Value *V1 = I.getOperand(0);
2116 Value *V2 = I.getOperand(1);
David Blaikieff6409d2015-05-18 22:13:54 +00002117 Value *Shift = IRB.CreateCall(I.getCalledValue(),
2118 {IRB.CreateBitCast(S1, V1->getType()), V2});
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002119 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2120 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2121 setOriginForNaryOp(I);
2122 }
2123
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002124 // \brief Get an X86_MMX-sized vector type.
2125 Type *getMMXVectorTy(unsigned EltSizeInBits) {
2126 const unsigned X86_MMXSizeInBits = 64;
2127 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2128 X86_MMXSizeInBits / EltSizeInBits);
2129 }
2130
2131 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2132 // intrinsic.
2133 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2134 switch (id) {
2135 case llvm::Intrinsic::x86_sse2_packsswb_128:
2136 case llvm::Intrinsic::x86_sse2_packuswb_128:
2137 return llvm::Intrinsic::x86_sse2_packsswb_128;
2138
2139 case llvm::Intrinsic::x86_sse2_packssdw_128:
2140 case llvm::Intrinsic::x86_sse41_packusdw:
2141 return llvm::Intrinsic::x86_sse2_packssdw_128;
2142
2143 case llvm::Intrinsic::x86_avx2_packsswb:
2144 case llvm::Intrinsic::x86_avx2_packuswb:
2145 return llvm::Intrinsic::x86_avx2_packsswb;
2146
2147 case llvm::Intrinsic::x86_avx2_packssdw:
2148 case llvm::Intrinsic::x86_avx2_packusdw:
2149 return llvm::Intrinsic::x86_avx2_packssdw;
2150
2151 case llvm::Intrinsic::x86_mmx_packsswb:
2152 case llvm::Intrinsic::x86_mmx_packuswb:
2153 return llvm::Intrinsic::x86_mmx_packsswb;
2154
2155 case llvm::Intrinsic::x86_mmx_packssdw:
2156 return llvm::Intrinsic::x86_mmx_packssdw;
2157 default:
2158 llvm_unreachable("unexpected intrinsic id");
2159 }
2160 }
2161
Evgeniy Stepanov5d972932014-06-17 11:26:00 +00002162 // \brief Instrument vector pack instrinsic.
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002163 //
2164 // This function instruments intrinsics like x86_mmx_packsswb, that
Evgeniy Stepanov5d972932014-06-17 11:26:00 +00002165 // packs elements of 2 input vectors into half as many bits with saturation.
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002166 // Shadow is propagated with the signed variant of the same intrinsic applied
2167 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2168 // EltSizeInBits is used only for x86mmx arguments.
2169 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002170 assert(I.getNumArgOperands() == 2);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002171 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002172 IRBuilder<> IRB(&I);
2173 Value *S1 = getShadow(&I, 0);
2174 Value *S2 = getShadow(&I, 1);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002175 assert(isX86_MMX || S1->getType()->isVectorTy());
2176
2177 // SExt and ICmpNE below must apply to individual elements of input vectors.
2178 // In case of x86mmx arguments, cast them to appropriate vector types and
2179 // back.
2180 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2181 if (isX86_MMX) {
2182 S1 = IRB.CreateBitCast(S1, T);
2183 S2 = IRB.CreateBitCast(S2, T);
2184 }
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002185 Value *S1_ext = IRB.CreateSExt(
2186 IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2187 Value *S2_ext = IRB.CreateSExt(
2188 IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002189 if (isX86_MMX) {
2190 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2191 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2192 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2193 }
2194
2195 Function *ShadowFn = Intrinsic::getDeclaration(
2196 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2197
David Blaikieff6409d2015-05-18 22:13:54 +00002198 Value *S =
2199 IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002200 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002201 setShadow(&I, S);
2202 setOriginForNaryOp(I);
2203 }
2204
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002205 // \brief Instrument sum-of-absolute-differencies intrinsic.
2206 void handleVectorSadIntrinsic(IntrinsicInst &I) {
2207 const unsigned SignificantBitsPerResultElement = 16;
2208 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2209 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2210 unsigned ZeroBitsPerResultElement =
2211 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2212
2213 IRBuilder<> IRB(&I);
2214 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2215 S = IRB.CreateBitCast(S, ResTy);
2216 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2217 ResTy);
2218 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2219 S = IRB.CreateBitCast(S, getShadowTy(&I));
2220 setShadow(&I, S);
2221 setOriginForNaryOp(I);
2222 }
2223
2224 // \brief Instrument multiply-add intrinsic.
2225 void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2226 unsigned EltSizeInBits = 0) {
2227 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2228 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2229 IRBuilder<> IRB(&I);
2230 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2231 S = IRB.CreateBitCast(S, ResTy);
2232 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2233 ResTy);
2234 S = IRB.CreateBitCast(S, getShadowTy(&I));
2235 setShadow(&I, S);
2236 setOriginForNaryOp(I);
2237 }
2238
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002239 void visitIntrinsicInst(IntrinsicInst &I) {
2240 switch (I.getIntrinsicID()) {
2241 case llvm::Intrinsic::bswap:
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002242 handleBswap(I);
2243 break;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002244 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2245 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2246 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2247 case llvm::Intrinsic::x86_avx512_cvtss2usi:
2248 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2249 case llvm::Intrinsic::x86_avx512_cvttss2usi:
2250 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2251 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2252 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2253 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2254 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2255 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2256 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2257 case llvm::Intrinsic::x86_sse2_cvtsd2si:
2258 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2259 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2260 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2261 case llvm::Intrinsic::x86_sse2_cvtss2sd:
2262 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2263 case llvm::Intrinsic::x86_sse2_cvttsd2si:
2264 case llvm::Intrinsic::x86_sse_cvtsi2ss:
2265 case llvm::Intrinsic::x86_sse_cvtsi642ss:
2266 case llvm::Intrinsic::x86_sse_cvtss2si64:
2267 case llvm::Intrinsic::x86_sse_cvtss2si:
2268 case llvm::Intrinsic::x86_sse_cvttss2si64:
2269 case llvm::Intrinsic::x86_sse_cvttss2si:
2270 handleVectorConvertIntrinsic(I, 1);
2271 break;
2272 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2273 case llvm::Intrinsic::x86_sse2_cvtps2pd:
2274 case llvm::Intrinsic::x86_sse_cvtps2pi:
2275 case llvm::Intrinsic::x86_sse_cvttps2pi:
2276 handleVectorConvertIntrinsic(I, 2);
2277 break;
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002278 case llvm::Intrinsic::x86_avx2_psll_w:
2279 case llvm::Intrinsic::x86_avx2_psll_d:
2280 case llvm::Intrinsic::x86_avx2_psll_q:
2281 case llvm::Intrinsic::x86_avx2_pslli_w:
2282 case llvm::Intrinsic::x86_avx2_pslli_d:
2283 case llvm::Intrinsic::x86_avx2_pslli_q:
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002284 case llvm::Intrinsic::x86_avx2_psrl_w:
2285 case llvm::Intrinsic::x86_avx2_psrl_d:
2286 case llvm::Intrinsic::x86_avx2_psrl_q:
2287 case llvm::Intrinsic::x86_avx2_psra_w:
2288 case llvm::Intrinsic::x86_avx2_psra_d:
2289 case llvm::Intrinsic::x86_avx2_psrli_w:
2290 case llvm::Intrinsic::x86_avx2_psrli_d:
2291 case llvm::Intrinsic::x86_avx2_psrli_q:
2292 case llvm::Intrinsic::x86_avx2_psrai_w:
2293 case llvm::Intrinsic::x86_avx2_psrai_d:
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002294 case llvm::Intrinsic::x86_sse2_psll_w:
2295 case llvm::Intrinsic::x86_sse2_psll_d:
2296 case llvm::Intrinsic::x86_sse2_psll_q:
2297 case llvm::Intrinsic::x86_sse2_pslli_w:
2298 case llvm::Intrinsic::x86_sse2_pslli_d:
2299 case llvm::Intrinsic::x86_sse2_pslli_q:
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002300 case llvm::Intrinsic::x86_sse2_psrl_w:
2301 case llvm::Intrinsic::x86_sse2_psrl_d:
2302 case llvm::Intrinsic::x86_sse2_psrl_q:
2303 case llvm::Intrinsic::x86_sse2_psra_w:
2304 case llvm::Intrinsic::x86_sse2_psra_d:
2305 case llvm::Intrinsic::x86_sse2_psrli_w:
2306 case llvm::Intrinsic::x86_sse2_psrli_d:
2307 case llvm::Intrinsic::x86_sse2_psrli_q:
2308 case llvm::Intrinsic::x86_sse2_psrai_w:
2309 case llvm::Intrinsic::x86_sse2_psrai_d:
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002310 case llvm::Intrinsic::x86_mmx_psll_w:
2311 case llvm::Intrinsic::x86_mmx_psll_d:
2312 case llvm::Intrinsic::x86_mmx_psll_q:
2313 case llvm::Intrinsic::x86_mmx_pslli_w:
2314 case llvm::Intrinsic::x86_mmx_pslli_d:
2315 case llvm::Intrinsic::x86_mmx_pslli_q:
2316 case llvm::Intrinsic::x86_mmx_psrl_w:
2317 case llvm::Intrinsic::x86_mmx_psrl_d:
2318 case llvm::Intrinsic::x86_mmx_psrl_q:
2319 case llvm::Intrinsic::x86_mmx_psra_w:
2320 case llvm::Intrinsic::x86_mmx_psra_d:
2321 case llvm::Intrinsic::x86_mmx_psrli_w:
2322 case llvm::Intrinsic::x86_mmx_psrli_d:
2323 case llvm::Intrinsic::x86_mmx_psrli_q:
2324 case llvm::Intrinsic::x86_mmx_psrai_w:
2325 case llvm::Intrinsic::x86_mmx_psrai_d:
2326 handleVectorShiftIntrinsic(I, /* Variable */ false);
2327 break;
2328 case llvm::Intrinsic::x86_avx2_psllv_d:
2329 case llvm::Intrinsic::x86_avx2_psllv_d_256:
2330 case llvm::Intrinsic::x86_avx2_psllv_q:
2331 case llvm::Intrinsic::x86_avx2_psllv_q_256:
2332 case llvm::Intrinsic::x86_avx2_psrlv_d:
2333 case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2334 case llvm::Intrinsic::x86_avx2_psrlv_q:
2335 case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2336 case llvm::Intrinsic::x86_avx2_psrav_d:
2337 case llvm::Intrinsic::x86_avx2_psrav_d_256:
2338 handleVectorShiftIntrinsic(I, /* Variable */ true);
2339 break;
2340
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002341 case llvm::Intrinsic::x86_sse2_packsswb_128:
2342 case llvm::Intrinsic::x86_sse2_packssdw_128:
2343 case llvm::Intrinsic::x86_sse2_packuswb_128:
2344 case llvm::Intrinsic::x86_sse41_packusdw:
2345 case llvm::Intrinsic::x86_avx2_packsswb:
2346 case llvm::Intrinsic::x86_avx2_packssdw:
2347 case llvm::Intrinsic::x86_avx2_packuswb:
2348 case llvm::Intrinsic::x86_avx2_packusdw:
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002349 handleVectorPackIntrinsic(I);
2350 break;
2351
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002352 case llvm::Intrinsic::x86_mmx_packsswb:
2353 case llvm::Intrinsic::x86_mmx_packuswb:
2354 handleVectorPackIntrinsic(I, 16);
2355 break;
2356
2357 case llvm::Intrinsic::x86_mmx_packssdw:
2358 handleVectorPackIntrinsic(I, 32);
2359 break;
2360
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002361 case llvm::Intrinsic::x86_mmx_psad_bw:
2362 case llvm::Intrinsic::x86_sse2_psad_bw:
2363 case llvm::Intrinsic::x86_avx2_psad_bw:
2364 handleVectorSadIntrinsic(I);
2365 break;
2366
2367 case llvm::Intrinsic::x86_sse2_pmadd_wd:
2368 case llvm::Intrinsic::x86_avx2_pmadd_wd:
2369 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2370 case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2371 handleVectorPmaddIntrinsic(I);
2372 break;
2373
2374 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2375 handleVectorPmaddIntrinsic(I, 8);
2376 break;
2377
2378 case llvm::Intrinsic::x86_mmx_pmadd_wd:
2379 handleVectorPmaddIntrinsic(I, 16);
2380 break;
2381
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002382 default:
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002383 if (!handleUnknownIntrinsic(I))
2384 visitInstruction(I);
Evgeniy Stepanov88b8dce2012-12-17 16:30:05 +00002385 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002386 }
2387 }
2388
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002389 void visitCallSite(CallSite CS) {
2390 Instruction &I = *CS.getInstruction();
2391 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2392 if (CS.isCall()) {
Evgeniy Stepanov7ad7e832012-11-29 14:32:03 +00002393 CallInst *Call = cast<CallInst>(&I);
2394
2395 // For inline asm, do the usual thing: check argument shadow and mark all
2396 // outputs as clean. Note that any side effects of the inline asm that are
2397 // not immediately visible in its constraints are not handled.
2398 if (Call->isInlineAsm()) {
2399 visitInstruction(I);
2400 return;
2401 }
2402
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002403 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002404
2405 // We are going to insert code that relies on the fact that the callee
2406 // will become a non-readonly function after it is instrumented by us. To
2407 // prevent this code from being optimized out, mark that function
2408 // non-readonly in advance.
2409 if (Function *Func = Call->getCalledFunction()) {
2410 // Clear out readonly/readnone attributes.
2411 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002412 B.addAttribute(Attribute::ReadOnly)
2413 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00002414 Func->removeAttributes(AttributeSet::FunctionIndex,
2415 AttributeSet::get(Func->getContext(),
2416 AttributeSet::FunctionIndex,
2417 B));
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002418 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002419 }
2420 IRBuilder<> IRB(&I);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002421
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002422 unsigned ArgOffset = 0;
2423 DEBUG(dbgs() << " CallSite: " << I << "\n");
2424 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2425 ArgIt != End; ++ArgIt) {
2426 Value *A = *ArgIt;
2427 unsigned i = ArgIt - CS.arg_begin();
2428 if (!A->getType()->isSized()) {
2429 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2430 continue;
2431 }
2432 unsigned Size = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00002433 Value *Store = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002434 // Compute the Shadow for arg even if it is ByVal, because
2435 // in that case getShadow() will copy the actual arg shadow to
2436 // __msan_param_tls.
2437 Value *ArgShadow = getShadow(A);
2438 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2439 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2440 " Shadow: " << *ArgShadow << "\n");
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002441 bool ArgIsInitialized = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002442 const DataLayout &DL = F.getParent()->getDataLayout();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002443 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002444 assert(A->getType()->isPointerTy() &&
2445 "ByVal argument is not a pointer!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002446 Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00002447 if (ArgOffset + Size > kParamTLSSize) break;
Evgeniy Stepanove08633e2014-10-17 23:29:44 +00002448 unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2449 unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002450 Store = IRB.CreateMemCpy(ArgShadowBase,
2451 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2452 Size, Alignment);
2453 } else {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002454 Size = DL.getTypeAllocSize(A->getType());
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00002455 if (ArgOffset + Size > kParamTLSSize) break;
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002456 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2457 kShadowTLSAlignment);
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002458 Constant *Cst = dyn_cast<Constant>(ArgShadow);
2459 if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002460 }
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002461 if (MS.TrackOrigins && !ArgIsInitialized)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +00002462 IRB.CreateStore(getOrigin(A),
2463 getOriginPtrForArgument(A, IRB, ArgOffset));
Edwin Vane82f80d42013-01-29 17:42:24 +00002464 (void)Store;
Craig Toppere73658d2014-04-28 04:05:08 +00002465 assert(Size != 0 && Store != nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002466 DEBUG(dbgs() << " Param:" << *Store << "\n");
David Majnemerf3cadce2014-10-20 06:13:33 +00002467 ArgOffset += RoundUpToAlignment(Size, 8);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002468 }
2469 DEBUG(dbgs() << " done with call args\n");
2470
2471 FunctionType *FT =
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002472 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002473 if (FT->isVarArg()) {
2474 VAHelper->visitCallSite(CS, IRB);
2475 }
2476
2477 // Now, get the shadow for the RetVal.
2478 if (!I.getType()->isSized()) return;
2479 IRBuilder<> IRBBefore(&I);
Alp Tokercb402912014-01-24 17:20:08 +00002480 // Until we have full dynamic coverage, make sure the retval shadow is 0.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002481 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002482 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
Craig Topperf40110f2014-04-25 05:29:35 +00002483 Instruction *NextInsn = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002484 if (CS.isCall()) {
2485 NextInsn = I.getNextNode();
2486 } else {
2487 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2488 if (!NormalDest->getSinglePredecessor()) {
2489 // FIXME: this case is tricky, so we are just conservative here.
2490 // Perhaps we need to split the edge between this BB and NormalDest,
2491 // but a naive attempt to use SplitEdge leads to a crash.
2492 setShadow(&I, getCleanShadow(&I));
2493 setOrigin(&I, getCleanOrigin());
2494 return;
2495 }
2496 NextInsn = NormalDest->getFirstInsertionPt();
2497 assert(NextInsn &&
2498 "Could not find insertion point for retval shadow load");
2499 }
2500 IRBuilder<> IRBAfter(NextInsn);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002501 Value *RetvalShadow =
2502 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2503 kShadowTLSAlignment, "_msret");
2504 setShadow(&I, RetvalShadow);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002505 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002506 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2507 }
2508
2509 void visitReturnInst(ReturnInst &I) {
2510 IRBuilder<> IRB(&I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002511 Value *RetVal = I.getReturnValue();
2512 if (!RetVal) return;
2513 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2514 if (CheckReturnValue) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002515 insertShadowCheck(RetVal, &I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002516 Value *Shadow = getCleanShadow(RetVal);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002517 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002518 } else {
2519 Value *Shadow = getShadow(RetVal);
2520 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2521 // FIXME: make it conditional if ClStoreCleanOrigin==0
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002522 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002523 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2524 }
2525 }
2526
2527 void visitPHINode(PHINode &I) {
2528 IRBuilder<> IRB(&I);
Evgeniy Stepanovd948a5f2014-07-07 13:28:31 +00002529 if (!PropagateShadow) {
2530 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00002531 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanovd948a5f2014-07-07 13:28:31 +00002532 return;
2533 }
2534
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002535 ShadowPHINodes.push_back(&I);
2536 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2537 "_msphi_s"));
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002538 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002539 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2540 "_msphi_o"));
2541 }
2542
2543 void visitAllocaInst(AllocaInst &I) {
2544 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanov2e5a1f12014-12-03 14:15:53 +00002545 setOrigin(&I, getCleanOrigin());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002546 IRBuilder<> IRB(I.getNextNode());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002547 const DataLayout &DL = F.getParent()->getDataLayout();
2548 uint64_t Size = DL.getTypeAllocSize(I.getAllocatedType());
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002549 if (PoisonStack && ClPoisonStackWithCall) {
David Blaikieff6409d2015-05-18 22:13:54 +00002550 IRB.CreateCall(MS.MsanPoisonStackFn,
2551 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2552 ConstantInt::get(MS.IntptrTy, Size)});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002553 } else {
2554 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002555 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2556 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002557 }
2558
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002559 if (PoisonStack && MS.TrackOrigins) {
Alp Tokere69170a2014-06-26 22:52:05 +00002560 SmallString<2048> StackDescriptionStorage;
2561 raw_svector_ostream StackDescription(StackDescriptionStorage);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002562 // We create a string with a description of the stack allocation and
2563 // pass it into __msan_set_alloca_origin.
2564 // It will be printed by the run-time if stack-originated UMR is found.
2565 // The first 4 bytes of the string are set to '----' and will be replaced
2566 // by __msan_va_arg_overflow_size_tls at the first call.
2567 StackDescription << "----" << I.getName() << "@" << F.getName();
2568 Value *Descr =
2569 createPrivateNonConstGlobalForString(*F.getParent(),
2570 StackDescription.str());
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002571
David Blaikieff6409d2015-05-18 22:13:54 +00002572 IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
2573 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002574 ConstantInt::get(MS.IntptrTy, Size),
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002575 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
David Blaikieff6409d2015-05-18 22:13:54 +00002576 IRB.CreatePointerCast(&F, MS.IntptrTy)});
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002577 }
2578 }
2579
2580 void visitSelectInst(SelectInst& I) {
2581 IRBuilder<> IRB(&I);
Evgeniy Stepanov566f5912013-09-03 10:04:11 +00002582 // a = select b, c, d
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002583 Value *B = I.getCondition();
2584 Value *C = I.getTrueValue();
2585 Value *D = I.getFalseValue();
2586 Value *Sb = getShadow(B);
2587 Value *Sc = getShadow(C);
2588 Value *Sd = getShadow(D);
2589
2590 // Result shadow if condition shadow is 0.
2591 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2592 Value *Sa1;
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002593 if (I.getType()->isAggregateType()) {
2594 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2595 // an extra "select". This results in much more compact IR.
2596 // Sa = select Sb, poisoned, (select b, Sc, Sd)
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002597 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002598 } else {
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002599 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2600 // If Sb (condition is poisoned), look for bits in c and d that are equal
2601 // and both unpoisoned.
2602 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2603
2604 // Cast arguments to shadow-compatible type.
2605 C = CreateAppToShadowCast(IRB, C);
2606 D = CreateAppToShadowCast(IRB, D);
2607
2608 // Result shadow if condition shadow is 1.
2609 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002610 }
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002611 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2612 setShadow(&I, Sa);
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002613 if (MS.TrackOrigins) {
2614 // Origins are always i32, so any vector conditions must be flattened.
2615 // FIXME: consider tracking vector origins for app vectors?
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002616 if (B->getType()->isVectorTy()) {
2617 Type *FlatTy = getShadowTyNoVec(B->getType());
2618 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002619 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002620 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002621 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002622 }
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002623 // a = select b, c, d
2624 // Oa = Sb ? Ob : (b ? Oc : Od)
Evgeniy Stepanova0b68992014-11-28 11:17:58 +00002625 setOrigin(
2626 &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2627 IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2628 getOrigin(I.getFalseValue()))));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002629 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002630 }
2631
2632 void visitLandingPadInst(LandingPadInst &I) {
2633 // Do nothing.
2634 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2635 setShadow(&I, getCleanShadow(&I));
2636 setOrigin(&I, getCleanOrigin());
2637 }
2638
2639 void visitGetElementPtrInst(GetElementPtrInst &I) {
2640 handleShadowOr(I);
2641 }
2642
2643 void visitExtractValueInst(ExtractValueInst &I) {
2644 IRBuilder<> IRB(&I);
2645 Value *Agg = I.getAggregateOperand();
2646 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2647 Value *AggShadow = getShadow(Agg);
2648 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2649 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2650 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2651 setShadow(&I, ResShadow);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002652 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002653 }
2654
2655 void visitInsertValueInst(InsertValueInst &I) {
2656 IRBuilder<> IRB(&I);
2657 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2658 Value *AggShadow = getShadow(I.getAggregateOperand());
2659 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2660 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2661 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2662 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2663 DEBUG(dbgs() << " Res: " << *Res << "\n");
2664 setShadow(&I, Res);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002665 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002666 }
2667
2668 void dumpInst(Instruction &I) {
2669 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2670 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2671 } else {
2672 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2673 }
2674 errs() << "QQQ " << I << "\n";
2675 }
2676
2677 void visitResumeInst(ResumeInst &I) {
2678 DEBUG(dbgs() << "Resume: " << I << "\n");
2679 // Nothing to do here.
2680 }
2681
2682 void visitInstruction(Instruction &I) {
2683 // Everything else: stop propagating and check for poisoned shadow.
2684 if (ClDumpStrictInstructions)
2685 dumpInst(I);
2686 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2687 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002688 insertShadowCheck(I.getOperand(i), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002689 setShadow(&I, getCleanShadow(&I));
2690 setOrigin(&I, getCleanOrigin());
2691 }
2692};
2693
2694/// \brief AMD64-specific implementation of VarArgHelper.
2695struct VarArgAMD64Helper : public VarArgHelper {
2696 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2697 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002698 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002699 static const unsigned AMD64FpEndOffset = 176;
2700
2701 Function &F;
2702 MemorySanitizer &MS;
2703 MemorySanitizerVisitor &MSV;
2704 Value *VAArgTLSCopy;
2705 Value *VAArgOverflowSize;
2706
2707 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2708
2709 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2710 MemorySanitizerVisitor &MSV)
Craig Topperf40110f2014-04-25 05:29:35 +00002711 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2712 VAArgOverflowSize(nullptr) {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002713
2714 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2715
2716 ArgKind classifyArgument(Value* arg) {
2717 // A very rough approximation of X86_64 argument classification rules.
2718 Type *T = arg->getType();
2719 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2720 return AK_FloatingPoint;
2721 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2722 return AK_GeneralPurpose;
2723 if (T->isPointerTy())
2724 return AK_GeneralPurpose;
2725 return AK_Memory;
2726 }
2727
2728 // For VarArg functions, store the argument shadow in an ABI-specific format
2729 // that corresponds to va_list layout.
2730 // We do this because Clang lowers va_arg in the frontend, and this pass
2731 // only sees the low level code that deals with va_list internals.
2732 // A much easier alternative (provided that Clang emits va_arg instructions)
2733 // would have been to associate each live instance of va_list with a copy of
2734 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2735 // order.
Craig Topper3e4c6972014-03-05 09:10:37 +00002736 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002737 unsigned GpOffset = 0;
2738 unsigned FpOffset = AMD64GpEndOffset;
2739 unsigned OverflowOffset = AMD64FpEndOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002740 const DataLayout &DL = F.getParent()->getDataLayout();
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002741 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2742 ArgIt != End; ++ArgIt) {
2743 Value *A = *ArgIt;
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002744 unsigned ArgNo = CS.getArgumentNo(ArgIt);
2745 bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2746 if (IsByVal) {
2747 // ByVal arguments always go to the overflow area.
2748 assert(A->getType()->isPointerTy());
2749 Type *RealTy = A->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002750 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002751 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
David Majnemerf3cadce2014-10-20 06:13:33 +00002752 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002753 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2754 ArgSize, kShadowTLSAlignment);
2755 } else {
2756 ArgKind AK = classifyArgument(A);
2757 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2758 AK = AK_Memory;
2759 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2760 AK = AK_Memory;
2761 Value *Base;
2762 switch (AK) {
2763 case AK_GeneralPurpose:
2764 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2765 GpOffset += 8;
2766 break;
2767 case AK_FloatingPoint:
2768 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2769 FpOffset += 16;
2770 break;
2771 case AK_Memory:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002772 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002773 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
David Majnemerf3cadce2014-10-20 06:13:33 +00002774 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002775 }
2776 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002777 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002778 }
2779 Constant *OverflowSize =
2780 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2781 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2782 }
2783
2784 /// \brief Compute the shadow address for a given va_arg.
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002785 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002786 int ArgOffset) {
2787 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2788 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002789 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002790 "_msarg");
2791 }
2792
Craig Topper3e4c6972014-03-05 09:10:37 +00002793 void visitVAStartInst(VAStartInst &I) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002794 IRBuilder<> IRB(&I);
2795 VAStartInstrumentationList.push_back(&I);
2796 Value *VAListTag = I.getArgOperand(0);
2797 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2798
2799 // Unpoison the whole __va_list_tag.
2800 // FIXME: magic ABI constants.
2801 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00002802 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002803 }
2804
Craig Topper3e4c6972014-03-05 09:10:37 +00002805 void visitVACopyInst(VACopyInst &I) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002806 IRBuilder<> IRB(&I);
2807 Value *VAListTag = I.getArgOperand(0);
2808 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2809
2810 // Unpoison the whole __va_list_tag.
2811 // FIXME: magic ABI constants.
2812 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00002813 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002814 }
2815
Craig Topper3e4c6972014-03-05 09:10:37 +00002816 void finalizeInstrumentation() override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002817 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2818 "finalizeInstrumentation called twice");
2819 if (!VAStartInstrumentationList.empty()) {
2820 // If there is a va_start in this function, make a backup copy of
2821 // va_arg_tls somewhere in the function entry block.
2822 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2823 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2824 Value *CopySize =
2825 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2826 VAArgOverflowSize);
2827 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2828 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2829 }
2830
2831 // Instrument va_start.
2832 // Copy va_list shadow from the backup copy of the TLS contents.
2833 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2834 CallInst *OrigInst = VAStartInstrumentationList[i];
2835 IRBuilder<> IRB(OrigInst->getNextNode());
2836 Value *VAListTag = OrigInst->getArgOperand(0);
2837
2838 Value *RegSaveAreaPtrPtr =
2839 IRB.CreateIntToPtr(
2840 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2841 ConstantInt::get(MS.IntptrTy, 16)),
2842 Type::getInt64PtrTy(*MS.C));
2843 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2844 Value *RegSaveAreaShadowPtr =
2845 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2846 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2847 AMD64FpEndOffset, 16);
2848
2849 Value *OverflowArgAreaPtrPtr =
2850 IRB.CreateIntToPtr(
2851 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2852 ConstantInt::get(MS.IntptrTy, 8)),
2853 Type::getInt64PtrTy(*MS.C));
2854 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2855 Value *OverflowArgAreaShadowPtr =
2856 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
David Blaikie95d3e532015-04-03 23:03:54 +00002857 Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
2858 AMD64FpEndOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002859 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2860 }
2861 }
2862};
2863
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00002864/// \brief MIPS64-specific implementation of VarArgHelper.
2865struct VarArgMIPS64Helper : public VarArgHelper {
2866 Function &F;
2867 MemorySanitizer &MS;
2868 MemorySanitizerVisitor &MSV;
2869 Value *VAArgTLSCopy;
2870 Value *VAArgSize;
2871
2872 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2873
2874 VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
2875 MemorySanitizerVisitor &MSV)
2876 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2877 VAArgSize(nullptr) {}
2878
2879 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2880 unsigned VAArgOffset = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002881 const DataLayout &DL = F.getParent()->getDataLayout();
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00002882 for (CallSite::arg_iterator ArgIt = CS.arg_begin() + 1, End = CS.arg_end();
2883 ArgIt != End; ++ArgIt) {
2884 Value *A = *ArgIt;
2885 Value *Base;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002886 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00002887#if defined(__MIPSEB__) || defined(MIPSEB)
2888 // Adjusting the shadow for argument with size < 8 to match the placement
2889 // of bits in big endian system
2890 if (ArgSize < 8)
2891 VAArgOffset += (8 - ArgSize);
2892#endif
2893 Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
2894 VAArgOffset += ArgSize;
2895 VAArgOffset = RoundUpToAlignment(VAArgOffset, 8);
2896 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2897 }
2898
2899 Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
2900 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
2901 // a new class member i.e. it is the total size of all VarArgs.
2902 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
2903 }
2904
2905 /// \brief Compute the shadow address for a given va_arg.
2906 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2907 int ArgOffset) {
2908 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2909 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2910 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2911 "_msarg");
2912 }
2913
2914 void visitVAStartInst(VAStartInst &I) override {
2915 IRBuilder<> IRB(&I);
2916 VAStartInstrumentationList.push_back(&I);
2917 Value *VAListTag = I.getArgOperand(0);
2918 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2919 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2920 /* size */8, /* alignment */8, false);
2921 }
2922
2923 void visitVACopyInst(VACopyInst &I) override {
2924 IRBuilder<> IRB(&I);
2925 Value *VAListTag = I.getArgOperand(0);
2926 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2927 // Unpoison the whole __va_list_tag.
2928 // FIXME: magic ABI constants.
2929 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2930 /* size */8, /* alignment */8, false);
2931 }
2932
2933 void finalizeInstrumentation() override {
2934 assert(!VAArgSize && !VAArgTLSCopy &&
2935 "finalizeInstrumentation called twice");
2936 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2937 VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2938 Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
2939 VAArgSize);
2940
2941 if (!VAStartInstrumentationList.empty()) {
2942 // If there is a va_start in this function, make a backup copy of
2943 // va_arg_tls somewhere in the function entry block.
2944 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2945 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2946 }
2947
2948 // Instrument va_start.
2949 // Copy va_list shadow from the backup copy of the TLS contents.
2950 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2951 CallInst *OrigInst = VAStartInstrumentationList[i];
2952 IRBuilder<> IRB(OrigInst->getNextNode());
2953 Value *VAListTag = OrigInst->getArgOperand(0);
2954 Value *RegSaveAreaPtrPtr =
2955 IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2956 Type::getInt64PtrTy(*MS.C));
2957 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2958 Value *RegSaveAreaShadowPtr =
2959 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2960 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
2961 }
2962 }
2963};
2964
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002965/// \brief A no-op implementation of VarArgHelper.
2966struct VarArgNoOpHelper : public VarArgHelper {
2967 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2968 MemorySanitizerVisitor &MSV) {}
2969
Craig Topper3e4c6972014-03-05 09:10:37 +00002970 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002971
Craig Topper3e4c6972014-03-05 09:10:37 +00002972 void visitVAStartInst(VAStartInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002973
Craig Topper3e4c6972014-03-05 09:10:37 +00002974 void visitVACopyInst(VACopyInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002975
Craig Topper3e4c6972014-03-05 09:10:37 +00002976 void finalizeInstrumentation() override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002977};
2978
2979VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002980 MemorySanitizerVisitor &Visitor) {
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002981 // VarArg handling is only implemented on AMD64. False positives are possible
2982 // on other platforms.
2983 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2984 if (TargetTriple.getArch() == llvm::Triple::x86_64)
2985 return new VarArgAMD64Helper(Func, Msan, Visitor);
Mohit K. Bhakkad518946e2015-02-18 11:41:24 +00002986 else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
2987 TargetTriple.getArch() == llvm::Triple::mips64el)
2988 return new VarArgMIPS64Helper(Func, Msan, Visitor);
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002989 else
2990 return new VarArgNoOpHelper(Func, Msan, Visitor);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002991}
2992
2993} // namespace
2994
2995bool MemorySanitizer::runOnFunction(Function &F) {
Ismail Pazarbasie5048e12015-05-07 21:41:52 +00002996 if (&F == MsanCtorFunction)
2997 return false;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002998 MemorySanitizerVisitor Visitor(F, *this);
2999
3000 // Clear out readonly/readnone attributes.
3001 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003002 B.addAttribute(Attribute::ReadOnly)
3003 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00003004 F.removeAttributes(AttributeSet::FunctionIndex,
3005 AttributeSet::get(F.getContext(),
3006 AttributeSet::FunctionIndex, B));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00003007
3008 return Visitor.runOnFunction();
3009}