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