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