Fix Clang-tidy modernize-use-nullptr warnings in source directories and generated...
[oota-llvm.git] / lib / Transforms / Instrumentation / MemorySanitizer.cpp
1 //===-- 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 ///
13 /// 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).
44 ///
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
61 /// practice.
62 ///
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.
67 ///
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
92 //===----------------------------------------------------------------------===//
93
94 #include "llvm/Transforms/Instrumentation.h"
95 #include "llvm/ADT/DepthFirstIterator.h"
96 #include "llvm/ADT/SmallString.h"
97 #include "llvm/ADT/SmallVector.h"
98 #include "llvm/ADT/StringExtras.h"
99 #include "llvm/ADT/Triple.h"
100 #include "llvm/IR/DataLayout.h"
101 #include "llvm/IR/Function.h"
102 #include "llvm/IR/IRBuilder.h"
103 #include "llvm/IR/InlineAsm.h"
104 #include "llvm/IR/InstVisitor.h"
105 #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"
110 #include "llvm/IR/ValueMap.h"
111 #include "llvm/Support/CommandLine.h"
112 #include "llvm/Support/Compiler.h"
113 #include "llvm/Support/Debug.h"
114 #include "llvm/Support/raw_ostream.h"
115 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include "llvm/Transforms/Utils/ModuleUtils.h"
118
119 using namespace llvm;
120
121 #define DEBUG_TYPE "msan"
122
123 // VMA size definition for architecture that support multiple sizes.
124 // AArch64 has 3 VMA sizes: 39, 42 and 48.
125 #ifndef SANITIZER_AARCH64_VMA
126 # define SANITIZER_AARCH64_VMA 39
127 #else
128 # if SANITIZER_AARCH64_VMA != 39 && SANITIZER_AARCH64_VMA != 42
129 #  error "invalid SANITIZER_AARCH64_VMA size"
130 # endif
131 #endif
132
133 static const unsigned kOriginSize = 4;
134 static const unsigned kMinOriginAlignment = 4;
135 static const unsigned kShadowTLSAlignment = 8;
136
137 // These constants must be kept in sync with the ones in msan.h.
138 static const unsigned kParamTLSSize = 800;
139 static const unsigned kRetvalTLSSize = 800;
140
141 // Accesses sizes are powers of two: 1, 2, 4, 8.
142 static const size_t kNumberOfAccessSizes = 4;
143
144 /// \brief Track origins of uninitialized values.
145 ///
146 /// Adds a section to MemorySanitizer report that points to the allocation
147 /// (stack or heap) the uninitialized bits came from originally.
148 static cl::opt<int> ClTrackOrigins("msan-track-origins",
149        cl::desc("Track origins (allocation sites) of poisoned memory"),
150        cl::Hidden, cl::init(0));
151 static cl::opt<bool> ClKeepGoing("msan-keep-going",
152        cl::desc("keep going after reporting a UMR"),
153        cl::Hidden, cl::init(false));
154 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
155        cl::desc("poison uninitialized stack variables"),
156        cl::Hidden, cl::init(true));
157 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
158        cl::desc("poison uninitialized stack variables with a call"),
159        cl::Hidden, cl::init(false));
160 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
161        cl::desc("poison uninitialized stack variables with the given pattern"),
162        cl::Hidden, cl::init(0xff));
163 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
164        cl::desc("poison undef temps"),
165        cl::Hidden, cl::init(true));
166
167 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
168        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
169        cl::Hidden, cl::init(true));
170
171 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
172        cl::desc("exact handling of relational integer ICmp"),
173        cl::Hidden, cl::init(false));
174
175 // This flag controls whether we check the shadow of the address
176 // operand of load or store. Such bugs are very rare, since load from
177 // a garbage address typically results in SEGV, but still happen
178 // (e.g. only lower bits of address are garbage, or the access happens
179 // early at program startup where malloc-ed memory is more likely to
180 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
181 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
182        cl::desc("report accesses through a pointer which has poisoned shadow"),
183        cl::Hidden, cl::init(true));
184
185 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
186        cl::desc("print out instructions with default strict semantics"),
187        cl::Hidden, cl::init(false));
188
189 static cl::opt<int> ClInstrumentationWithCallThreshold(
190     "msan-instrumentation-with-call-threshold",
191     cl::desc(
192         "If the function being instrumented requires more than "
193         "this number of checks and origin stores, use callbacks instead of "
194         "inline checks (-1 means never use callbacks)."),
195     cl::Hidden, cl::init(3500));
196
197 // This is an experiment to enable handling of cases where shadow is a non-zero
198 // compile-time constant. For some unexplainable reason they were silently
199 // ignored in the instrumentation.
200 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
201        cl::desc("Insert checks for constant shadow values"),
202        cl::Hidden, cl::init(false));
203
204 static const char *const kMsanModuleCtorName = "msan.module_ctor";
205 static const char *const kMsanInitName = "__msan_init";
206
207 namespace {
208
209 // Memory map parameters used in application-to-shadow address calculation.
210 // Offset = (Addr & ~AndMask) ^ XorMask
211 // Shadow = ShadowBase + Offset
212 // Origin = OriginBase + Offset
213 struct MemoryMapParams {
214   uint64_t AndMask;
215   uint64_t XorMask;
216   uint64_t ShadowBase;
217   uint64_t OriginBase;
218 };
219
220 struct PlatformMemoryMapParams {
221   const MemoryMapParams *bits32;
222   const MemoryMapParams *bits64;
223 };
224
225 // i386 Linux
226 static const MemoryMapParams Linux_I386_MemoryMapParams = {
227   0x000080000000,  // AndMask
228   0,               // XorMask (not used)
229   0,               // ShadowBase (not used)
230   0x000040000000,  // OriginBase
231 };
232
233 // x86_64 Linux
234 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
235   0x400000000000,  // AndMask
236   0,               // XorMask (not used)
237   0,               // ShadowBase (not used)
238   0x200000000000,  // OriginBase
239 };
240
241 // mips64 Linux
242 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
243   0x004000000000,  // AndMask
244   0,               // XorMask (not used)
245   0,               // ShadowBase (not used)
246   0x002000000000,  // OriginBase
247 };
248
249 // ppc64 Linux
250 static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
251   0x200000000000,  // AndMask
252   0x100000000000,  // XorMask
253   0x080000000000,  // ShadowBase
254   0x1C0000000000,  // OriginBase
255 };
256
257 // aarch64 Linux
258 static const MemoryMapParams Linux_AArch64_MemoryMapParams = {
259 #if SANITIZER_AARCH64_VMA == 39
260   0x007C00000000,  // AndMask
261   0x000100000000,  // XorMask
262   0x004000000000,  // ShadowBase
263   0x004300000000,  // OriginBase
264 #elif SANITIZER_AARCH64_VMA == 42
265   0x03E000000000,  // AndMask
266   0x001000000000,  // XorMask
267   0x010000000000,  // ShadowBase
268   0x012000000000,  // OriginBase
269 #endif
270 };
271
272 // i386 FreeBSD
273 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
274   0x000180000000,  // AndMask
275   0x000040000000,  // XorMask
276   0x000020000000,  // ShadowBase
277   0x000700000000,  // OriginBase
278 };
279
280 // x86_64 FreeBSD
281 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
282   0xc00000000000,  // AndMask
283   0x200000000000,  // XorMask
284   0x100000000000,  // ShadowBase
285   0x380000000000,  // OriginBase
286 };
287
288 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
289   &Linux_I386_MemoryMapParams,
290   &Linux_X86_64_MemoryMapParams,
291 };
292
293 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
294   nullptr,
295   &Linux_MIPS64_MemoryMapParams,
296 };
297
298 static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
299   nullptr,
300   &Linux_PowerPC64_MemoryMapParams,
301 };
302
303 static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = {
304   nullptr,
305   &Linux_AArch64_MemoryMapParams,
306 };
307
308 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
309   &FreeBSD_I386_MemoryMapParams,
310   &FreeBSD_X86_64_MemoryMapParams,
311 };
312
313 /// \brief An instrumentation pass implementing detection of uninitialized
314 /// reads.
315 ///
316 /// MemorySanitizer: instrument the code in module to find
317 /// uninitialized reads.
318 class MemorySanitizer : public FunctionPass {
319  public:
320   MemorySanitizer(int TrackOrigins = 0)
321       : FunctionPass(ID),
322         TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
323         WarningFn(nullptr) {}
324   const char *getPassName() const override { return "MemorySanitizer"; }
325   bool runOnFunction(Function &F) override;
326   bool doInitialization(Module &M) override;
327   static char ID;  // Pass identification, replacement for typeid.
328
329  private:
330   void initializeCallbacks(Module &M);
331
332   /// \brief Track origins (allocation points) of uninitialized values.
333   int TrackOrigins;
334
335   LLVMContext *C;
336   Type *IntptrTy;
337   Type *OriginTy;
338   /// \brief Thread-local shadow storage for function parameters.
339   GlobalVariable *ParamTLS;
340   /// \brief Thread-local origin storage for function parameters.
341   GlobalVariable *ParamOriginTLS;
342   /// \brief Thread-local shadow storage for function return value.
343   GlobalVariable *RetvalTLS;
344   /// \brief Thread-local origin storage for function return value.
345   GlobalVariable *RetvalOriginTLS;
346   /// \brief Thread-local shadow storage for in-register va_arg function
347   /// parameters (x86_64-specific).
348   GlobalVariable *VAArgTLS;
349   /// \brief Thread-local shadow storage for va_arg overflow area
350   /// (x86_64-specific).
351   GlobalVariable *VAArgOverflowSizeTLS;
352   /// \brief Thread-local space used to pass origin value to the UMR reporting
353   /// function.
354   GlobalVariable *OriginTLS;
355
356   /// \brief The run-time callback to print a warning.
357   Value *WarningFn;
358   // These arrays are indexed by log2(AccessSize).
359   Value *MaybeWarningFn[kNumberOfAccessSizes];
360   Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
361
362   /// \brief Run-time helper that generates a new origin value for a stack
363   /// allocation.
364   Value *MsanSetAllocaOrigin4Fn;
365   /// \brief Run-time helper that poisons stack on function entry.
366   Value *MsanPoisonStackFn;
367   /// \brief Run-time helper that records a store (or any event) of an
368   /// uninitialized value and returns an updated origin id encoding this info.
369   Value *MsanChainOriginFn;
370   /// \brief MSan runtime replacements for memmove, memcpy and memset.
371   Value *MemmoveFn, *MemcpyFn, *MemsetFn;
372
373   /// \brief Memory map parameters used in application-to-shadow calculation.
374   const MemoryMapParams *MapParams;
375
376   MDNode *ColdCallWeights;
377   /// \brief Branch weights for origin store.
378   MDNode *OriginStoreWeights;
379   /// \brief An empty volatile inline asm that prevents callback merge.
380   InlineAsm *EmptyAsm;
381   Function *MsanCtorFunction;
382
383   friend struct MemorySanitizerVisitor;
384   friend struct VarArgAMD64Helper;
385   friend struct VarArgMIPS64Helper;
386 };
387 } // anonymous namespace
388
389 char MemorySanitizer::ID = 0;
390 INITIALIZE_PASS(MemorySanitizer, "msan",
391                 "MemorySanitizer: detects uninitialized reads.",
392                 false, false)
393
394 FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
395   return new MemorySanitizer(TrackOrigins);
396 }
397
398 /// \brief Create a non-const global initialized with the given string.
399 ///
400 /// Creates a writable global for Str so that we can pass it to the
401 /// run-time lib. Runtime uses first 4 bytes of the string to store the
402 /// frame ID, so the string needs to be mutable.
403 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
404                                                             StringRef Str) {
405   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
406   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
407                             GlobalValue::PrivateLinkage, StrConst, "");
408 }
409
410 /// \brief Insert extern declaration of runtime-provided functions and globals.
411 void MemorySanitizer::initializeCallbacks(Module &M) {
412   // Only do this once.
413   if (WarningFn)
414     return;
415
416   IRBuilder<> IRB(*C);
417   // Create the callback.
418   // FIXME: this function should have "Cold" calling conv,
419   // which is not yet implemented.
420   StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
421                                         : "__msan_warning_noreturn";
422   WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
423
424   for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
425        AccessSizeIndex++) {
426     unsigned AccessSize = 1 << AccessSizeIndex;
427     std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
428     MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
429         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
430         IRB.getInt32Ty(), nullptr);
431
432     FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
433     MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
434         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
435         IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
436   }
437
438   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
439     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
440     IRB.getInt8PtrTy(), IntptrTy, nullptr);
441   MsanPoisonStackFn =
442       M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
443                             IRB.getInt8PtrTy(), IntptrTy, nullptr);
444   MsanChainOriginFn = M.getOrInsertFunction(
445     "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
446   MemmoveFn = M.getOrInsertFunction(
447     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
448     IRB.getInt8PtrTy(), IntptrTy, nullptr);
449   MemcpyFn = M.getOrInsertFunction(
450     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
451     IntptrTy, nullptr);
452   MemsetFn = M.getOrInsertFunction(
453     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
454     IntptrTy, nullptr);
455
456   // Create globals.
457   RetvalTLS = new GlobalVariable(
458     M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
459     GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
460     GlobalVariable::InitialExecTLSModel);
461   RetvalOriginTLS = new GlobalVariable(
462     M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
463     "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
464
465   ParamTLS = new GlobalVariable(
466     M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
467     GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
468     GlobalVariable::InitialExecTLSModel);
469   ParamOriginTLS = new GlobalVariable(
470     M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
471     GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
472     nullptr, GlobalVariable::InitialExecTLSModel);
473
474   VAArgTLS = new GlobalVariable(
475     M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
476     GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
477     GlobalVariable::InitialExecTLSModel);
478   VAArgOverflowSizeTLS = new GlobalVariable(
479     M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
480     "__msan_va_arg_overflow_size_tls", nullptr,
481     GlobalVariable::InitialExecTLSModel);
482   OriginTLS = new GlobalVariable(
483     M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
484     "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
485
486   // We insert an empty inline asm after __msan_report* to avoid callback merge.
487   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
488                             StringRef(""), StringRef(""),
489                             /*hasSideEffects=*/true);
490 }
491
492 /// \brief Module-level initialization.
493 ///
494 /// inserts a call to __msan_init to the module's constructor list.
495 bool MemorySanitizer::doInitialization(Module &M) {
496   auto &DL = M.getDataLayout();
497
498   Triple TargetTriple(M.getTargetTriple());
499   switch (TargetTriple.getOS()) {
500     case Triple::FreeBSD:
501       switch (TargetTriple.getArch()) {
502         case Triple::x86_64:
503           MapParams = FreeBSD_X86_MemoryMapParams.bits64;
504           break;
505         case Triple::x86:
506           MapParams = FreeBSD_X86_MemoryMapParams.bits32;
507           break;
508         default:
509           report_fatal_error("unsupported architecture");
510       }
511       break;
512     case Triple::Linux:
513       switch (TargetTriple.getArch()) {
514         case Triple::x86_64:
515           MapParams = Linux_X86_MemoryMapParams.bits64;
516           break;
517         case Triple::x86:
518           MapParams = Linux_X86_MemoryMapParams.bits32;
519           break;
520         case Triple::mips64:
521         case Triple::mips64el:
522           MapParams = Linux_MIPS_MemoryMapParams.bits64;
523           break;
524         case Triple::ppc64:
525         case Triple::ppc64le:
526           MapParams = Linux_PowerPC_MemoryMapParams.bits64;
527           break;
528         case Triple::aarch64:
529         case Triple::aarch64_be:
530           MapParams = Linux_ARM_MemoryMapParams.bits64;
531           break;
532         default:
533           report_fatal_error("unsupported architecture");
534       }
535       break;
536     default:
537       report_fatal_error("unsupported operating system");
538   }
539
540   C = &(M.getContext());
541   IRBuilder<> IRB(*C);
542   IntptrTy = IRB.getIntPtrTy(DL);
543   OriginTy = IRB.getInt32Ty();
544
545   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
546   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
547
548   std::tie(MsanCtorFunction, std::ignore) =
549       createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
550                                           /*InitArgTypes=*/{},
551                                           /*InitArgs=*/{});
552
553   appendToGlobalCtors(M, MsanCtorFunction, 0);
554
555   if (TrackOrigins)
556     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
557                        IRB.getInt32(TrackOrigins), "__msan_track_origins");
558
559   if (ClKeepGoing)
560     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
561                        IRB.getInt32(ClKeepGoing), "__msan_keep_going");
562
563   return true;
564 }
565
566 namespace {
567
568 /// \brief A helper class that handles instrumentation of VarArg
569 /// functions on a particular platform.
570 ///
571 /// Implementations are expected to insert the instrumentation
572 /// necessary to propagate argument shadow through VarArg function
573 /// calls. Visit* methods are called during an InstVisitor pass over
574 /// the function, and should avoid creating new basic blocks. A new
575 /// instance of this class is created for each instrumented function.
576 struct VarArgHelper {
577   /// \brief Visit a CallSite.
578   virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
579
580   /// \brief Visit a va_start call.
581   virtual void visitVAStartInst(VAStartInst &I) = 0;
582
583   /// \brief Visit a va_copy call.
584   virtual void visitVACopyInst(VACopyInst &I) = 0;
585
586   /// \brief Finalize function instrumentation.
587   ///
588   /// This method is called after visiting all interesting (see above)
589   /// instructions in a function.
590   virtual void finalizeInstrumentation() = 0;
591
592   virtual ~VarArgHelper() {}
593 };
594
595 struct MemorySanitizerVisitor;
596
597 VarArgHelper*
598 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
599                    MemorySanitizerVisitor &Visitor);
600
601 unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
602   if (TypeSize <= 8) return 0;
603   return Log2_32_Ceil(TypeSize / 8);
604 }
605
606 /// This class does all the work for a given function. Store and Load
607 /// instructions store and load corresponding shadow and origin
608 /// values. Most instructions propagate shadow from arguments to their
609 /// return values. Certain instructions (most importantly, BranchInst)
610 /// test their argument shadow and print reports (with a runtime call) if it's
611 /// non-zero.
612 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
613   Function &F;
614   MemorySanitizer &MS;
615   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
616   ValueMap<Value*, Value*> ShadowMap, OriginMap;
617   std::unique_ptr<VarArgHelper> VAHelper;
618
619   // The following flags disable parts of MSan instrumentation based on
620   // blacklist contents and command-line options.
621   bool InsertChecks;
622   bool PropagateShadow;
623   bool PoisonStack;
624   bool PoisonUndef;
625   bool CheckReturnValue;
626
627   struct ShadowOriginAndInsertPoint {
628     Value *Shadow;
629     Value *Origin;
630     Instruction *OrigIns;
631     ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
632       : Shadow(S), Origin(O), OrigIns(I) { }
633   };
634   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
635   SmallVector<Instruction*, 16> StoreList;
636
637   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
638       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
639     bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
640     InsertChecks = SanitizeFunction;
641     PropagateShadow = SanitizeFunction;
642     PoisonStack = SanitizeFunction && ClPoisonStack;
643     PoisonUndef = SanitizeFunction && ClPoisonUndef;
644     // FIXME: Consider using SpecialCaseList to specify a list of functions that
645     // must always return fully initialized values. For now, we hardcode "main".
646     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
647
648     DEBUG(if (!InsertChecks)
649           dbgs() << "MemorySanitizer is not inserting checks into '"
650                  << F.getName() << "'\n");
651   }
652
653   Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
654     if (MS.TrackOrigins <= 1) return V;
655     return IRB.CreateCall(MS.MsanChainOriginFn, V);
656   }
657
658   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
659     const DataLayout &DL = F.getParent()->getDataLayout();
660     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
661     if (IntptrSize == kOriginSize) return Origin;
662     assert(IntptrSize == kOriginSize * 2);
663     Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
664     return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
665   }
666
667   /// \brief Fill memory range with the given origin value.
668   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
669                    unsigned Size, unsigned Alignment) {
670     const DataLayout &DL = F.getParent()->getDataLayout();
671     unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
672     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
673     assert(IntptrAlignment >= kMinOriginAlignment);
674     assert(IntptrSize >= kOriginSize);
675
676     unsigned Ofs = 0;
677     unsigned CurrentAlignment = Alignment;
678     if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
679       Value *IntptrOrigin = originToIntptr(IRB, Origin);
680       Value *IntptrOriginPtr =
681           IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
682       for (unsigned i = 0; i < Size / IntptrSize; ++i) {
683         Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
684                        : IntptrOriginPtr;
685         IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
686         Ofs += IntptrSize / kOriginSize;
687         CurrentAlignment = IntptrAlignment;
688       }
689     }
690
691     for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
692       Value *GEP =
693           i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
694       IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
695       CurrentAlignment = kMinOriginAlignment;
696     }
697   }
698
699   void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
700                    unsigned Alignment, bool AsCall) {
701     const DataLayout &DL = F.getParent()->getDataLayout();
702     unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
703     unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
704     if (isa<StructType>(Shadow->getType())) {
705       paintOrigin(IRB, updateOrigin(Origin, IRB),
706                   getOriginPtr(Addr, IRB, Alignment), StoreSize,
707                   OriginAlignment);
708     } else {
709       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
710       Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
711       if (ConstantShadow) {
712         if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
713           paintOrigin(IRB, updateOrigin(Origin, IRB),
714                       getOriginPtr(Addr, IRB, Alignment), StoreSize,
715                       OriginAlignment);
716         return;
717       }
718
719       unsigned TypeSizeInBits =
720           DL.getTypeSizeInBits(ConvertedShadow->getType());
721       unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
722       if (AsCall && SizeIndex < kNumberOfAccessSizes) {
723         Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
724         Value *ConvertedShadow2 = IRB.CreateZExt(
725             ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
726         IRB.CreateCall(Fn, {ConvertedShadow2,
727                             IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
728                             Origin});
729       } else {
730         Value *Cmp = IRB.CreateICmpNE(
731             ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
732         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
733             Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
734         IRBuilder<> IRBNew(CheckTerm);
735         paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
736                     getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
737                     OriginAlignment);
738       }
739     }
740   }
741
742   void materializeStores(bool InstrumentWithCalls) {
743     for (auto Inst : StoreList) {
744       StoreInst &SI = *dyn_cast<StoreInst>(Inst);
745
746       IRBuilder<> IRB(&SI);
747       Value *Val = SI.getValueOperand();
748       Value *Addr = SI.getPointerOperand();
749       Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
750       Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
751
752       StoreInst *NewSI =
753           IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
754       DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
755       (void)NewSI;
756
757       if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
758
759       if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
760
761       if (MS.TrackOrigins && !SI.isAtomic())
762         storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI.getAlignment(),
763                     InstrumentWithCalls);
764     }
765   }
766
767   void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
768                            bool AsCall) {
769     IRBuilder<> IRB(OrigIns);
770     DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
771     Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
772     DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
773
774     Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
775     if (ConstantShadow) {
776       if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
777         if (MS.TrackOrigins) {
778           IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
779                           MS.OriginTLS);
780         }
781         IRB.CreateCall(MS.WarningFn, {});
782         IRB.CreateCall(MS.EmptyAsm, {});
783         // FIXME: Insert UnreachableInst if !ClKeepGoing?
784         // This may invalidate some of the following checks and needs to be done
785         // at the very end.
786       }
787       return;
788     }
789
790     const DataLayout &DL = OrigIns->getModule()->getDataLayout();
791
792     unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
793     unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
794     if (AsCall && SizeIndex < kNumberOfAccessSizes) {
795       Value *Fn = MS.MaybeWarningFn[SizeIndex];
796       Value *ConvertedShadow2 =
797           IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
798       IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
799                                                 ? Origin
800                                                 : (Value *)IRB.getInt32(0)});
801     } else {
802       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
803                                     getCleanShadow(ConvertedShadow), "_mscmp");
804       Instruction *CheckTerm = SplitBlockAndInsertIfThen(
805           Cmp, OrigIns,
806           /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
807
808       IRB.SetInsertPoint(CheckTerm);
809       if (MS.TrackOrigins) {
810         IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
811                         MS.OriginTLS);
812       }
813       IRB.CreateCall(MS.WarningFn, {});
814       IRB.CreateCall(MS.EmptyAsm, {});
815       DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
816     }
817   }
818
819   void materializeChecks(bool InstrumentWithCalls) {
820     for (const auto &ShadowData : InstrumentationList) {
821       Instruction *OrigIns = ShadowData.OrigIns;
822       Value *Shadow = ShadowData.Shadow;
823       Value *Origin = ShadowData.Origin;
824       materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
825     }
826     DEBUG(dbgs() << "DONE:\n" << F);
827   }
828
829   /// \brief Add MemorySanitizer instrumentation to a function.
830   bool runOnFunction() {
831     MS.initializeCallbacks(*F.getParent());
832
833     // In the presence of unreachable blocks, we may see Phi nodes with
834     // incoming nodes from such blocks. Since InstVisitor skips unreachable
835     // blocks, such nodes will not have any shadow value associated with them.
836     // It's easier to remove unreachable blocks than deal with missing shadow.
837     removeUnreachableBlocks(F);
838
839     // Iterate all BBs in depth-first order and create shadow instructions
840     // for all instructions (where applicable).
841     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
842     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
843       visit(*BB);
844
845
846     // Finalize PHI nodes.
847     for (PHINode *PN : ShadowPHINodes) {
848       PHINode *PNS = cast<PHINode>(getShadow(PN));
849       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
850       size_t NumValues = PN->getNumIncomingValues();
851       for (size_t v = 0; v < NumValues; v++) {
852         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
853         if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
854       }
855     }
856
857     VAHelper->finalizeInstrumentation();
858
859     bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
860                                InstrumentationList.size() + StoreList.size() >
861                                    (unsigned)ClInstrumentationWithCallThreshold;
862
863     // Delayed instrumentation of StoreInst.
864     // This may add new checks to be inserted later.
865     materializeStores(InstrumentWithCalls);
866
867     // Insert shadow value checks.
868     materializeChecks(InstrumentWithCalls);
869
870     return true;
871   }
872
873   /// \brief Compute the shadow type that corresponds to a given Value.
874   Type *getShadowTy(Value *V) {
875     return getShadowTy(V->getType());
876   }
877
878   /// \brief Compute the shadow type that corresponds to a given Type.
879   Type *getShadowTy(Type *OrigTy) {
880     if (!OrigTy->isSized()) {
881       return nullptr;
882     }
883     // For integer type, shadow is the same as the original type.
884     // This may return weird-sized types like i1.
885     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
886       return IT;
887     const DataLayout &DL = F.getParent()->getDataLayout();
888     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
889       uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
890       return VectorType::get(IntegerType::get(*MS.C, EltSize),
891                              VT->getNumElements());
892     }
893     if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
894       return ArrayType::get(getShadowTy(AT->getElementType()),
895                             AT->getNumElements());
896     }
897     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
898       SmallVector<Type*, 4> Elements;
899       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
900         Elements.push_back(getShadowTy(ST->getElementType(i)));
901       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
902       DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
903       return Res;
904     }
905     uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
906     return IntegerType::get(*MS.C, TypeSize);
907   }
908
909   /// \brief Flatten a vector type.
910   Type *getShadowTyNoVec(Type *ty) {
911     if (VectorType *vt = dyn_cast<VectorType>(ty))
912       return IntegerType::get(*MS.C, vt->getBitWidth());
913     return ty;
914   }
915
916   /// \brief Convert a shadow value to it's flattened variant.
917   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
918     Type *Ty = V->getType();
919     Type *NoVecTy = getShadowTyNoVec(Ty);
920     if (Ty == NoVecTy) return V;
921     return IRB.CreateBitCast(V, NoVecTy);
922   }
923
924   /// \brief Compute the integer shadow offset that corresponds to a given
925   /// application address.
926   ///
927   /// Offset = (Addr & ~AndMask) ^ XorMask
928   Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
929     uint64_t AndMask = MS.MapParams->AndMask;
930     assert(AndMask != 0 && "AndMask shall be specified");
931     Value *OffsetLong =
932       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
933                     ConstantInt::get(MS.IntptrTy, ~AndMask));
934
935     uint64_t XorMask = MS.MapParams->XorMask;
936     if (XorMask != 0)
937       OffsetLong = IRB.CreateXor(OffsetLong,
938                                  ConstantInt::get(MS.IntptrTy, XorMask));
939     return OffsetLong;
940   }
941
942   /// \brief Compute the shadow address that corresponds to a given application
943   /// address.
944   ///
945   /// Shadow = ShadowBase + Offset
946   Value *getShadowPtr(Value *Addr, Type *ShadowTy,
947                       IRBuilder<> &IRB) {
948     Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
949     uint64_t ShadowBase = MS.MapParams->ShadowBase;
950     if (ShadowBase != 0)
951       ShadowLong =
952         IRB.CreateAdd(ShadowLong,
953                       ConstantInt::get(MS.IntptrTy, ShadowBase));
954     return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
955   }
956
957   /// \brief Compute the origin address that corresponds to a given application
958   /// address.
959   ///
960   /// OriginAddr = (OriginBase + Offset) & ~3ULL
961   Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
962     Value *OriginLong = getShadowPtrOffset(Addr, IRB);
963     uint64_t OriginBase = MS.MapParams->OriginBase;
964     if (OriginBase != 0)
965       OriginLong =
966         IRB.CreateAdd(OriginLong,
967                       ConstantInt::get(MS.IntptrTy, OriginBase));
968     if (Alignment < kMinOriginAlignment) {
969       uint64_t Mask = kMinOriginAlignment - 1;
970       OriginLong = IRB.CreateAnd(OriginLong,
971                                  ConstantInt::get(MS.IntptrTy, ~Mask));
972     }
973     return IRB.CreateIntToPtr(OriginLong,
974                               PointerType::get(IRB.getInt32Ty(), 0));
975   }
976
977   /// \brief Compute the shadow address for a given function argument.
978   ///
979   /// Shadow = ParamTLS+ArgOffset.
980   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
981                                  int ArgOffset) {
982     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
983     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
984     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
985                               "_msarg");
986   }
987
988   /// \brief Compute the origin address for a given function argument.
989   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
990                                  int ArgOffset) {
991     if (!MS.TrackOrigins) return nullptr;
992     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
993     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
994     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
995                               "_msarg_o");
996   }
997
998   /// \brief Compute the shadow address for a retval.
999   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
1000     Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
1001     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
1002                               "_msret");
1003   }
1004
1005   /// \brief Compute the origin address for a retval.
1006   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
1007     // We keep a single origin for the entire retval. Might be too optimistic.
1008     return MS.RetvalOriginTLS;
1009   }
1010
1011   /// \brief Set SV to be the shadow value for V.
1012   void setShadow(Value *V, Value *SV) {
1013     assert(!ShadowMap.count(V) && "Values may only have one shadow");
1014     ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
1015   }
1016
1017   /// \brief Set Origin to be the origin value for V.
1018   void setOrigin(Value *V, Value *Origin) {
1019     if (!MS.TrackOrigins) return;
1020     assert(!OriginMap.count(V) && "Values may only have one origin");
1021     DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
1022     OriginMap[V] = Origin;
1023   }
1024
1025   /// \brief Create a clean shadow value for a given value.
1026   ///
1027   /// Clean shadow (all zeroes) means all bits of the value are defined
1028   /// (initialized).
1029   Constant *getCleanShadow(Value *V) {
1030     Type *ShadowTy = getShadowTy(V);
1031     if (!ShadowTy)
1032       return nullptr;
1033     return Constant::getNullValue(ShadowTy);
1034   }
1035
1036   /// \brief Create a dirty shadow of a given shadow type.
1037   Constant *getPoisonedShadow(Type *ShadowTy) {
1038     assert(ShadowTy);
1039     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
1040       return Constant::getAllOnesValue(ShadowTy);
1041     if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
1042       SmallVector<Constant *, 4> Vals(AT->getNumElements(),
1043                                       getPoisonedShadow(AT->getElementType()));
1044       return ConstantArray::get(AT, Vals);
1045     }
1046     if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
1047       SmallVector<Constant *, 4> Vals;
1048       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1049         Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1050       return ConstantStruct::get(ST, Vals);
1051     }
1052     llvm_unreachable("Unexpected shadow type");
1053   }
1054
1055   /// \brief Create a dirty shadow for a given value.
1056   Constant *getPoisonedShadow(Value *V) {
1057     Type *ShadowTy = getShadowTy(V);
1058     if (!ShadowTy)
1059       return nullptr;
1060     return getPoisonedShadow(ShadowTy);
1061   }
1062
1063   /// \brief Create a clean (zero) origin.
1064   Value *getCleanOrigin() {
1065     return Constant::getNullValue(MS.OriginTy);
1066   }
1067
1068   /// \brief Get the shadow value for a given Value.
1069   ///
1070   /// This function either returns the value set earlier with setShadow,
1071   /// or extracts if from ParamTLS (for function arguments).
1072   Value *getShadow(Value *V) {
1073     if (!PropagateShadow) return getCleanShadow(V);
1074     if (Instruction *I = dyn_cast<Instruction>(V)) {
1075       // For instructions the shadow is already stored in the map.
1076       Value *Shadow = ShadowMap[V];
1077       if (!Shadow) {
1078         DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
1079         (void)I;
1080         assert(Shadow && "No shadow for a value");
1081       }
1082       return Shadow;
1083     }
1084     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
1085       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
1086       DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
1087       (void)U;
1088       return AllOnes;
1089     }
1090     if (Argument *A = dyn_cast<Argument>(V)) {
1091       // For arguments we compute the shadow on demand and store it in the map.
1092       Value **ShadowPtr = &ShadowMap[V];
1093       if (*ShadowPtr)
1094         return *ShadowPtr;
1095       Function *F = A->getParent();
1096       IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
1097       unsigned ArgOffset = 0;
1098       const DataLayout &DL = F->getParent()->getDataLayout();
1099       for (auto &FArg : F->args()) {
1100         if (!FArg.getType()->isSized()) {
1101           DEBUG(dbgs() << "Arg is not sized\n");
1102           continue;
1103         }
1104         unsigned Size =
1105             FArg.hasByValAttr()
1106                 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
1107                 : DL.getTypeAllocSize(FArg.getType());
1108         if (A == &FArg) {
1109           bool Overflow = ArgOffset + Size > kParamTLSSize;
1110           Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1111           if (FArg.hasByValAttr()) {
1112             // ByVal pointer itself has clean shadow. We copy the actual
1113             // argument shadow to the underlying memory.
1114             // Figure out maximal valid memcpy alignment.
1115             unsigned ArgAlign = FArg.getParamAlignment();
1116             if (ArgAlign == 0) {
1117               Type *EltType = A->getType()->getPointerElementType();
1118               ArgAlign = DL.getABITypeAlignment(EltType);
1119             }
1120             if (Overflow) {
1121               // ParamTLS overflow.
1122               EntryIRB.CreateMemSet(
1123                   getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
1124                   Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
1125             } else {
1126               unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1127               Value *Cpy = EntryIRB.CreateMemCpy(
1128                   getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
1129                   CopyAlign);
1130               DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
1131               (void)Cpy;
1132             }
1133             *ShadowPtr = getCleanShadow(V);
1134           } else {
1135             if (Overflow) {
1136               // ParamTLS overflow.
1137               *ShadowPtr = getCleanShadow(V);
1138             } else {
1139               *ShadowPtr =
1140                   EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1141             }
1142           }
1143           DEBUG(dbgs() << "  ARG:    "  << FArg << " ==> " <<
1144                 **ShadowPtr << "\n");
1145           if (MS.TrackOrigins && !Overflow) {
1146             Value *OriginPtr =
1147                 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
1148             setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
1149           } else {
1150             setOrigin(A, getCleanOrigin());
1151           }
1152         }
1153         ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
1154       }
1155       assert(*ShadowPtr && "Could not find shadow for an argument");
1156       return *ShadowPtr;
1157     }
1158     // For everything else the shadow is zero.
1159     return getCleanShadow(V);
1160   }
1161
1162   /// \brief Get the shadow for i-th argument of the instruction I.
1163   Value *getShadow(Instruction *I, int i) {
1164     return getShadow(I->getOperand(i));
1165   }
1166
1167   /// \brief Get the origin for a value.
1168   Value *getOrigin(Value *V) {
1169     if (!MS.TrackOrigins) return nullptr;
1170     if (!PropagateShadow) return getCleanOrigin();
1171     if (isa<Constant>(V)) return getCleanOrigin();
1172     assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1173            "Unexpected value type in getOrigin()");
1174     Value *Origin = OriginMap[V];
1175     assert(Origin && "Missing origin");
1176     return Origin;
1177   }
1178
1179   /// \brief Get the origin for i-th argument of the instruction I.
1180   Value *getOrigin(Instruction *I, int i) {
1181     return getOrigin(I->getOperand(i));
1182   }
1183
1184   /// \brief Remember the place where a shadow check should be inserted.
1185   ///
1186   /// This location will be later instrumented with a check that will print a
1187   /// UMR warning in runtime if the shadow value is not 0.
1188   void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1189     assert(Shadow);
1190     if (!InsertChecks) return;
1191 #ifndef NDEBUG
1192     Type *ShadowTy = Shadow->getType();
1193     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1194            "Can only insert checks for integer and vector shadow types");
1195 #endif
1196     InstrumentationList.push_back(
1197         ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1198   }
1199
1200   /// \brief Remember the place where a shadow check should be inserted.
1201   ///
1202   /// This location will be later instrumented with a check that will print a
1203   /// UMR warning in runtime if the value is not fully defined.
1204   void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1205     assert(Val);
1206     Value *Shadow, *Origin;
1207     if (ClCheckConstantShadow) {
1208       Shadow = getShadow(Val);
1209       if (!Shadow) return;
1210       Origin = getOrigin(Val);
1211     } else {
1212       Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1213       if (!Shadow) return;
1214       Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1215     }
1216     insertShadowCheck(Shadow, Origin, OrigIns);
1217   }
1218
1219   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1220     switch (a) {
1221       case NotAtomic:
1222         return NotAtomic;
1223       case Unordered:
1224       case Monotonic:
1225       case Release:
1226         return Release;
1227       case Acquire:
1228       case AcquireRelease:
1229         return AcquireRelease;
1230       case SequentiallyConsistent:
1231         return SequentiallyConsistent;
1232     }
1233     llvm_unreachable("Unknown ordering");
1234   }
1235
1236   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1237     switch (a) {
1238       case NotAtomic:
1239         return NotAtomic;
1240       case Unordered:
1241       case Monotonic:
1242       case Acquire:
1243         return Acquire;
1244       case Release:
1245       case AcquireRelease:
1246         return AcquireRelease;
1247       case SequentiallyConsistent:
1248         return SequentiallyConsistent;
1249     }
1250     llvm_unreachable("Unknown ordering");
1251   }
1252
1253   // ------------------- Visitors.
1254
1255   /// \brief Instrument LoadInst
1256   ///
1257   /// Loads the corresponding shadow and (optionally) origin.
1258   /// Optionally, checks that the load address is fully defined.
1259   void visitLoadInst(LoadInst &I) {
1260     assert(I.getType()->isSized() && "Load type must have size");
1261     IRBuilder<> IRB(I.getNextNode());
1262     Type *ShadowTy = getShadowTy(&I);
1263     Value *Addr = I.getPointerOperand();
1264     if (PropagateShadow && !I.getMetadata("nosanitize")) {
1265       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1266       setShadow(&I,
1267                 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1268     } else {
1269       setShadow(&I, getCleanShadow(&I));
1270     }
1271
1272     if (ClCheckAccessAddress)
1273       insertShadowCheck(I.getPointerOperand(), &I);
1274
1275     if (I.isAtomic())
1276       I.setOrdering(addAcquireOrdering(I.getOrdering()));
1277
1278     if (MS.TrackOrigins) {
1279       if (PropagateShadow) {
1280         unsigned Alignment = I.getAlignment();
1281         unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1282         setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
1283                                             OriginAlignment));
1284       } else {
1285         setOrigin(&I, getCleanOrigin());
1286       }
1287     }
1288   }
1289
1290   /// \brief Instrument StoreInst
1291   ///
1292   /// Stores the corresponding shadow and (optionally) origin.
1293   /// Optionally, checks that the store address is fully defined.
1294   void visitStoreInst(StoreInst &I) {
1295     StoreList.push_back(&I);
1296   }
1297
1298   void handleCASOrRMW(Instruction &I) {
1299     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1300
1301     IRBuilder<> IRB(&I);
1302     Value *Addr = I.getOperand(0);
1303     Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1304
1305     if (ClCheckAccessAddress)
1306       insertShadowCheck(Addr, &I);
1307
1308     // Only test the conditional argument of cmpxchg instruction.
1309     // The other argument can potentially be uninitialized, but we can not
1310     // detect this situation reliably without possible false positives.
1311     if (isa<AtomicCmpXchgInst>(I))
1312       insertShadowCheck(I.getOperand(1), &I);
1313
1314     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1315
1316     setShadow(&I, getCleanShadow(&I));
1317     setOrigin(&I, getCleanOrigin());
1318   }
1319
1320   void visitAtomicRMWInst(AtomicRMWInst &I) {
1321     handleCASOrRMW(I);
1322     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1323   }
1324
1325   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1326     handleCASOrRMW(I);
1327     I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1328   }
1329
1330   // Vector manipulation.
1331   void visitExtractElementInst(ExtractElementInst &I) {
1332     insertShadowCheck(I.getOperand(1), &I);
1333     IRBuilder<> IRB(&I);
1334     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1335               "_msprop"));
1336     setOrigin(&I, getOrigin(&I, 0));
1337   }
1338
1339   void visitInsertElementInst(InsertElementInst &I) {
1340     insertShadowCheck(I.getOperand(2), &I);
1341     IRBuilder<> IRB(&I);
1342     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1343               I.getOperand(2), "_msprop"));
1344     setOriginForNaryOp(I);
1345   }
1346
1347   void visitShuffleVectorInst(ShuffleVectorInst &I) {
1348     insertShadowCheck(I.getOperand(2), &I);
1349     IRBuilder<> IRB(&I);
1350     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1351               I.getOperand(2), "_msprop"));
1352     setOriginForNaryOp(I);
1353   }
1354
1355   // Casts.
1356   void visitSExtInst(SExtInst &I) {
1357     IRBuilder<> IRB(&I);
1358     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1359     setOrigin(&I, getOrigin(&I, 0));
1360   }
1361
1362   void visitZExtInst(ZExtInst &I) {
1363     IRBuilder<> IRB(&I);
1364     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1365     setOrigin(&I, getOrigin(&I, 0));
1366   }
1367
1368   void visitTruncInst(TruncInst &I) {
1369     IRBuilder<> IRB(&I);
1370     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1371     setOrigin(&I, getOrigin(&I, 0));
1372   }
1373
1374   void visitBitCastInst(BitCastInst &I) {
1375     // Special case: if this is the bitcast (there is exactly 1 allowed) between
1376     // a musttail call and a ret, don't instrument. New instructions are not
1377     // allowed after a musttail call.
1378     if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
1379       if (CI->isMustTailCall())
1380         return;
1381     IRBuilder<> IRB(&I);
1382     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1383     setOrigin(&I, getOrigin(&I, 0));
1384   }
1385
1386   void visitPtrToIntInst(PtrToIntInst &I) {
1387     IRBuilder<> IRB(&I);
1388     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1389              "_msprop_ptrtoint"));
1390     setOrigin(&I, getOrigin(&I, 0));
1391   }
1392
1393   void visitIntToPtrInst(IntToPtrInst &I) {
1394     IRBuilder<> IRB(&I);
1395     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1396              "_msprop_inttoptr"));
1397     setOrigin(&I, getOrigin(&I, 0));
1398   }
1399
1400   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1401   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1402   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1403   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1404   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1405   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1406
1407   /// \brief Propagate shadow for bitwise AND.
1408   ///
1409   /// This code is exact, i.e. if, for example, a bit in the left argument
1410   /// is defined and 0, then neither the value not definedness of the
1411   /// corresponding bit in B don't affect the resulting shadow.
1412   void visitAnd(BinaryOperator &I) {
1413     IRBuilder<> IRB(&I);
1414     //  "And" of 0 and a poisoned value results in unpoisoned value.
1415     //  1&1 => 1;     0&1 => 0;     p&1 => p;
1416     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
1417     //  1&p => p;     0&p => 0;     p&p => p;
1418     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1419     Value *S1 = getShadow(&I, 0);
1420     Value *S2 = getShadow(&I, 1);
1421     Value *V1 = I.getOperand(0);
1422     Value *V2 = I.getOperand(1);
1423     if (V1->getType() != S1->getType()) {
1424       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1425       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1426     }
1427     Value *S1S2 = IRB.CreateAnd(S1, S2);
1428     Value *V1S2 = IRB.CreateAnd(V1, S2);
1429     Value *S1V2 = IRB.CreateAnd(S1, V2);
1430     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1431     setOriginForNaryOp(I);
1432   }
1433
1434   void visitOr(BinaryOperator &I) {
1435     IRBuilder<> IRB(&I);
1436     //  "Or" of 1 and a poisoned value results in unpoisoned value.
1437     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
1438     //  1|0 => 1;     0|0 => 0;     p|0 => p;
1439     //  1|p => 1;     0|p => p;     p|p => p;
1440     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1441     Value *S1 = getShadow(&I, 0);
1442     Value *S2 = getShadow(&I, 1);
1443     Value *V1 = IRB.CreateNot(I.getOperand(0));
1444     Value *V2 = IRB.CreateNot(I.getOperand(1));
1445     if (V1->getType() != S1->getType()) {
1446       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1447       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1448     }
1449     Value *S1S2 = IRB.CreateAnd(S1, S2);
1450     Value *V1S2 = IRB.CreateAnd(V1, S2);
1451     Value *S1V2 = IRB.CreateAnd(S1, V2);
1452     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1453     setOriginForNaryOp(I);
1454   }
1455
1456   /// \brief Default propagation of shadow and/or origin.
1457   ///
1458   /// This class implements the general case of shadow propagation, used in all
1459   /// cases where we don't know and/or don't care about what the operation
1460   /// actually does. It converts all input shadow values to a common type
1461   /// (extending or truncating as necessary), and bitwise OR's them.
1462   ///
1463   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1464   /// fully initialized), and less prone to false positives.
1465   ///
1466   /// This class also implements the general case of origin propagation. For a
1467   /// Nary operation, result origin is set to the origin of an argument that is
1468   /// not entirely initialized. If there is more than one such arguments, the
1469   /// rightmost of them is picked. It does not matter which one is picked if all
1470   /// arguments are initialized.
1471   template <bool CombineShadow>
1472   class Combiner {
1473     Value *Shadow;
1474     Value *Origin;
1475     IRBuilder<> &IRB;
1476     MemorySanitizerVisitor *MSV;
1477
1478   public:
1479     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1480       Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
1481
1482     /// \brief Add a pair of shadow and origin values to the mix.
1483     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1484       if (CombineShadow) {
1485         assert(OpShadow);
1486         if (!Shadow)
1487           Shadow = OpShadow;
1488         else {
1489           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1490           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1491         }
1492       }
1493
1494       if (MSV->MS.TrackOrigins) {
1495         assert(OpOrigin);
1496         if (!Origin) {
1497           Origin = OpOrigin;
1498         } else {
1499           Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1500           // No point in adding something that might result in 0 origin value.
1501           if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1502             Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1503             Value *Cond =
1504                 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1505             Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1506           }
1507         }
1508       }
1509       return *this;
1510     }
1511
1512     /// \brief Add an application value to the mix.
1513     Combiner &Add(Value *V) {
1514       Value *OpShadow = MSV->getShadow(V);
1515       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
1516       return Add(OpShadow, OpOrigin);
1517     }
1518
1519     /// \brief Set the current combined values as the given instruction's shadow
1520     /// and origin.
1521     void Done(Instruction *I) {
1522       if (CombineShadow) {
1523         assert(Shadow);
1524         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1525         MSV->setShadow(I, Shadow);
1526       }
1527       if (MSV->MS.TrackOrigins) {
1528         assert(Origin);
1529         MSV->setOrigin(I, Origin);
1530       }
1531     }
1532   };
1533
1534   typedef Combiner<true> ShadowAndOriginCombiner;
1535   typedef Combiner<false> OriginCombiner;
1536
1537   /// \brief Propagate origin for arbitrary operation.
1538   void setOriginForNaryOp(Instruction &I) {
1539     if (!MS.TrackOrigins) return;
1540     IRBuilder<> IRB(&I);
1541     OriginCombiner OC(this, IRB);
1542     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1543       OC.Add(OI->get());
1544     OC.Done(&I);
1545   }
1546
1547   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1548     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1549            "Vector of pointers is not a valid shadow type");
1550     return Ty->isVectorTy() ?
1551       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1552       Ty->getPrimitiveSizeInBits();
1553   }
1554
1555   /// \brief Cast between two shadow types, extending or truncating as
1556   /// necessary.
1557   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1558                           bool Signed = false) {
1559     Type *srcTy = V->getType();
1560     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1561       return IRB.CreateIntCast(V, dstTy, Signed);
1562     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1563         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1564       return IRB.CreateIntCast(V, dstTy, Signed);
1565     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1566     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1567     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1568     Value *V2 =
1569       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1570     return IRB.CreateBitCast(V2, dstTy);
1571     // TODO: handle struct types.
1572   }
1573
1574   /// \brief Cast an application value to the type of its own shadow.
1575   Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1576     Type *ShadowTy = getShadowTy(V);
1577     if (V->getType() == ShadowTy)
1578       return V;
1579     if (V->getType()->isPtrOrPtrVectorTy())
1580       return IRB.CreatePtrToInt(V, ShadowTy);
1581     else
1582       return IRB.CreateBitCast(V, ShadowTy);
1583   }
1584
1585   /// \brief Propagate shadow for arbitrary operation.
1586   void handleShadowOr(Instruction &I) {
1587     IRBuilder<> IRB(&I);
1588     ShadowAndOriginCombiner SC(this, IRB);
1589     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1590       SC.Add(OI->get());
1591     SC.Done(&I);
1592   }
1593
1594   // \brief Handle multiplication by constant.
1595   //
1596   // Handle a special case of multiplication by constant that may have one or
1597   // more zeros in the lower bits. This makes corresponding number of lower bits
1598   // of the result zero as well. We model it by shifting the other operand
1599   // shadow left by the required number of bits. Effectively, we transform
1600   // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1601   // We use multiplication by 2**N instead of shift to cover the case of
1602   // multiplication by 0, which may occur in some elements of a vector operand.
1603   void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1604                            Value *OtherArg) {
1605     Constant *ShadowMul;
1606     Type *Ty = ConstArg->getType();
1607     if (Ty->isVectorTy()) {
1608       unsigned NumElements = Ty->getVectorNumElements();
1609       Type *EltTy = Ty->getSequentialElementType();
1610       SmallVector<Constant *, 16> Elements;
1611       for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1612         ConstantInt *Elt =
1613             dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1614         APInt V = Elt->getValue();
1615         APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1616         Elements.push_back(ConstantInt::get(EltTy, V2));
1617       }
1618       ShadowMul = ConstantVector::get(Elements);
1619     } else {
1620       ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1621       APInt V = Elt->getValue();
1622       APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1623       ShadowMul = ConstantInt::get(Elt->getType(), V2);
1624     }
1625
1626     IRBuilder<> IRB(&I);
1627     setShadow(&I,
1628               IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1629     setOrigin(&I, getOrigin(OtherArg));
1630   }
1631
1632   void visitMul(BinaryOperator &I) {
1633     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1634     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1635     if (constOp0 && !constOp1)
1636       handleMulByConstant(I, constOp0, I.getOperand(1));
1637     else if (constOp1 && !constOp0)
1638       handleMulByConstant(I, constOp1, I.getOperand(0));
1639     else
1640       handleShadowOr(I);
1641   }
1642
1643   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1644   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1645   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1646   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1647   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1648   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1649
1650   void handleDiv(Instruction &I) {
1651     IRBuilder<> IRB(&I);
1652     // Strict on the second argument.
1653     insertShadowCheck(I.getOperand(1), &I);
1654     setShadow(&I, getShadow(&I, 0));
1655     setOrigin(&I, getOrigin(&I, 0));
1656   }
1657
1658   void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1659   void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1660   void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1661   void visitURem(BinaryOperator &I) { handleDiv(I); }
1662   void visitSRem(BinaryOperator &I) { handleDiv(I); }
1663   void visitFRem(BinaryOperator &I) { handleDiv(I); }
1664
1665   /// \brief Instrument == and != comparisons.
1666   ///
1667   /// Sometimes the comparison result is known even if some of the bits of the
1668   /// arguments are not.
1669   void handleEqualityComparison(ICmpInst &I) {
1670     IRBuilder<> IRB(&I);
1671     Value *A = I.getOperand(0);
1672     Value *B = I.getOperand(1);
1673     Value *Sa = getShadow(A);
1674     Value *Sb = getShadow(B);
1675
1676     // Get rid of pointers and vectors of pointers.
1677     // For ints (and vectors of ints), types of A and Sa match,
1678     // and this is a no-op.
1679     A = IRB.CreatePointerCast(A, Sa->getType());
1680     B = IRB.CreatePointerCast(B, Sb->getType());
1681
1682     // A == B  <==>  (C = A^B) == 0
1683     // A != B  <==>  (C = A^B) != 0
1684     // Sc = Sa | Sb
1685     Value *C = IRB.CreateXor(A, B);
1686     Value *Sc = IRB.CreateOr(Sa, Sb);
1687     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1688     // Result is defined if one of the following is true
1689     // * there is a defined 1 bit in C
1690     // * C is fully defined
1691     // Si = !(C & ~Sc) && Sc
1692     Value *Zero = Constant::getNullValue(Sc->getType());
1693     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1694     Value *Si =
1695       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1696                     IRB.CreateICmpEQ(
1697                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1698     Si->setName("_msprop_icmp");
1699     setShadow(&I, Si);
1700     setOriginForNaryOp(I);
1701   }
1702
1703   /// \brief Build the lowest possible value of V, taking into account V's
1704   ///        uninitialized bits.
1705   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1706                                 bool isSigned) {
1707     if (isSigned) {
1708       // Split shadow into sign bit and other bits.
1709       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1710       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1711       // Maximise the undefined shadow bit, minimize other undefined bits.
1712       return
1713         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1714     } else {
1715       // Minimize undefined bits.
1716       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1717     }
1718   }
1719
1720   /// \brief Build the highest possible value of V, taking into account V's
1721   ///        uninitialized bits.
1722   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1723                                 bool isSigned) {
1724     if (isSigned) {
1725       // Split shadow into sign bit and other bits.
1726       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1727       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1728       // Minimise the undefined shadow bit, maximise other undefined bits.
1729       return
1730         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1731     } else {
1732       // Maximize undefined bits.
1733       return IRB.CreateOr(A, Sa);
1734     }
1735   }
1736
1737   /// \brief Instrument relational comparisons.
1738   ///
1739   /// This function does exact shadow propagation for all relational
1740   /// comparisons of integers, pointers and vectors of those.
1741   /// FIXME: output seems suboptimal when one of the operands is a constant
1742   void handleRelationalComparisonExact(ICmpInst &I) {
1743     IRBuilder<> IRB(&I);
1744     Value *A = I.getOperand(0);
1745     Value *B = I.getOperand(1);
1746     Value *Sa = getShadow(A);
1747     Value *Sb = getShadow(B);
1748
1749     // Get rid of pointers and vectors of pointers.
1750     // For ints (and vectors of ints), types of A and Sa match,
1751     // and this is a no-op.
1752     A = IRB.CreatePointerCast(A, Sa->getType());
1753     B = IRB.CreatePointerCast(B, Sb->getType());
1754
1755     // Let [a0, a1] be the interval of possible values of A, taking into account
1756     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1757     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1758     bool IsSigned = I.isSigned();
1759     Value *S1 = IRB.CreateICmp(I.getPredicate(),
1760                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
1761                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
1762     Value *S2 = IRB.CreateICmp(I.getPredicate(),
1763                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
1764                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
1765     Value *Si = IRB.CreateXor(S1, S2);
1766     setShadow(&I, Si);
1767     setOriginForNaryOp(I);
1768   }
1769
1770   /// \brief Instrument signed relational comparisons.
1771   ///
1772   /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest
1773   /// bit of the shadow. Everything else is delegated to handleShadowOr().
1774   void handleSignedRelationalComparison(ICmpInst &I) {
1775     Constant *constOp;
1776     Value *op = nullptr;
1777     CmpInst::Predicate pre;
1778     if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) {
1779       op = I.getOperand(0);
1780       pre = I.getPredicate();
1781     } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) {
1782       op = I.getOperand(1);
1783       pre = I.getSwappedPredicate();
1784     } else {
1785       handleShadowOr(I);
1786       return;
1787     }
1788
1789     if ((constOp->isNullValue() &&
1790          (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) ||
1791         (constOp->isAllOnesValue() &&
1792          (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) {
1793       IRBuilder<> IRB(&I);
1794       Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op),
1795                                         "_msprop_icmp_s");
1796       setShadow(&I, Shadow);
1797       setOrigin(&I, getOrigin(op));
1798     } else {
1799       handleShadowOr(I);
1800     }
1801   }
1802
1803   void visitICmpInst(ICmpInst &I) {
1804     if (!ClHandleICmp) {
1805       handleShadowOr(I);
1806       return;
1807     }
1808     if (I.isEquality()) {
1809       handleEqualityComparison(I);
1810       return;
1811     }
1812
1813     assert(I.isRelational());
1814     if (ClHandleICmpExact) {
1815       handleRelationalComparisonExact(I);
1816       return;
1817     }
1818     if (I.isSigned()) {
1819       handleSignedRelationalComparison(I);
1820       return;
1821     }
1822
1823     assert(I.isUnsigned());
1824     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1825       handleRelationalComparisonExact(I);
1826       return;
1827     }
1828
1829     handleShadowOr(I);
1830   }
1831
1832   void visitFCmpInst(FCmpInst &I) {
1833     handleShadowOr(I);
1834   }
1835
1836   void handleShift(BinaryOperator &I) {
1837     IRBuilder<> IRB(&I);
1838     // If any of the S2 bits are poisoned, the whole thing is poisoned.
1839     // Otherwise perform the same shift on S1.
1840     Value *S1 = getShadow(&I, 0);
1841     Value *S2 = getShadow(&I, 1);
1842     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1843                                    S2->getType());
1844     Value *V2 = I.getOperand(1);
1845     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1846     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1847     setOriginForNaryOp(I);
1848   }
1849
1850   void visitShl(BinaryOperator &I) { handleShift(I); }
1851   void visitAShr(BinaryOperator &I) { handleShift(I); }
1852   void visitLShr(BinaryOperator &I) { handleShift(I); }
1853
1854   /// \brief Instrument llvm.memmove
1855   ///
1856   /// At this point we don't know if llvm.memmove will be inlined or not.
1857   /// If we don't instrument it and it gets inlined,
1858   /// our interceptor will not kick in and we will lose the memmove.
1859   /// If we instrument the call here, but it does not get inlined,
1860   /// we will memove the shadow twice: which is bad in case
1861   /// of overlapping regions. So, we simply lower the intrinsic to a call.
1862   ///
1863   /// Similar situation exists for memcpy and memset.
1864   void visitMemMoveInst(MemMoveInst &I) {
1865     IRBuilder<> IRB(&I);
1866     IRB.CreateCall(
1867         MS.MemmoveFn,
1868         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1869          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1870          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1871     I.eraseFromParent();
1872   }
1873
1874   // Similar to memmove: avoid copying shadow twice.
1875   // This is somewhat unfortunate as it may slowdown small constant memcpys.
1876   // FIXME: consider doing manual inline for small constant sizes and proper
1877   // alignment.
1878   void visitMemCpyInst(MemCpyInst &I) {
1879     IRBuilder<> IRB(&I);
1880     IRB.CreateCall(
1881         MS.MemcpyFn,
1882         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1883          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1884          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1885     I.eraseFromParent();
1886   }
1887
1888   // Same as memcpy.
1889   void visitMemSetInst(MemSetInst &I) {
1890     IRBuilder<> IRB(&I);
1891     IRB.CreateCall(
1892         MS.MemsetFn,
1893         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1894          IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1895          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1896     I.eraseFromParent();
1897   }
1898
1899   void visitVAStartInst(VAStartInst &I) {
1900     VAHelper->visitVAStartInst(I);
1901   }
1902
1903   void visitVACopyInst(VACopyInst &I) {
1904     VAHelper->visitVACopyInst(I);
1905   }
1906
1907   enum IntrinsicKind {
1908     IK_DoesNotAccessMemory,
1909     IK_OnlyReadsMemory,
1910     IK_WritesMemory
1911   };
1912
1913   static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1914     const int FMRB_DoesNotAccessMemory = IK_DoesNotAccessMemory;
1915     const int FMRB_OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1916     const int FMRB_OnlyReadsMemory = IK_OnlyReadsMemory;
1917     const int FMRB_OnlyAccessesArgumentPointees = IK_WritesMemory;
1918     const int FMRB_UnknownModRefBehavior = IK_WritesMemory;
1919 #define GET_INTRINSIC_MODREF_BEHAVIOR
1920 #define FunctionModRefBehavior IntrinsicKind
1921 #include "llvm/IR/Intrinsics.gen"
1922 #undef FunctionModRefBehavior
1923 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1924   }
1925
1926   /// \brief Handle vector store-like intrinsics.
1927   ///
1928   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1929   /// has 1 pointer argument and 1 vector argument, returns void.
1930   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1931     IRBuilder<> IRB(&I);
1932     Value* Addr = I.getArgOperand(0);
1933     Value *Shadow = getShadow(&I, 1);
1934     Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1935
1936     // We don't know the pointer alignment (could be unaligned SSE store!).
1937     // Have to assume to worst case.
1938     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1939
1940     if (ClCheckAccessAddress)
1941       insertShadowCheck(Addr, &I);
1942
1943     // FIXME: use ClStoreCleanOrigin
1944     // FIXME: factor out common code from materializeStores
1945     if (MS.TrackOrigins)
1946       IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
1947     return true;
1948   }
1949
1950   /// \brief Handle vector load-like intrinsics.
1951   ///
1952   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1953   /// has 1 pointer argument, returns a vector.
1954   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1955     IRBuilder<> IRB(&I);
1956     Value *Addr = I.getArgOperand(0);
1957
1958     Type *ShadowTy = getShadowTy(&I);
1959     if (PropagateShadow) {
1960       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1961       // We don't know the pointer alignment (could be unaligned SSE load!).
1962       // Have to assume to worst case.
1963       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1964     } else {
1965       setShadow(&I, getCleanShadow(&I));
1966     }
1967
1968     if (ClCheckAccessAddress)
1969       insertShadowCheck(Addr, &I);
1970
1971     if (MS.TrackOrigins) {
1972       if (PropagateShadow)
1973         setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
1974       else
1975         setOrigin(&I, getCleanOrigin());
1976     }
1977     return true;
1978   }
1979
1980   /// \brief Handle (SIMD arithmetic)-like intrinsics.
1981   ///
1982   /// Instrument intrinsics with any number of arguments of the same type,
1983   /// equal to the return type. The type should be simple (no aggregates or
1984   /// pointers; vectors are fine).
1985   /// Caller guarantees that this intrinsic does not access memory.
1986   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1987     Type *RetTy = I.getType();
1988     if (!(RetTy->isIntOrIntVectorTy() ||
1989           RetTy->isFPOrFPVectorTy() ||
1990           RetTy->isX86_MMXTy()))
1991       return false;
1992
1993     unsigned NumArgOperands = I.getNumArgOperands();
1994
1995     for (unsigned i = 0; i < NumArgOperands; ++i) {
1996       Type *Ty = I.getArgOperand(i)->getType();
1997       if (Ty != RetTy)
1998         return false;
1999     }
2000
2001     IRBuilder<> IRB(&I);
2002     ShadowAndOriginCombiner SC(this, IRB);
2003     for (unsigned i = 0; i < NumArgOperands; ++i)
2004       SC.Add(I.getArgOperand(i));
2005     SC.Done(&I);
2006
2007     return true;
2008   }
2009
2010   /// \brief Heuristically instrument unknown intrinsics.
2011   ///
2012   /// The main purpose of this code is to do something reasonable with all
2013   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
2014   /// We recognize several classes of intrinsics by their argument types and
2015   /// ModRefBehaviour and apply special intrumentation when we are reasonably
2016   /// sure that we know what the intrinsic does.
2017   ///
2018   /// We special-case intrinsics where this approach fails. See llvm.bswap
2019   /// handling as an example of that.
2020   bool handleUnknownIntrinsic(IntrinsicInst &I) {
2021     unsigned NumArgOperands = I.getNumArgOperands();
2022     if (NumArgOperands == 0)
2023       return false;
2024
2025     Intrinsic::ID iid = I.getIntrinsicID();
2026     IntrinsicKind IK = getIntrinsicKind(iid);
2027     bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
2028     bool WritesMemory = IK == IK_WritesMemory;
2029     assert(!(OnlyReadsMemory && WritesMemory));
2030
2031     if (NumArgOperands == 2 &&
2032         I.getArgOperand(0)->getType()->isPointerTy() &&
2033         I.getArgOperand(1)->getType()->isVectorTy() &&
2034         I.getType()->isVoidTy() &&
2035         WritesMemory) {
2036       // This looks like a vector store.
2037       return handleVectorStoreIntrinsic(I);
2038     }
2039
2040     if (NumArgOperands == 1 &&
2041         I.getArgOperand(0)->getType()->isPointerTy() &&
2042         I.getType()->isVectorTy() &&
2043         OnlyReadsMemory) {
2044       // This looks like a vector load.
2045       return handleVectorLoadIntrinsic(I);
2046     }
2047
2048     if (!OnlyReadsMemory && !WritesMemory)
2049       if (maybeHandleSimpleNomemIntrinsic(I))
2050         return true;
2051
2052     // FIXME: detect and handle SSE maskstore/maskload
2053     return false;
2054   }
2055
2056   void handleBswap(IntrinsicInst &I) {
2057     IRBuilder<> IRB(&I);
2058     Value *Op = I.getArgOperand(0);
2059     Type *OpType = Op->getType();
2060     Function *BswapFunc = Intrinsic::getDeclaration(
2061       F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
2062     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2063     setOrigin(&I, getOrigin(Op));
2064   }
2065
2066   // \brief Instrument vector convert instrinsic.
2067   //
2068   // This function instruments intrinsics like cvtsi2ss:
2069   // %Out = int_xxx_cvtyyy(%ConvertOp)
2070   // or
2071   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2072   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2073   // number \p Out elements, and (if has 2 arguments) copies the rest of the
2074   // elements from \p CopyOp.
2075   // In most cases conversion involves floating-point value which may trigger a
2076   // hardware exception when not fully initialized. For this reason we require
2077   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2078   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2079   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2080   // return a fully initialized value.
2081   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2082     IRBuilder<> IRB(&I);
2083     Value *CopyOp, *ConvertOp;
2084
2085     switch (I.getNumArgOperands()) {
2086     case 3:
2087       assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
2088     case 2:
2089       CopyOp = I.getArgOperand(0);
2090       ConvertOp = I.getArgOperand(1);
2091       break;
2092     case 1:
2093       ConvertOp = I.getArgOperand(0);
2094       CopyOp = nullptr;
2095       break;
2096     default:
2097       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2098     }
2099
2100     // The first *NumUsedElements* elements of ConvertOp are converted to the
2101     // same number of output elements. The rest of the output is copied from
2102     // CopyOp, or (if not available) filled with zeroes.
2103     // Combine shadow for elements of ConvertOp that are used in this operation,
2104     // and insert a check.
2105     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2106     // int->any conversion.
2107     Value *ConvertShadow = getShadow(ConvertOp);
2108     Value *AggShadow = nullptr;
2109     if (ConvertOp->getType()->isVectorTy()) {
2110       AggShadow = IRB.CreateExtractElement(
2111           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2112       for (int i = 1; i < NumUsedElements; ++i) {
2113         Value *MoreShadow = IRB.CreateExtractElement(
2114             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2115         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2116       }
2117     } else {
2118       AggShadow = ConvertShadow;
2119     }
2120     assert(AggShadow->getType()->isIntegerTy());
2121     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2122
2123     // Build result shadow by zero-filling parts of CopyOp shadow that come from
2124     // ConvertOp.
2125     if (CopyOp) {
2126       assert(CopyOp->getType() == I.getType());
2127       assert(CopyOp->getType()->isVectorTy());
2128       Value *ResultShadow = getShadow(CopyOp);
2129       Type *EltTy = ResultShadow->getType()->getVectorElementType();
2130       for (int i = 0; i < NumUsedElements; ++i) {
2131         ResultShadow = IRB.CreateInsertElement(
2132             ResultShadow, ConstantInt::getNullValue(EltTy),
2133             ConstantInt::get(IRB.getInt32Ty(), i));
2134       }
2135       setShadow(&I, ResultShadow);
2136       setOrigin(&I, getOrigin(CopyOp));
2137     } else {
2138       setShadow(&I, getCleanShadow(&I));
2139       setOrigin(&I, getCleanOrigin());
2140     }
2141   }
2142
2143   // Given a scalar or vector, extract lower 64 bits (or less), and return all
2144   // zeroes if it is zero, and all ones otherwise.
2145   Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2146     if (S->getType()->isVectorTy())
2147       S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2148     assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2149     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2150     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2151   }
2152
2153   Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2154     Type *T = S->getType();
2155     assert(T->isVectorTy());
2156     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2157     return IRB.CreateSExt(S2, T);
2158   }
2159
2160   // \brief Instrument vector shift instrinsic.
2161   //
2162   // This function instruments intrinsics like int_x86_avx2_psll_w.
2163   // Intrinsic shifts %In by %ShiftSize bits.
2164   // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2165   // size, and the rest is ignored. Behavior is defined even if shift size is
2166   // greater than register (or field) width.
2167   void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2168     assert(I.getNumArgOperands() == 2);
2169     IRBuilder<> IRB(&I);
2170     // If any of the S2 bits are poisoned, the whole thing is poisoned.
2171     // Otherwise perform the same shift on S1.
2172     Value *S1 = getShadow(&I, 0);
2173     Value *S2 = getShadow(&I, 1);
2174     Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2175                              : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2176     Value *V1 = I.getOperand(0);
2177     Value *V2 = I.getOperand(1);
2178     Value *Shift = IRB.CreateCall(I.getCalledValue(),
2179                                   {IRB.CreateBitCast(S1, V1->getType()), V2});
2180     Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2181     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2182     setOriginForNaryOp(I);
2183   }
2184
2185   // \brief Get an X86_MMX-sized vector type.
2186   Type *getMMXVectorTy(unsigned EltSizeInBits) {
2187     const unsigned X86_MMXSizeInBits = 64;
2188     return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2189                            X86_MMXSizeInBits / EltSizeInBits);
2190   }
2191
2192   // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2193   // intrinsic.
2194   Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2195     switch (id) {
2196       case llvm::Intrinsic::x86_sse2_packsswb_128:
2197       case llvm::Intrinsic::x86_sse2_packuswb_128:
2198         return llvm::Intrinsic::x86_sse2_packsswb_128;
2199
2200       case llvm::Intrinsic::x86_sse2_packssdw_128:
2201       case llvm::Intrinsic::x86_sse41_packusdw:
2202         return llvm::Intrinsic::x86_sse2_packssdw_128;
2203
2204       case llvm::Intrinsic::x86_avx2_packsswb:
2205       case llvm::Intrinsic::x86_avx2_packuswb:
2206         return llvm::Intrinsic::x86_avx2_packsswb;
2207
2208       case llvm::Intrinsic::x86_avx2_packssdw:
2209       case llvm::Intrinsic::x86_avx2_packusdw:
2210         return llvm::Intrinsic::x86_avx2_packssdw;
2211
2212       case llvm::Intrinsic::x86_mmx_packsswb:
2213       case llvm::Intrinsic::x86_mmx_packuswb:
2214         return llvm::Intrinsic::x86_mmx_packsswb;
2215
2216       case llvm::Intrinsic::x86_mmx_packssdw:
2217         return llvm::Intrinsic::x86_mmx_packssdw;
2218       default:
2219         llvm_unreachable("unexpected intrinsic id");
2220     }
2221   }
2222
2223   // \brief Instrument vector pack instrinsic.
2224   //
2225   // This function instruments intrinsics like x86_mmx_packsswb, that
2226   // packs elements of 2 input vectors into half as many bits with saturation.
2227   // Shadow is propagated with the signed variant of the same intrinsic applied
2228   // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2229   // EltSizeInBits is used only for x86mmx arguments.
2230   void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
2231     assert(I.getNumArgOperands() == 2);
2232     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2233     IRBuilder<> IRB(&I);
2234     Value *S1 = getShadow(&I, 0);
2235     Value *S2 = getShadow(&I, 1);
2236     assert(isX86_MMX || S1->getType()->isVectorTy());
2237
2238     // SExt and ICmpNE below must apply to individual elements of input vectors.
2239     // In case of x86mmx arguments, cast them to appropriate vector types and
2240     // back.
2241     Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2242     if (isX86_MMX) {
2243       S1 = IRB.CreateBitCast(S1, T);
2244       S2 = IRB.CreateBitCast(S2, T);
2245     }
2246     Value *S1_ext = IRB.CreateSExt(
2247         IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2248     Value *S2_ext = IRB.CreateSExt(
2249         IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
2250     if (isX86_MMX) {
2251       Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2252       S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2253       S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2254     }
2255
2256     Function *ShadowFn = Intrinsic::getDeclaration(
2257         F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2258
2259     Value *S =
2260         IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
2261     if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2262     setShadow(&I, S);
2263     setOriginForNaryOp(I);
2264   }
2265
2266   // \brief Instrument sum-of-absolute-differencies intrinsic.
2267   void handleVectorSadIntrinsic(IntrinsicInst &I) {
2268     const unsigned SignificantBitsPerResultElement = 16;
2269     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2270     Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2271     unsigned ZeroBitsPerResultElement =
2272         ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2273
2274     IRBuilder<> IRB(&I);
2275     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2276     S = IRB.CreateBitCast(S, ResTy);
2277     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2278                        ResTy);
2279     S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2280     S = IRB.CreateBitCast(S, getShadowTy(&I));
2281     setShadow(&I, S);
2282     setOriginForNaryOp(I);
2283   }
2284
2285   // \brief Instrument multiply-add intrinsic.
2286   void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2287                                   unsigned EltSizeInBits = 0) {
2288     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2289     Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2290     IRBuilder<> IRB(&I);
2291     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2292     S = IRB.CreateBitCast(S, ResTy);
2293     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2294                        ResTy);
2295     S = IRB.CreateBitCast(S, getShadowTy(&I));
2296     setShadow(&I, S);
2297     setOriginForNaryOp(I);
2298   }
2299
2300   void visitIntrinsicInst(IntrinsicInst &I) {
2301     switch (I.getIntrinsicID()) {
2302     case llvm::Intrinsic::bswap:
2303       handleBswap(I);
2304       break;
2305     case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2306     case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2307     case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2308     case llvm::Intrinsic::x86_avx512_cvtss2usi:
2309     case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2310     case llvm::Intrinsic::x86_avx512_cvttss2usi:
2311     case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2312     case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2313     case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2314     case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2315     case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2316     case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2317     case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2318     case llvm::Intrinsic::x86_sse2_cvtsd2si:
2319     case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2320     case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2321     case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2322     case llvm::Intrinsic::x86_sse2_cvtss2sd:
2323     case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2324     case llvm::Intrinsic::x86_sse2_cvttsd2si:
2325     case llvm::Intrinsic::x86_sse_cvtsi2ss:
2326     case llvm::Intrinsic::x86_sse_cvtsi642ss:
2327     case llvm::Intrinsic::x86_sse_cvtss2si64:
2328     case llvm::Intrinsic::x86_sse_cvtss2si:
2329     case llvm::Intrinsic::x86_sse_cvttss2si64:
2330     case llvm::Intrinsic::x86_sse_cvttss2si:
2331       handleVectorConvertIntrinsic(I, 1);
2332       break;
2333     case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2334     case llvm::Intrinsic::x86_sse2_cvtps2pd:
2335     case llvm::Intrinsic::x86_sse_cvtps2pi:
2336     case llvm::Intrinsic::x86_sse_cvttps2pi:
2337       handleVectorConvertIntrinsic(I, 2);
2338       break;
2339     case llvm::Intrinsic::x86_avx2_psll_w:
2340     case llvm::Intrinsic::x86_avx2_psll_d:
2341     case llvm::Intrinsic::x86_avx2_psll_q:
2342     case llvm::Intrinsic::x86_avx2_pslli_w:
2343     case llvm::Intrinsic::x86_avx2_pslli_d:
2344     case llvm::Intrinsic::x86_avx2_pslli_q:
2345     case llvm::Intrinsic::x86_avx2_psrl_w:
2346     case llvm::Intrinsic::x86_avx2_psrl_d:
2347     case llvm::Intrinsic::x86_avx2_psrl_q:
2348     case llvm::Intrinsic::x86_avx2_psra_w:
2349     case llvm::Intrinsic::x86_avx2_psra_d:
2350     case llvm::Intrinsic::x86_avx2_psrli_w:
2351     case llvm::Intrinsic::x86_avx2_psrli_d:
2352     case llvm::Intrinsic::x86_avx2_psrli_q:
2353     case llvm::Intrinsic::x86_avx2_psrai_w:
2354     case llvm::Intrinsic::x86_avx2_psrai_d:
2355     case llvm::Intrinsic::x86_sse2_psll_w:
2356     case llvm::Intrinsic::x86_sse2_psll_d:
2357     case llvm::Intrinsic::x86_sse2_psll_q:
2358     case llvm::Intrinsic::x86_sse2_pslli_w:
2359     case llvm::Intrinsic::x86_sse2_pslli_d:
2360     case llvm::Intrinsic::x86_sse2_pslli_q:
2361     case llvm::Intrinsic::x86_sse2_psrl_w:
2362     case llvm::Intrinsic::x86_sse2_psrl_d:
2363     case llvm::Intrinsic::x86_sse2_psrl_q:
2364     case llvm::Intrinsic::x86_sse2_psra_w:
2365     case llvm::Intrinsic::x86_sse2_psra_d:
2366     case llvm::Intrinsic::x86_sse2_psrli_w:
2367     case llvm::Intrinsic::x86_sse2_psrli_d:
2368     case llvm::Intrinsic::x86_sse2_psrli_q:
2369     case llvm::Intrinsic::x86_sse2_psrai_w:
2370     case llvm::Intrinsic::x86_sse2_psrai_d:
2371     case llvm::Intrinsic::x86_mmx_psll_w:
2372     case llvm::Intrinsic::x86_mmx_psll_d:
2373     case llvm::Intrinsic::x86_mmx_psll_q:
2374     case llvm::Intrinsic::x86_mmx_pslli_w:
2375     case llvm::Intrinsic::x86_mmx_pslli_d:
2376     case llvm::Intrinsic::x86_mmx_pslli_q:
2377     case llvm::Intrinsic::x86_mmx_psrl_w:
2378     case llvm::Intrinsic::x86_mmx_psrl_d:
2379     case llvm::Intrinsic::x86_mmx_psrl_q:
2380     case llvm::Intrinsic::x86_mmx_psra_w:
2381     case llvm::Intrinsic::x86_mmx_psra_d:
2382     case llvm::Intrinsic::x86_mmx_psrli_w:
2383     case llvm::Intrinsic::x86_mmx_psrli_d:
2384     case llvm::Intrinsic::x86_mmx_psrli_q:
2385     case llvm::Intrinsic::x86_mmx_psrai_w:
2386     case llvm::Intrinsic::x86_mmx_psrai_d:
2387       handleVectorShiftIntrinsic(I, /* Variable */ false);
2388       break;
2389     case llvm::Intrinsic::x86_avx2_psllv_d:
2390     case llvm::Intrinsic::x86_avx2_psllv_d_256:
2391     case llvm::Intrinsic::x86_avx2_psllv_q:
2392     case llvm::Intrinsic::x86_avx2_psllv_q_256:
2393     case llvm::Intrinsic::x86_avx2_psrlv_d:
2394     case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2395     case llvm::Intrinsic::x86_avx2_psrlv_q:
2396     case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2397     case llvm::Intrinsic::x86_avx2_psrav_d:
2398     case llvm::Intrinsic::x86_avx2_psrav_d_256:
2399       handleVectorShiftIntrinsic(I, /* Variable */ true);
2400       break;
2401
2402     case llvm::Intrinsic::x86_sse2_packsswb_128:
2403     case llvm::Intrinsic::x86_sse2_packssdw_128:
2404     case llvm::Intrinsic::x86_sse2_packuswb_128:
2405     case llvm::Intrinsic::x86_sse41_packusdw:
2406     case llvm::Intrinsic::x86_avx2_packsswb:
2407     case llvm::Intrinsic::x86_avx2_packssdw:
2408     case llvm::Intrinsic::x86_avx2_packuswb:
2409     case llvm::Intrinsic::x86_avx2_packusdw:
2410       handleVectorPackIntrinsic(I);
2411       break;
2412
2413     case llvm::Intrinsic::x86_mmx_packsswb:
2414     case llvm::Intrinsic::x86_mmx_packuswb:
2415       handleVectorPackIntrinsic(I, 16);
2416       break;
2417
2418     case llvm::Intrinsic::x86_mmx_packssdw:
2419       handleVectorPackIntrinsic(I, 32);
2420       break;
2421
2422     case llvm::Intrinsic::x86_mmx_psad_bw:
2423     case llvm::Intrinsic::x86_sse2_psad_bw:
2424     case llvm::Intrinsic::x86_avx2_psad_bw:
2425       handleVectorSadIntrinsic(I);
2426       break;
2427
2428     case llvm::Intrinsic::x86_sse2_pmadd_wd:
2429     case llvm::Intrinsic::x86_avx2_pmadd_wd:
2430     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2431     case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2432       handleVectorPmaddIntrinsic(I);
2433       break;
2434
2435     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2436       handleVectorPmaddIntrinsic(I, 8);
2437       break;
2438
2439     case llvm::Intrinsic::x86_mmx_pmadd_wd:
2440       handleVectorPmaddIntrinsic(I, 16);
2441       break;
2442
2443     default:
2444       if (!handleUnknownIntrinsic(I))
2445         visitInstruction(I);
2446       break;
2447     }
2448   }
2449
2450   void visitCallSite(CallSite CS) {
2451     Instruction &I = *CS.getInstruction();
2452     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2453     if (CS.isCall()) {
2454       CallInst *Call = cast<CallInst>(&I);
2455
2456       // For inline asm, do the usual thing: check argument shadow and mark all
2457       // outputs as clean. Note that any side effects of the inline asm that are
2458       // not immediately visible in its constraints are not handled.
2459       if (Call->isInlineAsm()) {
2460         visitInstruction(I);
2461         return;
2462       }
2463
2464       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
2465
2466       // We are going to insert code that relies on the fact that the callee
2467       // will become a non-readonly function after it is instrumented by us. To
2468       // prevent this code from being optimized out, mark that function
2469       // non-readonly in advance.
2470       if (Function *Func = Call->getCalledFunction()) {
2471         // Clear out readonly/readnone attributes.
2472         AttrBuilder B;
2473         B.addAttribute(Attribute::ReadOnly)
2474           .addAttribute(Attribute::ReadNone);
2475         Func->removeAttributes(AttributeSet::FunctionIndex,
2476                                AttributeSet::get(Func->getContext(),
2477                                                  AttributeSet::FunctionIndex,
2478                                                  B));
2479       }
2480     }
2481     IRBuilder<> IRB(&I);
2482
2483     unsigned ArgOffset = 0;
2484     DEBUG(dbgs() << "  CallSite: " << I << "\n");
2485     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2486          ArgIt != End; ++ArgIt) {
2487       Value *A = *ArgIt;
2488       unsigned i = ArgIt - CS.arg_begin();
2489       if (!A->getType()->isSized()) {
2490         DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2491         continue;
2492       }
2493       unsigned Size = 0;
2494       Value *Store = nullptr;
2495       // Compute the Shadow for arg even if it is ByVal, because
2496       // in that case getShadow() will copy the actual arg shadow to
2497       // __msan_param_tls.
2498       Value *ArgShadow = getShadow(A);
2499       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2500       DEBUG(dbgs() << "  Arg#" << i << ": " << *A <<
2501             " Shadow: " << *ArgShadow << "\n");
2502       bool ArgIsInitialized = false;
2503       const DataLayout &DL = F.getParent()->getDataLayout();
2504       if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
2505         assert(A->getType()->isPointerTy() &&
2506                "ByVal argument is not a pointer!");
2507         Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
2508         if (ArgOffset + Size > kParamTLSSize) break;
2509         unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2510         unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
2511         Store = IRB.CreateMemCpy(ArgShadowBase,
2512                                  getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2513                                  Size, Alignment);
2514       } else {
2515         Size = DL.getTypeAllocSize(A->getType());
2516         if (ArgOffset + Size > kParamTLSSize) break;
2517         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2518                                        kShadowTLSAlignment);
2519         Constant *Cst = dyn_cast<Constant>(ArgShadow);
2520         if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
2521       }
2522       if (MS.TrackOrigins && !ArgIsInitialized)
2523         IRB.CreateStore(getOrigin(A),
2524                         getOriginPtrForArgument(A, IRB, ArgOffset));
2525       (void)Store;
2526       assert(Size != 0 && Store != nullptr);
2527       DEBUG(dbgs() << "  Param:" << *Store << "\n");
2528       ArgOffset += RoundUpToAlignment(Size, 8);
2529     }
2530     DEBUG(dbgs() << "  done with call args\n");
2531
2532     FunctionType *FT =
2533       cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
2534     if (FT->isVarArg()) {
2535       VAHelper->visitCallSite(CS, IRB);
2536     }
2537
2538     // Now, get the shadow for the RetVal.
2539     if (!I.getType()->isSized()) return;
2540     // Don't emit the epilogue for musttail call returns.
2541     if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
2542     IRBuilder<> IRBBefore(&I);
2543     // Until we have full dynamic coverage, make sure the retval shadow is 0.
2544     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
2545     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
2546     Instruction *NextInsn = nullptr;
2547     if (CS.isCall()) {
2548       NextInsn = I.getNextNode();
2549     } else {
2550       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2551       if (!NormalDest->getSinglePredecessor()) {
2552         // FIXME: this case is tricky, so we are just conservative here.
2553         // Perhaps we need to split the edge between this BB and NormalDest,
2554         // but a naive attempt to use SplitEdge leads to a crash.
2555         setShadow(&I, getCleanShadow(&I));
2556         setOrigin(&I, getCleanOrigin());
2557         return;
2558       }
2559       NextInsn = NormalDest->getFirstInsertionPt();
2560       assert(NextInsn &&
2561              "Could not find insertion point for retval shadow load");
2562     }
2563     IRBuilder<> IRBAfter(NextInsn);
2564     Value *RetvalShadow =
2565       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2566                                  kShadowTLSAlignment, "_msret");
2567     setShadow(&I, RetvalShadow);
2568     if (MS.TrackOrigins)
2569       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2570   }
2571
2572   bool isAMustTailRetVal(Value *RetVal) {
2573     if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
2574       RetVal = I->getOperand(0);
2575     }
2576     if (auto *I = dyn_cast<CallInst>(RetVal)) {
2577       return I->isMustTailCall();
2578     }
2579     return false;
2580   }
2581
2582   void visitReturnInst(ReturnInst &I) {
2583     IRBuilder<> IRB(&I);
2584     Value *RetVal = I.getReturnValue();
2585     if (!RetVal) return;
2586     // Don't emit the epilogue for musttail call returns.
2587     if (isAMustTailRetVal(RetVal)) return;
2588     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2589     if (CheckReturnValue) {
2590       insertShadowCheck(RetVal, &I);
2591       Value *Shadow = getCleanShadow(RetVal);
2592       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2593     } else {
2594       Value *Shadow = getShadow(RetVal);
2595       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2596       // FIXME: make it conditional if ClStoreCleanOrigin==0
2597       if (MS.TrackOrigins)
2598         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2599     }
2600   }
2601
2602   void visitPHINode(PHINode &I) {
2603     IRBuilder<> IRB(&I);
2604     if (!PropagateShadow) {
2605       setShadow(&I, getCleanShadow(&I));
2606       setOrigin(&I, getCleanOrigin());
2607       return;
2608     }
2609
2610     ShadowPHINodes.push_back(&I);
2611     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2612                                 "_msphi_s"));
2613     if (MS.TrackOrigins)
2614       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2615                                   "_msphi_o"));
2616   }
2617
2618   void visitAllocaInst(AllocaInst &I) {
2619     setShadow(&I, getCleanShadow(&I));
2620     setOrigin(&I, getCleanOrigin());
2621     IRBuilder<> IRB(I.getNextNode());
2622     const DataLayout &DL = F.getParent()->getDataLayout();
2623     uint64_t Size = DL.getTypeAllocSize(I.getAllocatedType());
2624     if (PoisonStack && ClPoisonStackWithCall) {
2625       IRB.CreateCall(MS.MsanPoisonStackFn,
2626                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2627                       ConstantInt::get(MS.IntptrTy, Size)});
2628     } else {
2629       Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2630       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2631       IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2632     }
2633
2634     if (PoisonStack && MS.TrackOrigins) {
2635       SmallString<2048> StackDescriptionStorage;
2636       raw_svector_ostream StackDescription(StackDescriptionStorage);
2637       // We create a string with a description of the stack allocation and
2638       // pass it into __msan_set_alloca_origin.
2639       // It will be printed by the run-time if stack-originated UMR is found.
2640       // The first 4 bytes of the string are set to '----' and will be replaced
2641       // by __msan_va_arg_overflow_size_tls at the first call.
2642       StackDescription << "----" << I.getName() << "@" << F.getName();
2643       Value *Descr =
2644           createPrivateNonConstGlobalForString(*F.getParent(),
2645                                                StackDescription.str());
2646
2647       IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
2648                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2649                       ConstantInt::get(MS.IntptrTy, Size),
2650                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2651                       IRB.CreatePointerCast(&F, MS.IntptrTy)});
2652     }
2653   }
2654
2655   void visitSelectInst(SelectInst& I) {
2656     IRBuilder<> IRB(&I);
2657     // a = select b, c, d
2658     Value *B = I.getCondition();
2659     Value *C = I.getTrueValue();
2660     Value *D = I.getFalseValue();
2661     Value *Sb = getShadow(B);
2662     Value *Sc = getShadow(C);
2663     Value *Sd = getShadow(D);
2664
2665     // Result shadow if condition shadow is 0.
2666     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2667     Value *Sa1;
2668     if (I.getType()->isAggregateType()) {
2669       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2670       // an extra "select". This results in much more compact IR.
2671       // Sa = select Sb, poisoned, (select b, Sc, Sd)
2672       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
2673     } else {
2674       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2675       // If Sb (condition is poisoned), look for bits in c and d that are equal
2676       // and both unpoisoned.
2677       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2678
2679       // Cast arguments to shadow-compatible type.
2680       C = CreateAppToShadowCast(IRB, C);
2681       D = CreateAppToShadowCast(IRB, D);
2682
2683       // Result shadow if condition shadow is 1.
2684       Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
2685     }
2686     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2687     setShadow(&I, Sa);
2688     if (MS.TrackOrigins) {
2689       // Origins are always i32, so any vector conditions must be flattened.
2690       // FIXME: consider tracking vector origins for app vectors?
2691       if (B->getType()->isVectorTy()) {
2692         Type *FlatTy = getShadowTyNoVec(B->getType());
2693         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
2694                                 ConstantInt::getNullValue(FlatTy));
2695         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
2696                                       ConstantInt::getNullValue(FlatTy));
2697       }
2698       // a = select b, c, d
2699       // Oa = Sb ? Ob : (b ? Oc : Od)
2700       setOrigin(
2701           &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2702                                IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2703                                                 getOrigin(I.getFalseValue()))));
2704     }
2705   }
2706
2707   void visitLandingPadInst(LandingPadInst &I) {
2708     // Do nothing.
2709     // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2710     setShadow(&I, getCleanShadow(&I));
2711     setOrigin(&I, getCleanOrigin());
2712   }
2713
2714   void visitCleanupPadInst(CleanupPadInst &I) {
2715     setShadow(&I, getCleanShadow(&I));
2716     setOrigin(&I, getCleanOrigin());
2717   }
2718
2719   void visitCatchPad(CatchPadInst &I) {
2720     setShadow(&I, getCleanShadow(&I));
2721     setOrigin(&I, getCleanOrigin());
2722   }
2723
2724   void visitTerminatePad(TerminatePadInst &I) {
2725     DEBUG(dbgs() << "TerminatePad: " << I << "\n");
2726     // Nothing to do here.
2727   }
2728
2729   void visitCatchEndPadInst(CatchEndPadInst &I) {
2730     DEBUG(dbgs() << "CatchEndPad: " << I << "\n");
2731     // Nothing to do here.
2732   }
2733
2734   void visitCleanupEndPadInst(CleanupEndPadInst &I) {
2735     DEBUG(dbgs() << "CleanupEndPad: " << I << "\n");
2736     // Nothing to do here.
2737   }
2738
2739   void visitGetElementPtrInst(GetElementPtrInst &I) {
2740     handleShadowOr(I);
2741   }
2742
2743   void visitExtractValueInst(ExtractValueInst &I) {
2744     IRBuilder<> IRB(&I);
2745     Value *Agg = I.getAggregateOperand();
2746     DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
2747     Value *AggShadow = getShadow(Agg);
2748     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2749     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2750     DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
2751     setShadow(&I, ResShadow);
2752     setOriginForNaryOp(I);
2753   }
2754
2755   void visitInsertValueInst(InsertValueInst &I) {
2756     IRBuilder<> IRB(&I);
2757     DEBUG(dbgs() << "InsertValue:  " << I << "\n");
2758     Value *AggShadow = getShadow(I.getAggregateOperand());
2759     Value *InsShadow = getShadow(I.getInsertedValueOperand());
2760     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2761     DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
2762     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2763     DEBUG(dbgs() << "   Res:        " << *Res << "\n");
2764     setShadow(&I, Res);
2765     setOriginForNaryOp(I);
2766   }
2767
2768   void dumpInst(Instruction &I) {
2769     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2770       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2771     } else {
2772       errs() << "ZZZ " << I.getOpcodeName() << "\n";
2773     }
2774     errs() << "QQQ " << I << "\n";
2775   }
2776
2777   void visitResumeInst(ResumeInst &I) {
2778     DEBUG(dbgs() << "Resume: " << I << "\n");
2779     // Nothing to do here.
2780   }
2781
2782   void visitCleanupReturnInst(CleanupReturnInst &CRI) {
2783     DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
2784     // Nothing to do here.
2785   }
2786
2787   void visitCatchReturnInst(CatchReturnInst &CRI) {
2788     DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
2789     // Nothing to do here.
2790   }
2791
2792   void visitInstruction(Instruction &I) {
2793     // Everything else: stop propagating and check for poisoned shadow.
2794     if (ClDumpStrictInstructions)
2795       dumpInst(I);
2796     DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2797     for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2798       insertShadowCheck(I.getOperand(i), &I);
2799     setShadow(&I, getCleanShadow(&I));
2800     setOrigin(&I, getCleanOrigin());
2801   }
2802 };
2803
2804 /// \brief AMD64-specific implementation of VarArgHelper.
2805 struct VarArgAMD64Helper : public VarArgHelper {
2806   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2807   // See a comment in visitCallSite for more details.
2808   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
2809   static const unsigned AMD64FpEndOffset = 176;
2810
2811   Function &F;
2812   MemorySanitizer &MS;
2813   MemorySanitizerVisitor &MSV;
2814   Value *VAArgTLSCopy;
2815   Value *VAArgOverflowSize;
2816
2817   SmallVector<CallInst*, 16> VAStartInstrumentationList;
2818
2819   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2820                     MemorySanitizerVisitor &MSV)
2821     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2822       VAArgOverflowSize(nullptr) {}
2823
2824   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2825
2826   ArgKind classifyArgument(Value* arg) {
2827     // A very rough approximation of X86_64 argument classification rules.
2828     Type *T = arg->getType();
2829     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2830       return AK_FloatingPoint;
2831     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2832       return AK_GeneralPurpose;
2833     if (T->isPointerTy())
2834       return AK_GeneralPurpose;
2835     return AK_Memory;
2836   }
2837
2838   // For VarArg functions, store the argument shadow in an ABI-specific format
2839   // that corresponds to va_list layout.
2840   // We do this because Clang lowers va_arg in the frontend, and this pass
2841   // only sees the low level code that deals with va_list internals.
2842   // A much easier alternative (provided that Clang emits va_arg instructions)
2843   // would have been to associate each live instance of va_list with a copy of
2844   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2845   // order.
2846   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2847     unsigned GpOffset = 0;
2848     unsigned FpOffset = AMD64GpEndOffset;
2849     unsigned OverflowOffset = AMD64FpEndOffset;
2850     const DataLayout &DL = F.getParent()->getDataLayout();
2851     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2852          ArgIt != End; ++ArgIt) {
2853       Value *A = *ArgIt;
2854       unsigned ArgNo = CS.getArgumentNo(ArgIt);
2855       bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2856       if (IsByVal) {
2857         // ByVal arguments always go to the overflow area.
2858         assert(A->getType()->isPointerTy());
2859         Type *RealTy = A->getType()->getPointerElementType();
2860         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
2861         Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
2862         OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2863         IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2864                          ArgSize, kShadowTLSAlignment);
2865       } else {
2866         ArgKind AK = classifyArgument(A);
2867         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2868           AK = AK_Memory;
2869         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2870           AK = AK_Memory;
2871         Value *Base;
2872         switch (AK) {
2873           case AK_GeneralPurpose:
2874             Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2875             GpOffset += 8;
2876             break;
2877           case AK_FloatingPoint:
2878             Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2879             FpOffset += 16;
2880             break;
2881           case AK_Memory:
2882             uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
2883             Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2884             OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2885         }
2886         IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2887       }
2888     }
2889     Constant *OverflowSize =
2890       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2891     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2892   }
2893
2894   /// \brief Compute the shadow address for a given va_arg.
2895   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2896                                    int ArgOffset) {
2897     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2898     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2899     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2900                               "_msarg");
2901   }
2902
2903   void visitVAStartInst(VAStartInst &I) override {
2904     if (F.getCallingConv() == CallingConv::X86_64_Win64)
2905       return;
2906     IRBuilder<> IRB(&I);
2907     VAStartInstrumentationList.push_back(&I);
2908     Value *VAListTag = I.getArgOperand(0);
2909     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2910
2911     // Unpoison the whole __va_list_tag.
2912     // FIXME: magic ABI constants.
2913     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2914                      /* size */24, /* alignment */8, false);
2915   }
2916
2917   void visitVACopyInst(VACopyInst &I) override {
2918     if (F.getCallingConv() == CallingConv::X86_64_Win64)
2919       return;
2920     IRBuilder<> IRB(&I);
2921     Value *VAListTag = I.getArgOperand(0);
2922     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2923
2924     // Unpoison the whole __va_list_tag.
2925     // FIXME: magic ABI constants.
2926     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2927                      /* size */24, /* alignment */8, false);
2928   }
2929
2930   void finalizeInstrumentation() override {
2931     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2932            "finalizeInstrumentation called twice");
2933     if (!VAStartInstrumentationList.empty()) {
2934       // If there is a va_start in this function, make a backup copy of
2935       // va_arg_tls somewhere in the function entry block.
2936       IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2937       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2938       Value *CopySize =
2939         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2940                       VAArgOverflowSize);
2941       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2942       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2943     }
2944
2945     // Instrument va_start.
2946     // Copy va_list shadow from the backup copy of the TLS contents.
2947     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2948       CallInst *OrigInst = VAStartInstrumentationList[i];
2949       IRBuilder<> IRB(OrigInst->getNextNode());
2950       Value *VAListTag = OrigInst->getArgOperand(0);
2951
2952       Value *RegSaveAreaPtrPtr =
2953         IRB.CreateIntToPtr(
2954           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2955                         ConstantInt::get(MS.IntptrTy, 16)),
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,
2961                        AMD64FpEndOffset, 16);
2962
2963       Value *OverflowArgAreaPtrPtr =
2964         IRB.CreateIntToPtr(
2965           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2966                         ConstantInt::get(MS.IntptrTy, 8)),
2967           Type::getInt64PtrTy(*MS.C));
2968       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2969       Value *OverflowArgAreaShadowPtr =
2970         MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2971       Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
2972                                              AMD64FpEndOffset);
2973       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2974     }
2975   }
2976 };
2977
2978 /// \brief MIPS64-specific implementation of VarArgHelper.
2979 struct VarArgMIPS64Helper : public VarArgHelper {
2980   Function &F;
2981   MemorySanitizer &MS;
2982   MemorySanitizerVisitor &MSV;
2983   Value *VAArgTLSCopy;
2984   Value *VAArgSize;
2985
2986   SmallVector<CallInst*, 16> VAStartInstrumentationList;
2987
2988   VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
2989                     MemorySanitizerVisitor &MSV)
2990     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2991       VAArgSize(nullptr) {}
2992
2993   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2994     unsigned VAArgOffset = 0;
2995     const DataLayout &DL = F.getParent()->getDataLayout();
2996     for (CallSite::arg_iterator ArgIt = CS.arg_begin() + 1, End = CS.arg_end();
2997          ArgIt != End; ++ArgIt) {
2998       Value *A = *ArgIt;
2999       Value *Base;
3000       uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
3001 #if defined(__MIPSEB__) || defined(MIPSEB)
3002       // Adjusting the shadow for argument with size < 8 to match the placement
3003       // of bits in big endian system
3004       if (ArgSize < 8)
3005         VAArgOffset += (8 - ArgSize);
3006 #endif
3007       Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
3008       VAArgOffset += ArgSize;
3009       VAArgOffset = RoundUpToAlignment(VAArgOffset, 8);
3010       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
3011     }
3012
3013     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
3014     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
3015     // a new class member i.e. it is the total size of all VarArgs.
3016     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
3017   }
3018
3019   /// \brief Compute the shadow address for a given va_arg.
3020   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3021                                    int ArgOffset) {
3022     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3023     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3024     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3025                               "_msarg");
3026   }
3027
3028   void visitVAStartInst(VAStartInst &I) override {
3029     IRBuilder<> IRB(&I);
3030     VAStartInstrumentationList.push_back(&I);
3031     Value *VAListTag = I.getArgOperand(0);
3032     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3033     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3034                      /* size */8, /* alignment */8, false);
3035   }
3036
3037   void visitVACopyInst(VACopyInst &I) override {
3038     IRBuilder<> IRB(&I);
3039     Value *VAListTag = I.getArgOperand(0);
3040     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3041     // Unpoison the whole __va_list_tag.
3042     // FIXME: magic ABI constants.
3043     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3044                      /* size */8, /* alignment */8, false);
3045   }
3046
3047   void finalizeInstrumentation() override {
3048     assert(!VAArgSize && !VAArgTLSCopy &&
3049            "finalizeInstrumentation called twice");
3050     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
3051     VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3052     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
3053                                     VAArgSize);
3054
3055     if (!VAStartInstrumentationList.empty()) {
3056       // If there is a va_start in this function, make a backup copy of
3057       // va_arg_tls somewhere in the function entry block.
3058       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3059       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
3060     }
3061
3062     // Instrument va_start.
3063     // Copy va_list shadow from the backup copy of the TLS contents.
3064     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3065       CallInst *OrigInst = VAStartInstrumentationList[i];
3066       IRBuilder<> IRB(OrigInst->getNextNode());
3067       Value *VAListTag = OrigInst->getArgOperand(0);
3068       Value *RegSaveAreaPtrPtr =
3069         IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3070                         Type::getInt64PtrTy(*MS.C));
3071       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3072       Value *RegSaveAreaShadowPtr =
3073       MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
3074       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
3075     }
3076   }
3077 };
3078
3079 /// \brief A no-op implementation of VarArgHelper.
3080 struct VarArgNoOpHelper : public VarArgHelper {
3081   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
3082                    MemorySanitizerVisitor &MSV) {}
3083
3084   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
3085
3086   void visitVAStartInst(VAStartInst &I) override {}
3087
3088   void visitVACopyInst(VACopyInst &I) override {}
3089
3090   void finalizeInstrumentation() override {}
3091 };
3092
3093 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
3094                                  MemorySanitizerVisitor &Visitor) {
3095   // VarArg handling is only implemented on AMD64. False positives are possible
3096   // on other platforms.
3097   llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
3098   if (TargetTriple.getArch() == llvm::Triple::x86_64)
3099     return new VarArgAMD64Helper(Func, Msan, Visitor);
3100   else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
3101            TargetTriple.getArch() == llvm::Triple::mips64el)
3102     return new VarArgMIPS64Helper(Func, Msan, Visitor);
3103   else
3104     return new VarArgNoOpHelper(Func, Msan, Visitor);
3105 }
3106
3107 } // anonymous namespace
3108
3109 bool MemorySanitizer::runOnFunction(Function &F) {
3110   if (&F == MsanCtorFunction)
3111     return false;
3112   MemorySanitizerVisitor Visitor(F, *this);
3113
3114   // Clear out readonly/readnone attributes.
3115   AttrBuilder B;
3116   B.addAttribute(Attribute::ReadOnly)
3117     .addAttribute(Attribute::ReadNone);
3118   F.removeAttributes(AttributeSet::FunctionIndex,
3119                      AttributeSet::get(F.getContext(),
3120                                        AttributeSet::FunctionIndex, B));
3121
3122   return Visitor.runOnFunction();
3123 }