1 //===- MemorySanitizer.cpp - detector of uninitialized reads --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
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 overwriting 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 ///                      Instrumenting inline assembly.
93 ///
94 /// For inline assembly code LLVM has little idea about which memory locations
95 /// become initialized depending on the arguments. It can be possible to figure
96 /// out which arguments are meant to point to inputs and outputs, but the
97 /// actual semantics can be only visible at runtime. In the Linux kernel it's
98 /// also possible that the arguments only indicate the offset for a base taken
99 /// from a segment register, so it's dangerous to treat any asm() arguments as
100 /// pointers. We take a conservative approach generating calls to
101 ///   __msan_instrument_asm_store(ptr, size)
102 /// , which defer the memory unpoisoning to the runtime library.
103 /// The latter can perform more complex address checks to figure out whether
104 /// it's safe to touch the shadow memory.
105 /// Like with atomic operations, we call __msan_instrument_asm_store() before
106 /// the assembly call, so that changes to the shadow memory will be seen by
107 /// other threads together with main memory initialization.
108 ///
109 ///                  KernelMemorySanitizer (KMSAN) implementation.
110 ///
111 /// The major differences between KMSAN and MSan instrumentation are:
112 ///  - KMSAN always tracks the origins and implies msan-keep-going=true;
113 ///  - KMSAN allocates shadow and origin memory for each page separately, so
114 ///    there are no explicit accesses to shadow and origin in the
115 ///    instrumentation.
116 ///    Shadow and origin values for a particular X-byte memory location
117 ///    (X=1,2,4,8) are accessed through pointers obtained via the
118 ///      __msan_metadata_ptr_for_load_X(ptr)
119 ///      __msan_metadata_ptr_for_store_X(ptr)
120 ///    functions. The corresponding functions check that the X-byte accesses
121 ///    are possible and returns the pointers to shadow and origin memory.
122 ///    Arbitrary sized accesses are handled with:
123 ///      __msan_metadata_ptr_for_load_n(ptr, size)
124 ///      __msan_metadata_ptr_for_store_n(ptr, size);
125 ///  - TLS variables are stored in a single per-task struct. A call to a
126 ///    function __msan_get_context_state() returning a pointer to that struct
127 ///    is inserted into every instrumented function before the entry block;
128 ///  - __msan_warning() takes a 32-bit origin parameter;
129 ///  - local variables are poisoned with __msan_poison_alloca() upon function
130 ///    entry and unpoisoned with __msan_unpoison_alloca() before leaving the
131 ///    function;
132 ///  - the pass doesn't declare any global variables or add global constructors
133 ///    to the translation unit.
134 ///
135 /// Also, KMSAN currently ignores uninitialized memory passed into inline asm
136 /// calls, making sure we're on the safe side wrt. possible false positives.
137 ///
138 ///  KernelMemorySanitizer only supports X86_64 at the moment.
139 ///
140 //
141 // FIXME: This sanitizer does not yet handle scalable vectors
142 //
143 //===----------------------------------------------------------------------===//
144 
145 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
146 #include "llvm/ADT/APInt.h"
147 #include "llvm/ADT/ArrayRef.h"
148 #include "llvm/ADT/DepthFirstIterator.h"
149 #include "llvm/ADT/SmallSet.h"
150 #include "llvm/ADT/SmallString.h"
151 #include "llvm/ADT/SmallVector.h"
152 #include "llvm/ADT/StringExtras.h"
153 #include "llvm/ADT/StringRef.h"
154 #include "llvm/ADT/Triple.h"
155 #include "llvm/Analysis/TargetLibraryInfo.h"
156 #include "llvm/IR/Argument.h"
157 #include "llvm/IR/Attributes.h"
158 #include "llvm/IR/BasicBlock.h"
159 #include "llvm/IR/CallingConv.h"
160 #include "llvm/IR/Constant.h"
161 #include "llvm/IR/Constants.h"
162 #include "llvm/IR/DataLayout.h"
163 #include "llvm/IR/DerivedTypes.h"
164 #include "llvm/IR/Function.h"
165 #include "llvm/IR/GlobalValue.h"
166 #include "llvm/IR/GlobalVariable.h"
167 #include "llvm/IR/IRBuilder.h"
168 #include "llvm/IR/InlineAsm.h"
169 #include "llvm/IR/InstVisitor.h"
170 #include "llvm/IR/InstrTypes.h"
171 #include "llvm/IR/Instruction.h"
172 #include "llvm/IR/Instructions.h"
173 #include "llvm/IR/IntrinsicInst.h"
174 #include "llvm/IR/Intrinsics.h"
175 #include "llvm/IR/IntrinsicsX86.h"
176 #include "llvm/IR/LLVMContext.h"
177 #include "llvm/IR/MDBuilder.h"
178 #include "llvm/IR/Module.h"
179 #include "llvm/IR/Type.h"
180 #include "llvm/IR/Value.h"
181 #include "llvm/IR/ValueMap.h"
182 #include "llvm/InitializePasses.h"
183 #include "llvm/Pass.h"
184 #include "llvm/Support/AtomicOrdering.h"
185 #include "llvm/Support/Casting.h"
186 #include "llvm/Support/CommandLine.h"
187 #include "llvm/Support/Compiler.h"
188 #include "llvm/Support/Debug.h"
189 #include "llvm/Support/ErrorHandling.h"
190 #include "llvm/Support/MathExtras.h"
191 #include "llvm/Support/raw_ostream.h"
192 #include "llvm/Transforms/Instrumentation.h"
193 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
194 #include "llvm/Transforms/Utils/Local.h"
195 #include "llvm/Transforms/Utils/ModuleUtils.h"
196 #include <algorithm>
197 #include <cassert>
198 #include <cstddef>
199 #include <cstdint>
200 #include <memory>
201 #include <string>
202 #include <tuple>
203 
204 using namespace llvm;
205 
206 #define DEBUG_TYPE "msan"
207 
208 static const unsigned kOriginSize = 4;
209 static const Align kMinOriginAlignment = Align(4);
210 static const Align kShadowTLSAlignment = Align(8);
211 
212 // These constants must be kept in sync with the ones in msan.h.
213 static const unsigned kParamTLSSize = 800;
214 static const unsigned kRetvalTLSSize = 800;
215 
216 // Accesses sizes are powers of two: 1, 2, 4, 8.
217 static const size_t kNumberOfAccessSizes = 4;
218 
219 /// Track origins of uninitialized values.
220 ///
221 /// Adds a section to MemorySanitizer report that points to the allocation
222 /// (stack or heap) the uninitialized bits came from originally.
223 static cl::opt<int> ClTrackOrigins("msan-track-origins",
224        cl::desc("Track origins (allocation sites) of poisoned memory"),
225        cl::Hidden, cl::init(0));
226 
227 static cl::opt<bool> ClKeepGoing("msan-keep-going",
228        cl::desc("keep going after reporting a UMR"),
229        cl::Hidden, cl::init(false));
230 
231 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
232        cl::desc("poison uninitialized stack variables"),
233        cl::Hidden, cl::init(true));
234 
235 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
236        cl::desc("poison uninitialized stack variables with a call"),
237        cl::Hidden, cl::init(false));
238 
239 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
240        cl::desc("poison uninitialized stack variables with the given pattern"),
241        cl::Hidden, cl::init(0xff));
242 
243 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
244        cl::desc("poison undef temps"),
245        cl::Hidden, cl::init(true));
246 
247 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
248        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
249        cl::Hidden, cl::init(true));
250 
251 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
252        cl::desc("exact handling of relational integer ICmp"),
253        cl::Hidden, cl::init(false));
254 
255 static cl::opt<bool> ClHandleLifetimeIntrinsics(
256     "msan-handle-lifetime-intrinsics",
257     cl::desc(
258         "when possible, poison scoped variables at the beginning of the scope "
259         "(slower, but more precise)"),
260     cl::Hidden, cl::init(true));
261 
262 // When compiling the Linux kernel, we sometimes see false positives related to
263 // MSan being unable to understand that inline assembly calls may initialize
264 // local variables.
265 // This flag makes the compiler conservatively unpoison every memory location
266 // passed into an assembly call. Note that this may cause false positives.
267 // Because it's impossible to figure out the array sizes, we can only unpoison
268 // the first sizeof(type) bytes for each type* pointer.
269 // The instrumentation is only enabled in KMSAN builds, and only if
270 // -msan-handle-asm-conservative is on. This is done because we may want to
271 // quickly disable assembly instrumentation when it breaks.
272 static cl::opt<bool> ClHandleAsmConservative(
273     "msan-handle-asm-conservative",
274     cl::desc("conservative handling of inline assembly"), cl::Hidden,
275     cl::init(true));
276 
277 // This flag controls whether we check the shadow of the address
278 // operand of load or store. Such bugs are very rare, since load from
279 // a garbage address typically results in SEGV, but still happen
280 // (e.g. only lower bits of address are garbage, or the access happens
281 // early at program startup where malloc-ed memory is more likely to
282 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
283 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
284        cl::desc("report accesses through a pointer which has poisoned shadow"),
285        cl::Hidden, cl::init(true));
286 
287 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
288        cl::desc("print out instructions with default strict semantics"),
289        cl::Hidden, cl::init(false));
290 
291 static cl::opt<int> ClInstrumentationWithCallThreshold(
292     "msan-instrumentation-with-call-threshold",
293     cl::desc(
294         "If the function being instrumented requires more than "
295         "this number of checks and origin stores, use callbacks instead of "
296         "inline checks (-1 means never use callbacks)."),
297     cl::Hidden, cl::init(3500));
298 
299 static cl::opt<bool>
300     ClEnableKmsan("msan-kernel",
301                   cl::desc("Enable KernelMemorySanitizer instrumentation"),
302                   cl::Hidden, cl::init(false));
303 
304 // This is an experiment to enable handling of cases where shadow is a non-zero
305 // compile-time constant. For some unexplainable reason they were silently
306 // ignored in the instrumentation.
307 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
308        cl::desc("Insert checks for constant shadow values"),
309        cl::Hidden, cl::init(false));
310 
311 // This is off by default because of a bug in gold:
312 // https://sourceware.org/bugzilla/show_bug.cgi?id=19002
313 static cl::opt<bool> ClWithComdat("msan-with-comdat",
314        cl::desc("Place MSan constructors in comdat sections"),
315        cl::Hidden, cl::init(false));
316 
317 // These options allow to specify custom memory map parameters
318 // See MemoryMapParams for details.
319 static cl::opt<uint64_t> ClAndMask("msan-and-mask",
320                                    cl::desc("Define custom MSan AndMask"),
321                                    cl::Hidden, cl::init(0));
322 
323 static cl::opt<uint64_t> ClXorMask("msan-xor-mask",
324                                    cl::desc("Define custom MSan XorMask"),
325                                    cl::Hidden, cl::init(0));
326 
327 static cl::opt<uint64_t> ClShadowBase("msan-shadow-base",
328                                       cl::desc("Define custom MSan ShadowBase"),
329                                       cl::Hidden, cl::init(0));
330 
331 static cl::opt<uint64_t> ClOriginBase("msan-origin-base",
332                                       cl::desc("Define custom MSan OriginBase"),
333                                       cl::Hidden, cl::init(0));
334 
335 static const char *const kMsanModuleCtorName = "msan.module_ctor";
336 static const char *const kMsanInitName = "__msan_init";
337 
338 namespace {
339 
340 // Memory map parameters used in application-to-shadow address calculation.
341 // Offset = (Addr & ~AndMask) ^ XorMask
342 // Shadow = ShadowBase + Offset
343 // Origin = OriginBase + Offset
344 struct MemoryMapParams {
345   uint64_t AndMask;
346   uint64_t XorMask;
347   uint64_t ShadowBase;
348   uint64_t OriginBase;
349 };
350 
351 struct PlatformMemoryMapParams {
352   const MemoryMapParams *bits32;
353   const MemoryMapParams *bits64;
354 };
355 
356 } // end anonymous namespace
357 
358 // i386 Linux
359 static const MemoryMapParams Linux_I386_MemoryMapParams = {
360   0x000080000000,  // AndMask
361   0,               // XorMask (not used)
362   0,               // ShadowBase (not used)
363   0x000040000000,  // OriginBase
364 };
365 
366 // x86_64 Linux
367 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
368 #ifdef MSAN_LINUX_X86_64_OLD_MAPPING
369   0x400000000000,  // AndMask
370   0,               // XorMask (not used)
371   0,               // ShadowBase (not used)
372   0x200000000000,  // OriginBase
373 #else
374   0,               // AndMask (not used)
375   0x500000000000,  // XorMask
376   0,               // ShadowBase (not used)
377   0x100000000000,  // OriginBase
378 #endif
379 };
380 
381 // mips64 Linux
382 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
383   0,               // AndMask (not used)
384   0x008000000000,  // XorMask
385   0,               // ShadowBase (not used)
386   0x002000000000,  // OriginBase
387 };
388 
389 // ppc64 Linux
390 static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
391   0xE00000000000,  // AndMask
392   0x100000000000,  // XorMask
393   0x080000000000,  // ShadowBase
394   0x1C0000000000,  // OriginBase
395 };
396 
397 // s390x Linux
398 static const MemoryMapParams Linux_S390X_MemoryMapParams = {
399     0xC00000000000, // AndMask
400     0,              // XorMask (not used)
401     0x080000000000, // ShadowBase
402     0x1C0000000000, // OriginBase
403 };
404 
405 // aarch64 Linux
406 static const MemoryMapParams Linux_AArch64_MemoryMapParams = {
407   0,               // AndMask (not used)
408   0x06000000000,   // XorMask
409   0,               // ShadowBase (not used)
410   0x01000000000,   // OriginBase
411 };
412 
413 // i386 FreeBSD
414 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
415   0x000180000000,  // AndMask
416   0x000040000000,  // XorMask
417   0x000020000000,  // ShadowBase
418   0x000700000000,  // OriginBase
419 };
420 
421 // x86_64 FreeBSD
422 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
423   0xc00000000000,  // AndMask
424   0x200000000000,  // XorMask
425   0x100000000000,  // ShadowBase
426   0x380000000000,  // OriginBase
427 };
428 
429 // x86_64 NetBSD
430 static const MemoryMapParams NetBSD_X86_64_MemoryMapParams = {
431   0,               // AndMask
432   0x500000000000,  // XorMask
433   0,               // ShadowBase
434   0x100000000000,  // OriginBase
435 };
436 
437 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
438   &Linux_I386_MemoryMapParams,
439   &Linux_X86_64_MemoryMapParams,
440 };
441 
442 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
443   nullptr,
444   &Linux_MIPS64_MemoryMapParams,
445 };
446 
447 static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
448   nullptr,
449   &Linux_PowerPC64_MemoryMapParams,
450 };
451 
452 static const PlatformMemoryMapParams Linux_S390_MemoryMapParams = {
453     nullptr,
454     &Linux_S390X_MemoryMapParams,
455 };
456 
457 static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = {
458   nullptr,
459   &Linux_AArch64_MemoryMapParams,
460 };
461 
462 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
463   &FreeBSD_I386_MemoryMapParams,
464   &FreeBSD_X86_64_MemoryMapParams,
465 };
466 
467 static const PlatformMemoryMapParams NetBSD_X86_MemoryMapParams = {
468   nullptr,
469   &NetBSD_X86_64_MemoryMapParams,
470 };
471 
472 namespace {
473 
474 /// Instrument functions of a module to detect uninitialized reads.
475 ///
476 /// Instantiating MemorySanitizer inserts the msan runtime library API function
477 /// declarations into the module if they don't exist already. Instantiating
478 /// ensures the __msan_init function is in the list of global constructors for
479 /// the module.
480 class MemorySanitizer {
481 public:
482   MemorySanitizer(Module &M, MemorySanitizerOptions Options)
483       : CompileKernel(Options.Kernel), TrackOrigins(Options.TrackOrigins),
484         Recover(Options.Recover) {
485     initializeModule(M);
486   }
487 
488   // MSan cannot be moved or copied because of MapParams.
489   MemorySanitizer(MemorySanitizer &&) = delete;
490   MemorySanitizer &operator=(MemorySanitizer &&) = delete;
491   MemorySanitizer(const MemorySanitizer &) = delete;
492   MemorySanitizer &operator=(const MemorySanitizer &) = delete;
493 
494   bool sanitizeFunction(Function &F, TargetLibraryInfo &TLI);
495 
496 private:
497   friend struct MemorySanitizerVisitor;
498   friend struct VarArgAMD64Helper;
499   friend struct VarArgMIPS64Helper;
500   friend struct VarArgAArch64Helper;
501   friend struct VarArgPowerPC64Helper;
502   friend struct VarArgSystemZHelper;
503 
504   void initializeModule(Module &M);
505   void initializeCallbacks(Module &M);
506   void createKernelApi(Module &M);
507   void createUserspaceApi(Module &M);
508 
509   /// True if we're compiling the Linux kernel.
510   bool CompileKernel;
511   /// Track origins (allocation points) of uninitialized values.
512   int TrackOrigins;
513   bool Recover;
514 
515   LLVMContext *C;
516   Type *IntptrTy;
517   Type *OriginTy;
518 
519   // XxxTLS variables represent the per-thread state in MSan and per-task state
520   // in KMSAN.
521   // For the userspace these point to thread-local globals. In the kernel land
522   // they point to the members of a per-task struct obtained via a call to
523   // __msan_get_context_state().
524 
525   /// Thread-local shadow storage for function parameters.
526   Value *ParamTLS;
527 
528   /// Thread-local origin storage for function parameters.
529   Value *ParamOriginTLS;
530 
531   /// Thread-local shadow storage for function return value.
532   Value *RetvalTLS;
533 
534   /// Thread-local origin storage for function return value.
535   Value *RetvalOriginTLS;
536 
537   /// Thread-local shadow storage for in-register va_arg function
538   /// parameters (x86_64-specific).
539   Value *VAArgTLS;
540 
541   /// Thread-local shadow storage for in-register va_arg function
542   /// parameters (x86_64-specific).
543   Value *VAArgOriginTLS;
544 
545   /// Thread-local shadow storage for va_arg overflow area
546   /// (x86_64-specific).
547   Value *VAArgOverflowSizeTLS;
548 
549   /// Are the instrumentation callbacks set up?
550   bool CallbacksInitialized = false;
551 
552   /// The run-time callback to print a warning.
553   FunctionCallee WarningFn;
554 
555   // These arrays are indexed by log2(AccessSize).
556   FunctionCallee MaybeWarningFn[kNumberOfAccessSizes];
557   FunctionCallee MaybeStoreOriginFn[kNumberOfAccessSizes];
558 
559   /// Run-time helper that generates a new origin value for a stack
560   /// allocation.
561   FunctionCallee MsanSetAllocaOrigin4Fn;
562 
563   /// Run-time helper that poisons stack on function entry.
564   FunctionCallee MsanPoisonStackFn;
565 
566   /// Run-time helper that records a store (or any event) of an
567   /// uninitialized value and returns an updated origin id encoding this info.
568   FunctionCallee MsanChainOriginFn;
569 
570   /// MSan runtime replacements for memmove, memcpy and memset.
571   FunctionCallee MemmoveFn, MemcpyFn, MemsetFn;
572 
573   /// KMSAN callback for task-local function argument shadow.
574   StructType *MsanContextStateTy;
575   FunctionCallee MsanGetContextStateFn;
576 
577   /// Functions for poisoning/unpoisoning local variables
578   FunctionCallee MsanPoisonAllocaFn, MsanUnpoisonAllocaFn;
579 
580   /// Each of the MsanMetadataPtrXxx functions returns a pair of shadow/origin
581   /// pointers.
582   FunctionCallee MsanMetadataPtrForLoadN, MsanMetadataPtrForStoreN;
583   FunctionCallee MsanMetadataPtrForLoad_1_8[4];
584   FunctionCallee MsanMetadataPtrForStore_1_8[4];
585   FunctionCallee MsanInstrumentAsmStoreFn;
586 
587   /// Helper to choose between different MsanMetadataPtrXxx().
588   FunctionCallee getKmsanShadowOriginAccessFn(bool isStore, int size);
589 
590   /// Memory map parameters used in application-to-shadow calculation.
591   const MemoryMapParams *MapParams;
592 
593   /// Custom memory map parameters used when -msan-shadow-base or
594   // -msan-origin-base is provided.
595   MemoryMapParams CustomMapParams;
596 
597   MDNode *ColdCallWeights;
598 
599   /// Branch weights for origin store.
600   MDNode *OriginStoreWeights;
601 };
602 
603 void insertModuleCtor(Module &M) {
604   getOrCreateSanitizerCtorAndInitFunctions(
605       M, kMsanModuleCtorName, kMsanInitName,
606       /*InitArgTypes=*/{},
607       /*InitArgs=*/{},
608       // This callback is invoked when the functions are created the first
609       // time. Hook them into the global ctors list in that case:
610       [&](Function *Ctor, FunctionCallee) {
611         if (!ClWithComdat) {
612           appendToGlobalCtors(M, Ctor, 0);
613           return;
614         }
615         Comdat *MsanCtorComdat = M.getOrInsertComdat(kMsanModuleCtorName);
616         Ctor->setComdat(MsanCtorComdat);
617         appendToGlobalCtors(M, Ctor, 0, Ctor);
618       });
619 }
620 
621 /// A legacy function pass for msan instrumentation.
622 ///
623 /// Instruments functions to detect uninitialized reads.
624 struct MemorySanitizerLegacyPass : public FunctionPass {
625   // Pass identification, replacement for typeid.
626   static char ID;
627 
628   MemorySanitizerLegacyPass(MemorySanitizerOptions Options = {})
629       : FunctionPass(ID), Options(Options) {
630     initializeMemorySanitizerLegacyPassPass(*PassRegistry::getPassRegistry());
631   }
632   StringRef getPassName() const override { return "MemorySanitizerLegacyPass"; }
633 
634   void getAnalysisUsage(AnalysisUsage &AU) const override {
635     AU.addRequired<TargetLibraryInfoWrapperPass>();
636   }
637 
638   bool runOnFunction(Function &F) override {
639     return MSan->sanitizeFunction(
640         F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F));
641   }
642   bool doInitialization(Module &M) override;
643 
644   Optional<MemorySanitizer> MSan;
645   MemorySanitizerOptions Options;
646 };
647 
648 template <class T> T getOptOrDefault(const cl::opt<T> &Opt, T Default) {
649   return (Opt.getNumOccurrences() > 0) ? Opt : Default;
650 }
651 
652 } // end anonymous namespace
653 
654 MemorySanitizerOptions::MemorySanitizerOptions(int TO, bool R, bool K)
655     : Kernel(getOptOrDefault(ClEnableKmsan, K)),
656       TrackOrigins(getOptOrDefault(ClTrackOrigins, Kernel ? 2 : TO)),
657       Recover(getOptOrDefault(ClKeepGoing, Kernel || R)) {}
658 
659 PreservedAnalyses MemorySanitizerPass::run(Function &F,
660                                            FunctionAnalysisManager &FAM) {
661   MemorySanitizer Msan(*F.getParent(), Options);
662   if (Msan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F)))
663     return PreservedAnalyses::none();
664   return PreservedAnalyses::all();
665 }
666 
667 PreservedAnalyses MemorySanitizerPass::run(Module &M,
668                                            ModuleAnalysisManager &AM) {
669   if (Options.Kernel)
670     return PreservedAnalyses::all();
671   insertModuleCtor(M);
672   return PreservedAnalyses::none();
673 }
674 
675 char MemorySanitizerLegacyPass::ID = 0;
676 
677 INITIALIZE_PASS_BEGIN(MemorySanitizerLegacyPass, "msan",
678                       "MemorySanitizer: detects uninitialized reads.", false,
679                       false)
680 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
681 INITIALIZE_PASS_END(MemorySanitizerLegacyPass, "msan",
682                     "MemorySanitizer: detects uninitialized reads.", false,
683                     false)
684 
685 FunctionPass *
686 llvm::createMemorySanitizerLegacyPassPass(MemorySanitizerOptions Options) {
687   return new MemorySanitizerLegacyPass(Options);
688 }
689 
690 /// Create a non-const global initialized with the given string.
691 ///
692 /// Creates a writable global for Str so that we can pass it to the
693 /// run-time lib. Runtime uses first 4 bytes of the string to store the
694 /// frame ID, so the string needs to be mutable.
695 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
696                                                             StringRef Str) {
697   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
698   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
699                             GlobalValue::PrivateLinkage, StrConst, "");
700 }
701 
702 /// Create KMSAN API callbacks.
703 void MemorySanitizer::createKernelApi(Module &M) {
704   IRBuilder<> IRB(*C);
705 
706   // These will be initialized in insertKmsanPrologue().
707   RetvalTLS = nullptr;
708   RetvalOriginTLS = nullptr;
709   ParamTLS = nullptr;
710   ParamOriginTLS = nullptr;
711   VAArgTLS = nullptr;
712   VAArgOriginTLS = nullptr;
713   VAArgOverflowSizeTLS = nullptr;
714 
715   WarningFn = M.getOrInsertFunction("__msan_warning", IRB.getVoidTy(),
716                                     IRB.getInt32Ty());
717   // Requests the per-task context state (kmsan_context_state*) from the
718   // runtime library.
719   MsanContextStateTy = StructType::get(
720       ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8),
721       ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8),
722       ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8),
723       ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), /* va_arg_origin */
724       IRB.getInt64Ty(), ArrayType::get(OriginTy, kParamTLSSize / 4), OriginTy,
725       OriginTy);
726   MsanGetContextStateFn = M.getOrInsertFunction(
727       "__msan_get_context_state", PointerType::get(MsanContextStateTy, 0));
728 
729   Type *RetTy = StructType::get(PointerType::get(IRB.getInt8Ty(), 0),
730                                 PointerType::get(IRB.getInt32Ty(), 0));
731 
732   for (int ind = 0, size = 1; ind < 4; ind++, size <<= 1) {
733     std::string name_load =
734         "__msan_metadata_ptr_for_load_" + std::to_string(size);
735     std::string name_store =
736         "__msan_metadata_ptr_for_store_" + std::to_string(size);
737     MsanMetadataPtrForLoad_1_8[ind] = M.getOrInsertFunction(
738         name_load, RetTy, PointerType::get(IRB.getInt8Ty(), 0));
739     MsanMetadataPtrForStore_1_8[ind] = M.getOrInsertFunction(
740         name_store, RetTy, PointerType::get(IRB.getInt8Ty(), 0));
741   }
742 
743   MsanMetadataPtrForLoadN = M.getOrInsertFunction(
744       "__msan_metadata_ptr_for_load_n", RetTy,
745       PointerType::get(IRB.getInt8Ty(), 0), IRB.getInt64Ty());
746   MsanMetadataPtrForStoreN = M.getOrInsertFunction(
747       "__msan_metadata_ptr_for_store_n", RetTy,
748       PointerType::get(IRB.getInt8Ty(), 0), IRB.getInt64Ty());
749 
750   // Functions for poisoning and unpoisoning memory.
751   MsanPoisonAllocaFn =
752       M.getOrInsertFunction("__msan_poison_alloca", IRB.getVoidTy(),
753                             IRB.getInt8PtrTy(), IntptrTy, IRB.getInt8PtrTy());
754   MsanUnpoisonAllocaFn = M.getOrInsertFunction(
755       "__msan_unpoison_alloca", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy);
756 }
757 
758 static Constant *getOrInsertGlobal(Module &M, StringRef Name, Type *Ty) {
759   return M.getOrInsertGlobal(Name, Ty, [&] {
760     return new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
761                               nullptr, Name, nullptr,
762                               GlobalVariable::InitialExecTLSModel);
763   });
764 }
765 
766 /// Insert declarations for userspace-specific functions and globals.
767 void MemorySanitizer::createUserspaceApi(Module &M) {
768   IRBuilder<> IRB(*C);
769 
770   // Create the callback.
771   // FIXME: this function should have "Cold" calling conv,
772   // which is not yet implemented.
773   StringRef WarningFnName = Recover ? "__msan_warning_with_origin"
774                                     : "__msan_warning_with_origin_noreturn";
775   WarningFn =
776       M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), IRB.getInt32Ty());
777 
778   // Create the global TLS variables.
779   RetvalTLS =
780       getOrInsertGlobal(M, "__msan_retval_tls",
781                         ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8));
782 
783   RetvalOriginTLS = getOrInsertGlobal(M, "__msan_retval_origin_tls", OriginTy);
784 
785   ParamTLS =
786       getOrInsertGlobal(M, "__msan_param_tls",
787                         ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8));
788 
789   ParamOriginTLS =
790       getOrInsertGlobal(M, "__msan_param_origin_tls",
791                         ArrayType::get(OriginTy, kParamTLSSize / 4));
792 
793   VAArgTLS =
794       getOrInsertGlobal(M, "__msan_va_arg_tls",
795                         ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8));
796 
797   VAArgOriginTLS =
798       getOrInsertGlobal(M, "__msan_va_arg_origin_tls",
799                         ArrayType::get(OriginTy, kParamTLSSize / 4));
800 
801   VAArgOverflowSizeTLS =
802       getOrInsertGlobal(M, "__msan_va_arg_overflow_size_tls", IRB.getInt64Ty());
803 
804   for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
805        AccessSizeIndex++) {
806     unsigned AccessSize = 1 << AccessSizeIndex;
807     std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
808     SmallVector<std::pair<unsigned, Attribute>, 2> MaybeWarningFnAttrs;
809     MaybeWarningFnAttrs.push_back(std::make_pair(
810         AttributeList::FirstArgIndex, Attribute::get(*C, Attribute::ZExt)));
811     MaybeWarningFnAttrs.push_back(std::make_pair(
812         AttributeList::FirstArgIndex + 1, Attribute::get(*C, Attribute::ZExt)));
813     MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
814         FunctionName, AttributeList::get(*C, MaybeWarningFnAttrs),
815         IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8), IRB.getInt32Ty());
816 
817     FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
818     SmallVector<std::pair<unsigned, Attribute>, 2> MaybeStoreOriginFnAttrs;
819     MaybeStoreOriginFnAttrs.push_back(std::make_pair(
820         AttributeList::FirstArgIndex, Attribute::get(*C, Attribute::ZExt)));
821     MaybeStoreOriginFnAttrs.push_back(std::make_pair(
822         AttributeList::FirstArgIndex + 2, Attribute::get(*C, Attribute::ZExt)));
823     MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
824         FunctionName, AttributeList::get(*C, MaybeStoreOriginFnAttrs),
825         IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8), IRB.getInt8PtrTy(),
826         IRB.getInt32Ty());
827   }
828 
829   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
830     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
831     IRB.getInt8PtrTy(), IntptrTy);
832   MsanPoisonStackFn =
833       M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
834                             IRB.getInt8PtrTy(), IntptrTy);
835 }
836 
837 /// Insert extern declaration of runtime-provided functions and globals.
838 void MemorySanitizer::initializeCallbacks(Module &M) {
839   // Only do this once.
840   if (CallbacksInitialized)
841     return;
842 
843   IRBuilder<> IRB(*C);
844   // Initialize callbacks that are common for kernel and userspace
845   // instrumentation.
846   MsanChainOriginFn = M.getOrInsertFunction(
847     "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty());
848   MemmoveFn = M.getOrInsertFunction(
849     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
850     IRB.getInt8PtrTy(), IntptrTy);
851   MemcpyFn = M.getOrInsertFunction(
852     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
853     IntptrTy);
854   MemsetFn = M.getOrInsertFunction(
855     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
856     IntptrTy);
857 
858   MsanInstrumentAsmStoreFn =
859       M.getOrInsertFunction("__msan_instrument_asm_store", IRB.getVoidTy(),
860                             PointerType::get(IRB.getInt8Ty(), 0), IntptrTy);
861 
862   if (CompileKernel) {
863     createKernelApi(M);
864   } else {
865     createUserspaceApi(M);
866   }
867   CallbacksInitialized = true;
868 }
869 
870 FunctionCallee MemorySanitizer::getKmsanShadowOriginAccessFn(bool isStore,
871                                                              int size) {
872   FunctionCallee *Fns =
873       isStore ? MsanMetadataPtrForStore_1_8 : MsanMetadataPtrForLoad_1_8;
874   switch (size) {
875   case 1:
876     return Fns[0];
877   case 2:
878     return Fns[1];
879   case 4:
880     return Fns[2];
881   case 8:
882     return Fns[3];
883   default:
884     return nullptr;
885   }
886 }
887 
888 /// Module-level initialization.
889 ///
890 /// inserts a call to __msan_init to the module's constructor list.
891 void MemorySanitizer::initializeModule(Module &M) {
892   auto &DL = M.getDataLayout();
893 
894   bool ShadowPassed = ClShadowBase.getNumOccurrences() > 0;
895   bool OriginPassed = ClOriginBase.getNumOccurrences() > 0;
896   // Check the overrides first
897   if (ShadowPassed || OriginPassed) {
898     CustomMapParams.AndMask = ClAndMask;
899     CustomMapParams.XorMask = ClXorMask;
900     CustomMapParams.ShadowBase = ClShadowBase;
901     CustomMapParams.OriginBase = ClOriginBase;
902     MapParams = &CustomMapParams;
903   } else {
904     Triple TargetTriple(M.getTargetTriple());
905     switch (TargetTriple.getOS()) {
906       case Triple::FreeBSD:
907         switch (TargetTriple.getArch()) {
908           case Triple::x86_64:
909             MapParams = FreeBSD_X86_MemoryMapParams.bits64;
910             break;
911           case Triple::x86:
912             MapParams = FreeBSD_X86_MemoryMapParams.bits32;
913             break;
914           default:
915             report_fatal_error("unsupported architecture");
916         }
917         break;
918       case Triple::NetBSD:
919         switch (TargetTriple.getArch()) {
920           case Triple::x86_64:
921             MapParams = NetBSD_X86_MemoryMapParams.bits64;
922             break;
923           default:
924             report_fatal_error("unsupported architecture");
925         }
926         break;
927       case Triple::Linux:
928         switch (TargetTriple.getArch()) {
929           case Triple::x86_64:
930             MapParams = Linux_X86_MemoryMapParams.bits64;
931             break;
932           case Triple::x86:
933             MapParams = Linux_X86_MemoryMapParams.bits32;
934             break;
935           case Triple::mips64:
936           case Triple::mips64el:
937             MapParams = Linux_MIPS_MemoryMapParams.bits64;
938             break;
939           case Triple::ppc64:
940           case Triple::ppc64le:
941             MapParams = Linux_PowerPC_MemoryMapParams.bits64;
942             break;
943           case Triple::systemz:
944             MapParams = Linux_S390_MemoryMapParams.bits64;
945             break;
946           case Triple::aarch64:
947           case Triple::aarch64_be:
948             MapParams = Linux_ARM_MemoryMapParams.bits64;
949             break;
950           default:
951             report_fatal_error("unsupported architecture");
952         }
953         break;
954       default:
955         report_fatal_error("unsupported operating system");
956     }
957   }
958 
959   C = &(M.getContext());
960   IRBuilder<> IRB(*C);
961   IntptrTy = IRB.getIntPtrTy(DL);
962   OriginTy = IRB.getInt32Ty();
963 
964   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
965   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
966 
967   if (!CompileKernel) {
968     if (TrackOrigins)
969       M.getOrInsertGlobal("__msan_track_origins", IRB.getInt32Ty(), [&] {
970         return new GlobalVariable(
971             M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
972             IRB.getInt32(TrackOrigins), "__msan_track_origins");
973       });
974 
975     if (Recover)
976       M.getOrInsertGlobal("__msan_keep_going", IRB.getInt32Ty(), [&] {
977         return new GlobalVariable(M, IRB.getInt32Ty(), true,
978                                   GlobalValue::WeakODRLinkage,
979                                   IRB.getInt32(Recover), "__msan_keep_going");
980       });
981 }
982 }
983 
984 bool MemorySanitizerLegacyPass::doInitialization(Module &M) {
985   if (!Options.Kernel)
986     insertModuleCtor(M);
987   MSan.emplace(M, Options);
988   return true;
989 }
990 
991 namespace {
992 
993 /// A helper class that handles instrumentation of VarArg
994 /// functions on a particular platform.
995 ///
996 /// Implementations are expected to insert the instrumentation
997 /// necessary to propagate argument shadow through VarArg function
998 /// calls. Visit* methods are called during an InstVisitor pass over
999 /// the function, and should avoid creating new basic blocks. A new
1000 /// instance of this class is created for each instrumented function.
1001 struct VarArgHelper {
1002   virtual ~VarArgHelper() = default;
1003 
1004   /// Visit a CallBase.
1005   virtual void visitCallBase(CallBase &CB, IRBuilder<> &IRB) = 0;
1006 
1007   /// Visit a va_start call.
1008   virtual void visitVAStartInst(VAStartInst &I) = 0;
1009 
1010   /// Visit a va_copy call.
1011   virtual void visitVACopyInst(VACopyInst &I) = 0;
1012 
1013   /// Finalize function instrumentation.
1014   ///
1015   /// This method is called after visiting all interesting (see above)
1016   /// instructions in a function.
1017   virtual void finalizeInstrumentation() = 0;
1018 };
1019 
1020 struct MemorySanitizerVisitor;
1021 
1022 } // end anonymous namespace
1023 
1024 static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1025                                         MemorySanitizerVisitor &Visitor);
1026 
1027 static unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
1028   if (TypeSize <= 8) return 0;
1029   return Log2_32_Ceil((TypeSize + 7) / 8);
1030 }
1031 
1032 namespace {
1033 
1034 /// This class does all the work for a given function. Store and Load
1035 /// instructions store and load corresponding shadow and origin
1036 /// values. Most instructions propagate shadow from arguments to their
1037 /// return values. Certain instructions (most importantly, BranchInst)
1038 /// test their argument shadow and print reports (with a runtime call) if it's
1039 /// non-zero.
1040 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
1041   Function &F;
1042   MemorySanitizer &MS;
1043   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
1044   ValueMap<Value*, Value*> ShadowMap, OriginMap;
1045   std::unique_ptr<VarArgHelper> VAHelper;
1046   const TargetLibraryInfo *TLI;
1047   BasicBlock *ActualFnStart;
1048 
1049   // The following flags disable parts of MSan instrumentation based on
1050   // exclusion list contents and command-line options.
1051   bool InsertChecks;
1052   bool PropagateShadow;
1053   bool PoisonStack;
1054   bool PoisonUndef;
1055   bool CheckReturnValue;
1056 
1057   struct ShadowOriginAndInsertPoint {
1058     Value *Shadow;
1059     Value *Origin;
1060     Instruction *OrigIns;
1061 
1062     ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
1063       : Shadow(S), Origin(O), OrigIns(I) {}
1064   };
1065   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
1066   bool InstrumentLifetimeStart = ClHandleLifetimeIntrinsics;
1067   SmallSet<AllocaInst *, 16> AllocaSet;
1068   SmallVector<std::pair<IntrinsicInst *, AllocaInst *>, 16> LifetimeStartList;
1069   SmallVector<StoreInst *, 16> StoreList;
1070 
1071   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS,
1072                          const TargetLibraryInfo &TLI)
1073       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)), TLI(&TLI) {
1074     bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
1075     InsertChecks = SanitizeFunction;
1076     PropagateShadow = SanitizeFunction;
1077     PoisonStack = SanitizeFunction && ClPoisonStack;
1078     PoisonUndef = SanitizeFunction && ClPoisonUndef;
1079     // FIXME: Consider using SpecialCaseList to specify a list of functions that
1080     // must always return fully initialized values. For now, we hardcode "main".
1081     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
1082 
1083     MS.initializeCallbacks(*F.getParent());
1084     if (MS.CompileKernel)
1085       ActualFnStart = insertKmsanPrologue(F);
1086     else
1087       ActualFnStart = &F.getEntryBlock();
1088 
1089     LLVM_DEBUG(if (!InsertChecks) dbgs()
1090                << "MemorySanitizer is not inserting checks into '"
1091                << F.getName() << "'\n");
1092   }
1093 
1094   Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
1095     if (MS.TrackOrigins <= 1) return V;
1096     return IRB.CreateCall(MS.MsanChainOriginFn, V);
1097   }
1098 
1099   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
1100     const DataLayout &DL = F.getParent()->getDataLayout();
1101     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
1102     if (IntptrSize == kOriginSize) return Origin;
1103     assert(IntptrSize == kOriginSize * 2);
1104     Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
1105     return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
1106   }
1107 
1108   /// Fill memory range with the given origin value.
1109   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
1110                    unsigned Size, Align Alignment) {
1111     const DataLayout &DL = F.getParent()->getDataLayout();
1112     const Align IntptrAlignment = DL.getABITypeAlign(MS.IntptrTy);
1113     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
1114     assert(IntptrAlignment >= kMinOriginAlignment);
1115     assert(IntptrSize >= kOriginSize);
1116 
1117     unsigned Ofs = 0;
1118     Align CurrentAlignment = Alignment;
1119     if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
1120       Value *IntptrOrigin = originToIntptr(IRB, Origin);
1121       Value *IntptrOriginPtr =
1122           IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
1123       for (unsigned i = 0; i < Size / IntptrSize; ++i) {
1124         Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
1125                        : IntptrOriginPtr;
1126         IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
1127         Ofs += IntptrSize / kOriginSize;
1128         CurrentAlignment = IntptrAlignment;
1129       }
1130     }
1131 
1132     for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
1133       Value *GEP =
1134           i ? IRB.CreateConstGEP1_32(MS.OriginTy, OriginPtr, i) : OriginPtr;
1135       IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
1136       CurrentAlignment = kMinOriginAlignment;
1137     }
1138   }
1139 
1140   void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
1141                    Value *OriginPtr, Align Alignment, bool AsCall) {
1142     const DataLayout &DL = F.getParent()->getDataLayout();
1143     const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1144     unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
1145     if (Shadow->getType()->isAggregateType()) {
1146       paintOrigin(IRB, updateOrigin(Origin, IRB), OriginPtr, StoreSize,
1147                   OriginAlignment);
1148     } else {
1149       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
1150       if (auto *ConstantShadow = dyn_cast<Constant>(ConvertedShadow)) {
1151         if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
1152           paintOrigin(IRB, updateOrigin(Origin, IRB), OriginPtr, StoreSize,
1153                       OriginAlignment);
1154         return;
1155       }
1156 
1157       unsigned TypeSizeInBits =
1158           DL.getTypeSizeInBits(ConvertedShadow->getType());
1159       unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
1160       if (AsCall && SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) {
1161         FunctionCallee Fn = MS.MaybeStoreOriginFn[SizeIndex];
1162         Value *ConvertedShadow2 = IRB.CreateZExt(
1163             ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
1164         IRB.CreateCall(Fn, {ConvertedShadow2,
1165                             IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
1166                             Origin});
1167       } else {
1168         Value *Cmp = IRB.CreateICmpNE(
1169             ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
1170         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
1171             Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
1172         IRBuilder<> IRBNew(CheckTerm);
1173         paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), OriginPtr, StoreSize,
1174                     OriginAlignment);
1175       }
1176     }
1177   }
1178 
1179   void materializeStores(bool InstrumentWithCalls) {
1180     for (StoreInst *SI : StoreList) {
1181       IRBuilder<> IRB(SI);
1182       Value *Val = SI->getValueOperand();
1183       Value *Addr = SI->getPointerOperand();
1184       Value *Shadow = SI->isAtomic() ? getCleanShadow(Val) : getShadow(Val);
1185       Value *ShadowPtr, *OriginPtr;
1186       Type *ShadowTy = Shadow->getType();
1187       const Align Alignment = assumeAligned(SI->getAlignment());
1188       const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1189       std::tie(ShadowPtr, OriginPtr) =
1190           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ true);
1191 
1192       StoreInst *NewSI = IRB.CreateAlignedStore(Shadow, ShadowPtr, Alignment);
1193       LLVM_DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
1194       (void)NewSI;
1195 
1196       if (SI->isAtomic())
1197         SI->setOrdering(addReleaseOrdering(SI->getOrdering()));
1198 
1199       if (MS.TrackOrigins && !SI->isAtomic())
1200         storeOrigin(IRB, Addr, Shadow, getOrigin(Val), OriginPtr,
1201                     OriginAlignment, InstrumentWithCalls);
1202     }
1203   }
1204 
1205   /// Helper function to insert a warning at IRB's current insert point.
1206   void insertWarningFn(IRBuilder<> &IRB, Value *Origin) {
1207     if (!Origin)
1208       Origin = (Value *)IRB.getInt32(0);
1209     assert(Origin->getType()->isIntegerTy());
1210     IRB.CreateCall(MS.WarningFn, Origin)->setCannotMerge();
1211     // FIXME: Insert UnreachableInst if !MS.Recover?
1212     // This may invalidate some of the following checks and needs to be done
1213     // at the very end.
1214   }
1215 
1216   void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
1217                            bool AsCall) {
1218     IRBuilder<> IRB(OrigIns);
1219     LLVM_DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
1220     Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
1221     LLVM_DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
1222 
1223     if (auto *ConstantShadow = dyn_cast<Constant>(ConvertedShadow)) {
1224       if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
1225         insertWarningFn(IRB, Origin);
1226       }
1227       return;
1228     }
1229 
1230     const DataLayout &DL = OrigIns->getModule()->getDataLayout();
1231 
1232     unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
1233     unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
1234     if (AsCall && SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) {
1235       FunctionCallee Fn = MS.MaybeWarningFn[SizeIndex];
1236       Value *ConvertedShadow2 =
1237           IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
1238       IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
1239                                                 ? Origin
1240                                                 : (Value *)IRB.getInt32(0)});
1241     } else {
1242       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
1243                                     getCleanShadow(ConvertedShadow), "_mscmp");
1244       Instruction *CheckTerm = SplitBlockAndInsertIfThen(
1245           Cmp, OrigIns,
1246           /* Unreachable */ !MS.Recover, MS.ColdCallWeights);
1247 
1248       IRB.SetInsertPoint(CheckTerm);
1249       insertWarningFn(IRB, Origin);
1250       LLVM_DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
1251     }
1252   }
1253 
1254   void materializeChecks(bool InstrumentWithCalls) {
1255     for (const auto &ShadowData : InstrumentationList) {
1256       Instruction *OrigIns = ShadowData.OrigIns;
1257       Value *Shadow = ShadowData.Shadow;
1258       Value *Origin = ShadowData.Origin;
1259       materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
1260     }
1261     LLVM_DEBUG(dbgs() << "DONE:\n" << F);
1262   }
1263 
1264   BasicBlock *insertKmsanPrologue(Function &F) {
1265     BasicBlock *ret =
1266         SplitBlock(&F.getEntryBlock(), F.getEntryBlock().getFirstNonPHI());
1267     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1268     Value *ContextState = IRB.CreateCall(MS.MsanGetContextStateFn, {});
1269     Constant *Zero = IRB.getInt32(0);
1270     MS.ParamTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1271                                 {Zero, IRB.getInt32(0)}, "param_shadow");
1272     MS.RetvalTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1273                                  {Zero, IRB.getInt32(1)}, "retval_shadow");
1274     MS.VAArgTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1275                                 {Zero, IRB.getInt32(2)}, "va_arg_shadow");
1276     MS.VAArgOriginTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1277                                       {Zero, IRB.getInt32(3)}, "va_arg_origin");
1278     MS.VAArgOverflowSizeTLS =
1279         IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1280                       {Zero, IRB.getInt32(4)}, "va_arg_overflow_size");
1281     MS.ParamOriginTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1282                                       {Zero, IRB.getInt32(5)}, "param_origin");
1283     MS.RetvalOriginTLS =
1284         IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1285                       {Zero, IRB.getInt32(6)}, "retval_origin");
1286     return ret;
1287   }
1288 
1289   /// Add MemorySanitizer instrumentation to a function.
1290   bool runOnFunction() {
1291     // In the presence of unreachable blocks, we may see Phi nodes with
1292     // incoming nodes from such blocks. Since InstVisitor skips unreachable
1293     // blocks, such nodes will not have any shadow value associated with them.
1294     // It's easier to remove unreachable blocks than deal with missing shadow.
1295     removeUnreachableBlocks(F);
1296 
1297     // Iterate all BBs in depth-first order and create shadow instructions
1298     // for all instructions (where applicable).
1299     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
1300     for (BasicBlock *BB : depth_first(ActualFnStart))
1301       visit(*BB);
1302 
1303     // Finalize PHI nodes.
1304     for (PHINode *PN : ShadowPHINodes) {
1305       PHINode *PNS = cast<PHINode>(getShadow(PN));
1306       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
1307       size_t NumValues = PN->getNumIncomingValues();
1308       for (size_t v = 0; v < NumValues; v++) {
1309         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
1310         if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
1311       }
1312     }
1313 
1314     VAHelper->finalizeInstrumentation();
1315 
1316     // Poison llvm.lifetime.start intrinsics, if we haven't fallen back to
1317     // instrumenting only allocas.
1318     if (InstrumentLifetimeStart) {
1319       for (auto Item : LifetimeStartList) {
1320         instrumentAlloca(*Item.second, Item.first);
1321         AllocaSet.erase(Item.second);
1322       }
1323     }
1324     // Poison the allocas for which we didn't instrument the corresponding
1325     // lifetime intrinsics.
1326     for (AllocaInst *AI : AllocaSet)
1327       instrumentAlloca(*AI);
1328 
1329     bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
1330                                InstrumentationList.size() + StoreList.size() >
1331                                    (unsigned)ClInstrumentationWithCallThreshold;
1332 
1333     // Insert shadow value checks.
1334     materializeChecks(InstrumentWithCalls);
1335 
1336     // Delayed instrumentation of StoreInst.
1337     // This may not add new address checks.
1338     materializeStores(InstrumentWithCalls);
1339 
1340     return true;
1341   }
1342 
1343   /// Compute the shadow type that corresponds to a given Value.
1344   Type *getShadowTy(Value *V) {
1345     return getShadowTy(V->getType());
1346   }
1347 
1348   /// Compute the shadow type that corresponds to a given Type.
1349   Type *getShadowTy(Type *OrigTy) {
1350     if (!OrigTy->isSized()) {
1351       return nullptr;
1352     }
1353     // For integer type, shadow is the same as the original type.
1354     // This may return weird-sized types like i1.
1355     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
1356       return IT;
1357     const DataLayout &DL = F.getParent()->getDataLayout();
1358     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
1359       uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
1360       return FixedVectorType::get(IntegerType::get(*MS.C, EltSize),
1361                                   cast<FixedVectorType>(VT)->getNumElements());
1362     }
1363     if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
1364       return ArrayType::get(getShadowTy(AT->getElementType()),
1365                             AT->getNumElements());
1366     }
1367     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
1368       SmallVector<Type*, 4> Elements;
1369       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1370         Elements.push_back(getShadowTy(ST->getElementType(i)));
1371       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
1372       LLVM_DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
1373       return Res;
1374     }
1375     uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
1376     return IntegerType::get(*MS.C, TypeSize);
1377   }
1378 
1379   /// Flatten a vector type.
1380   Type *getShadowTyNoVec(Type *ty) {
1381     if (VectorType *vt = dyn_cast<VectorType>(ty))
1382       return IntegerType::get(*MS.C,
1383                               vt->getPrimitiveSizeInBits().getFixedSize());
1384     return ty;
1385   }
1386 
1387   /// Convert a shadow value to it's flattened variant.
1388   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
1389     Type *Ty = V->getType();
1390     Type *NoVecTy = getShadowTyNoVec(Ty);
1391     if (Ty == NoVecTy) return V;
1392     return IRB.CreateBitCast(V, NoVecTy);
1393   }
1394 
1395   /// Compute the integer shadow offset that corresponds to a given
1396   /// application address.
1397   ///
1398   /// Offset = (Addr & ~AndMask) ^ XorMask
1399   Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
1400     Value *OffsetLong = IRB.CreatePointerCast(Addr, MS.IntptrTy);
1401 
1402     uint64_t AndMask = MS.MapParams->AndMask;
1403     if (AndMask)
1404       OffsetLong =
1405           IRB.CreateAnd(OffsetLong, ConstantInt::get(MS.IntptrTy, ~AndMask));
1406 
1407     uint64_t XorMask = MS.MapParams->XorMask;
1408     if (XorMask)
1409       OffsetLong =
1410           IRB.CreateXor(OffsetLong, ConstantInt::get(MS.IntptrTy, XorMask));
1411     return OffsetLong;
1412   }
1413 
1414   /// Compute the shadow and origin addresses corresponding to a given
1415   /// application address.
1416   ///
1417   /// Shadow = ShadowBase + Offset
1418   /// Origin = (OriginBase + Offset) & ~3ULL
1419   std::pair<Value *, Value *>
1420   getShadowOriginPtrUserspace(Value *Addr, IRBuilder<> &IRB, Type *ShadowTy,
1421                               MaybeAlign Alignment) {
1422     Value *ShadowOffset = getShadowPtrOffset(Addr, IRB);
1423     Value *ShadowLong = ShadowOffset;
1424     uint64_t ShadowBase = MS.MapParams->ShadowBase;
1425     if (ShadowBase != 0) {
1426       ShadowLong =
1427         IRB.CreateAdd(ShadowLong,
1428                       ConstantInt::get(MS.IntptrTy, ShadowBase));
1429     }
1430     Value *ShadowPtr =
1431         IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
1432     Value *OriginPtr = nullptr;
1433     if (MS.TrackOrigins) {
1434       Value *OriginLong = ShadowOffset;
1435       uint64_t OriginBase = MS.MapParams->OriginBase;
1436       if (OriginBase != 0)
1437         OriginLong = IRB.CreateAdd(OriginLong,
1438                                    ConstantInt::get(MS.IntptrTy, OriginBase));
1439       if (!Alignment || *Alignment < kMinOriginAlignment) {
1440         uint64_t Mask = kMinOriginAlignment.value() - 1;
1441         OriginLong =
1442             IRB.CreateAnd(OriginLong, ConstantInt::get(MS.IntptrTy, ~Mask));
1443       }
1444       OriginPtr =
1445           IRB.CreateIntToPtr(OriginLong, PointerType::get(MS.OriginTy, 0));
1446     }
1447     return std::make_pair(ShadowPtr, OriginPtr);
1448   }
1449 
1450   std::pair<Value *, Value *> getShadowOriginPtrKernel(Value *Addr,
1451                                                        IRBuilder<> &IRB,
1452                                                        Type *ShadowTy,
1453                                                        bool isStore) {
1454     Value *ShadowOriginPtrs;
1455     const DataLayout &DL = F.getParent()->getDataLayout();
1456     int Size = DL.getTypeStoreSize(ShadowTy);
1457 
1458     FunctionCallee Getter = MS.getKmsanShadowOriginAccessFn(isStore, Size);
1459     Value *AddrCast =
1460         IRB.CreatePointerCast(Addr, PointerType::get(IRB.getInt8Ty(), 0));
1461     if (Getter) {
1462       ShadowOriginPtrs = IRB.CreateCall(Getter, AddrCast);
1463     } else {
1464       Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size);
1465       ShadowOriginPtrs = IRB.CreateCall(isStore ? MS.MsanMetadataPtrForStoreN
1466                                                 : MS.MsanMetadataPtrForLoadN,
1467                                         {AddrCast, SizeVal});
1468     }
1469     Value *ShadowPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 0);
1470     ShadowPtr = IRB.CreatePointerCast(ShadowPtr, PointerType::get(ShadowTy, 0));
1471     Value *OriginPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 1);
1472 
1473     return std::make_pair(ShadowPtr, OriginPtr);
1474   }
1475 
1476   std::pair<Value *, Value *> getShadowOriginPtr(Value *Addr, IRBuilder<> &IRB,
1477                                                  Type *ShadowTy,
1478                                                  MaybeAlign Alignment,
1479                                                  bool isStore) {
1480     if (MS.CompileKernel)
1481       return getShadowOriginPtrKernel(Addr, IRB, ShadowTy, isStore);
1482     return getShadowOriginPtrUserspace(Addr, IRB, ShadowTy, Alignment);
1483   }
1484 
1485   /// Compute the shadow address for a given function argument.
1486   ///
1487   /// Shadow = ParamTLS+ArgOffset.
1488   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
1489                                  int ArgOffset) {
1490     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
1491     if (ArgOffset)
1492       Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1493     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
1494                               "_msarg");
1495   }
1496 
1497   /// Compute the origin address for a given function argument.
1498   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
1499                                  int ArgOffset) {
1500     if (!MS.TrackOrigins)
1501       return nullptr;
1502     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
1503     if (ArgOffset)
1504       Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1505     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
1506                               "_msarg_o");
1507   }
1508 
1509   /// Compute the shadow address for a retval.
1510   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
1511     return IRB.CreatePointerCast(MS.RetvalTLS,
1512                                  PointerType::get(getShadowTy(A), 0),
1513                                  "_msret");
1514   }
1515 
1516   /// Compute the origin address for a retval.
1517   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
1518     // We keep a single origin for the entire retval. Might be too optimistic.
1519     return MS.RetvalOriginTLS;
1520   }
1521 
1522   /// Set SV to be the shadow value for V.
1523   void setShadow(Value *V, Value *SV) {
1524     assert(!ShadowMap.count(V) && "Values may only have one shadow");
1525     ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
1526   }
1527 
1528   /// Set Origin to be the origin value for V.
1529   void setOrigin(Value *V, Value *Origin) {
1530     if (!MS.TrackOrigins) return;
1531     assert(!OriginMap.count(V) && "Values may only have one origin");
1532     LLVM_DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
1533     OriginMap[V] = Origin;
1534   }
1535 
1536   Constant *getCleanShadow(Type *OrigTy) {
1537     Type *ShadowTy = getShadowTy(OrigTy);
1538     if (!ShadowTy)
1539       return nullptr;
1540     return Constant::getNullValue(ShadowTy);
1541   }
1542 
1543   /// Create a clean shadow value for a given value.
1544   ///
1545   /// Clean shadow (all zeroes) means all bits of the value are defined
1546   /// (initialized).
1547   Constant *getCleanShadow(Value *V) {
1548     return getCleanShadow(V->getType());
1549   }
1550 
1551   /// Create a dirty shadow of a given shadow type.
1552   Constant *getPoisonedShadow(Type *ShadowTy) {
1553     assert(ShadowTy);
1554     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
1555       return Constant::getAllOnesValue(ShadowTy);
1556     if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
1557       SmallVector<Constant *, 4> Vals(AT->getNumElements(),
1558                                       getPoisonedShadow(AT->getElementType()));
1559       return ConstantArray::get(AT, Vals);
1560     }
1561     if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
1562       SmallVector<Constant *, 4> Vals;
1563       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1564         Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1565       return ConstantStruct::get(ST, Vals);
1566     }
1567     llvm_unreachable("Unexpected shadow type");
1568   }
1569 
1570   /// Create a dirty shadow for a given value.
1571   Constant *getPoisonedShadow(Value *V) {
1572     Type *ShadowTy = getShadowTy(V);
1573     if (!ShadowTy)
1574       return nullptr;
1575     return getPoisonedShadow(ShadowTy);
1576   }
1577 
1578   /// Create a clean (zero) origin.
1579   Value *getCleanOrigin() {
1580     return Constant::getNullValue(MS.OriginTy);
1581   }
1582 
1583   /// Get the shadow value for a given Value.
1584   ///
1585   /// This function either returns the value set earlier with setShadow,
1586   /// or extracts if from ParamTLS (for function arguments).
1587   Value *getShadow(Value *V) {
1588     if (!PropagateShadow) return getCleanShadow(V);
1589     if (Instruction *I = dyn_cast<Instruction>(V)) {
1590       if (I->getMetadata("nosanitize"))
1591         return getCleanShadow(V);
1592       // For instructions the shadow is already stored in the map.
1593       Value *Shadow = ShadowMap[V];
1594       if (!Shadow) {
1595         LLVM_DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
1596         (void)I;
1597         assert(Shadow && "No shadow for a value");
1598       }
1599       return Shadow;
1600     }
1601     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
1602       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
1603       LLVM_DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
1604       (void)U;
1605       return AllOnes;
1606     }
1607     if (Argument *A = dyn_cast<Argument>(V)) {
1608       // For arguments we compute the shadow on demand and store it in the map.
1609       Value **ShadowPtr = &ShadowMap[V];
1610       if (*ShadowPtr)
1611         return *ShadowPtr;
1612       Function *F = A->getParent();
1613       IRBuilder<> EntryIRB(ActualFnStart->getFirstNonPHI());
1614       unsigned ArgOffset = 0;
1615       const DataLayout &DL = F->getParent()->getDataLayout();
1616       for (auto &FArg : F->args()) {
1617         if (!FArg.getType()->isSized()) {
1618           LLVM_DEBUG(dbgs() << "Arg is not sized\n");
1619           continue;
1620         }
1621         unsigned Size =
1622             FArg.hasByValAttr()
1623                 ? DL.getTypeAllocSize(FArg.getParamByValType())
1624                 : DL.getTypeAllocSize(FArg.getType());
1625         if (A == &FArg) {
1626           bool Overflow = ArgOffset + Size > kParamTLSSize;
1627           Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1628           if (FArg.hasByValAttr()) {
1629             // ByVal pointer itself has clean shadow. We copy the actual
1630             // argument shadow to the underlying memory.
1631             // Figure out maximal valid memcpy alignment.
1632             const Align ArgAlign = DL.getValueOrABITypeAlignment(
1633                 MaybeAlign(FArg.getParamAlignment()), FArg.getParamByValType());
1634             Value *CpShadowPtr =
1635                 getShadowOriginPtr(V, EntryIRB, EntryIRB.getInt8Ty(), ArgAlign,
1636                                    /*isStore*/ true)
1637                     .first;
1638             // TODO(glider): need to copy origins.
1639             if (Overflow) {
1640               // ParamTLS overflow.
1641               EntryIRB.CreateMemSet(
1642                   CpShadowPtr, Constant::getNullValue(EntryIRB.getInt8Ty()),
1643                   Size, ArgAlign);
1644             } else {
1645               const Align CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1646               Value *Cpy = EntryIRB.CreateMemCpy(CpShadowPtr, CopyAlign, Base,
1647                                                  CopyAlign, Size);
1648               LLVM_DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
1649               (void)Cpy;
1650             }
1651             *ShadowPtr = getCleanShadow(V);
1652           } else {
1653             if (Overflow) {
1654               // ParamTLS overflow.
1655               *ShadowPtr = getCleanShadow(V);
1656             } else {
1657               *ShadowPtr = EntryIRB.CreateAlignedLoad(getShadowTy(&FArg), Base,
1658                                                       kShadowTLSAlignment);
1659             }
1660           }
1661           LLVM_DEBUG(dbgs()
1662                      << "  ARG:    " << FArg << " ==> " << **ShadowPtr << "\n");
1663           if (MS.TrackOrigins && !Overflow) {
1664             Value *OriginPtr =
1665                 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
1666             setOrigin(A, EntryIRB.CreateLoad(MS.OriginTy, OriginPtr));
1667           } else {
1668             setOrigin(A, getCleanOrigin());
1669           }
1670         }
1671         ArgOffset += alignTo(Size, kShadowTLSAlignment);
1672       }
1673       assert(*ShadowPtr && "Could not find shadow for an argument");
1674       return *ShadowPtr;
1675     }
1676     // For everything else the shadow is zero.
1677     return getCleanShadow(V);
1678   }
1679 
1680   /// Get the shadow for i-th argument of the instruction I.
1681   Value *getShadow(Instruction *I, int i) {
1682     return getShadow(I->getOperand(i));
1683   }
1684 
1685   /// Get the origin for a value.
1686   Value *getOrigin(Value *V) {
1687     if (!MS.TrackOrigins) return nullptr;
1688     if (!PropagateShadow) return getCleanOrigin();
1689     if (isa<Constant>(V)) return getCleanOrigin();
1690     assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1691            "Unexpected value type in getOrigin()");
1692     if (Instruction *I = dyn_cast<Instruction>(V)) {
1693       if (I->getMetadata("nosanitize"))
1694         return getCleanOrigin();
1695     }
1696     Value *Origin = OriginMap[V];
1697     assert(Origin && "Missing origin");
1698     return Origin;
1699   }
1700 
1701   /// Get the origin for i-th argument of the instruction I.
1702   Value *getOrigin(Instruction *I, int i) {
1703     return getOrigin(I->getOperand(i));
1704   }
1705 
1706   /// Remember the place where a shadow check should be inserted.
1707   ///
1708   /// This location will be later instrumented with a check that will print a
1709   /// UMR warning in runtime if the shadow value is not 0.
1710   void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1711     assert(Shadow);
1712     if (!InsertChecks) return;
1713 #ifndef NDEBUG
1714     Type *ShadowTy = Shadow->getType();
1715     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1716            "Can only insert checks for integer and vector shadow types");
1717 #endif
1718     InstrumentationList.push_back(
1719         ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1720   }
1721 
1722   /// Remember the place where a shadow check should be inserted.
1723   ///
1724   /// This location will be later instrumented with a check that will print a
1725   /// UMR warning in runtime if the value is not fully defined.
1726   void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1727     assert(Val);
1728     Value *Shadow, *Origin;
1729     if (ClCheckConstantShadow) {
1730       Shadow = getShadow(Val);
1731       if (!Shadow) return;
1732       Origin = getOrigin(Val);
1733     } else {
1734       Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1735       if (!Shadow) return;
1736       Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1737     }
1738     insertShadowCheck(Shadow, Origin, OrigIns);
1739   }
1740 
1741   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1742     switch (a) {
1743       case AtomicOrdering::NotAtomic:
1744         return AtomicOrdering::NotAtomic;
1745       case AtomicOrdering::Unordered:
1746       case AtomicOrdering::Monotonic:
1747       case AtomicOrdering::Release:
1748         return AtomicOrdering::Release;
1749       case AtomicOrdering::Acquire:
1750       case AtomicOrdering::AcquireRelease:
1751         return AtomicOrdering::AcquireRelease;
1752       case AtomicOrdering::SequentiallyConsistent:
1753         return AtomicOrdering::SequentiallyConsistent;
1754     }
1755     llvm_unreachable("Unknown ordering");
1756   }
1757 
1758   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1759     switch (a) {
1760       case AtomicOrdering::NotAtomic:
1761         return AtomicOrdering::NotAtomic;
1762       case AtomicOrdering::Unordered:
1763       case AtomicOrdering::Monotonic:
1764       case AtomicOrdering::Acquire:
1765         return AtomicOrdering::Acquire;
1766       case AtomicOrdering::Release:
1767       case AtomicOrdering::AcquireRelease:
1768         return AtomicOrdering::AcquireRelease;
1769       case AtomicOrdering::SequentiallyConsistent:
1770         return AtomicOrdering::SequentiallyConsistent;
1771     }
1772     llvm_unreachable("Unknown ordering");
1773   }
1774 
1775   // ------------------- Visitors.
1776   using InstVisitor<MemorySanitizerVisitor>::visit;
1777   void visit(Instruction &I) {
1778     if (!I.getMetadata("nosanitize"))
1779       InstVisitor<MemorySanitizerVisitor>::visit(I);
1780   }
1781 
1782   /// Instrument LoadInst
1783   ///
1784   /// Loads the corresponding shadow and (optionally) origin.
1785   /// Optionally, checks that the load address is fully defined.
1786   void visitLoadInst(LoadInst &I) {
1787     assert(I.getType()->isSized() && "Load type must have size");
1788     assert(!I.getMetadata("nosanitize"));
1789     IRBuilder<> IRB(I.getNextNode());
1790     Type *ShadowTy = getShadowTy(&I);
1791     Value *Addr = I.getPointerOperand();
1792     Value *ShadowPtr = nullptr, *OriginPtr = nullptr;
1793     const Align Alignment = assumeAligned(I.getAlignment());
1794     if (PropagateShadow) {
1795       std::tie(ShadowPtr, OriginPtr) =
1796           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
1797       setShadow(&I,
1798                 IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Alignment, "_msld"));
1799     } else {
1800       setShadow(&I, getCleanShadow(&I));
1801     }
1802 
1803     if (ClCheckAccessAddress)
1804       insertShadowCheck(I.getPointerOperand(), &I);
1805 
1806     if (I.isAtomic())
1807       I.setOrdering(addAcquireOrdering(I.getOrdering()));
1808 
1809     if (MS.TrackOrigins) {
1810       if (PropagateShadow) {
1811         const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1812         setOrigin(
1813             &I, IRB.CreateAlignedLoad(MS.OriginTy, OriginPtr, OriginAlignment));
1814       } else {
1815         setOrigin(&I, getCleanOrigin());
1816       }
1817     }
1818   }
1819 
1820   /// Instrument StoreInst
1821   ///
1822   /// Stores the corresponding shadow and (optionally) origin.
1823   /// Optionally, checks that the store address is fully defined.
1824   void visitStoreInst(StoreInst &I) {
1825     StoreList.push_back(&I);
1826     if (ClCheckAccessAddress)
1827       insertShadowCheck(I.getPointerOperand(), &I);
1828   }
1829 
1830   void handleCASOrRMW(Instruction &I) {
1831     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1832 
1833     IRBuilder<> IRB(&I);
1834     Value *Addr = I.getOperand(0);
1835     Value *ShadowPtr = getShadowOriginPtr(Addr, IRB, I.getType(), Align(1),
1836                                           /*isStore*/ true)
1837                            .first;
1838 
1839     if (ClCheckAccessAddress)
1840       insertShadowCheck(Addr, &I);
1841 
1842     // Only test the conditional argument of cmpxchg instruction.
1843     // The other argument can potentially be uninitialized, but we can not
1844     // detect this situation reliably without possible false positives.
1845     if (isa<AtomicCmpXchgInst>(I))
1846       insertShadowCheck(I.getOperand(1), &I);
1847 
1848     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1849 
1850     setShadow(&I, getCleanShadow(&I));
1851     setOrigin(&I, getCleanOrigin());
1852   }
1853 
1854   void visitAtomicRMWInst(AtomicRMWInst &I) {
1855     handleCASOrRMW(I);
1856     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1857   }
1858 
1859   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1860     handleCASOrRMW(I);
1861     I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1862   }
1863 
1864   // Vector manipulation.
1865   void visitExtractElementInst(ExtractElementInst &I) {
1866     insertShadowCheck(I.getOperand(1), &I);
1867     IRBuilder<> IRB(&I);
1868     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1869               "_msprop"));
1870     setOrigin(&I, getOrigin(&I, 0));
1871   }
1872 
1873   void visitInsertElementInst(InsertElementInst &I) {
1874     insertShadowCheck(I.getOperand(2), &I);
1875     IRBuilder<> IRB(&I);
1876     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1877               I.getOperand(2), "_msprop"));
1878     setOriginForNaryOp(I);
1879   }
1880 
1881   void visitShuffleVectorInst(ShuffleVectorInst &I) {
1882     IRBuilder<> IRB(&I);
1883     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1884                                           I.getShuffleMask(), "_msprop"));
1885     setOriginForNaryOp(I);
1886   }
1887 
1888   // Casts.
1889   void visitSExtInst(SExtInst &I) {
1890     IRBuilder<> IRB(&I);
1891     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1892     setOrigin(&I, getOrigin(&I, 0));
1893   }
1894 
1895   void visitZExtInst(ZExtInst &I) {
1896     IRBuilder<> IRB(&I);
1897     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1898     setOrigin(&I, getOrigin(&I, 0));
1899   }
1900 
1901   void visitTruncInst(TruncInst &I) {
1902     IRBuilder<> IRB(&I);
1903     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1904     setOrigin(&I, getOrigin(&I, 0));
1905   }
1906 
1907   void visitBitCastInst(BitCastInst &I) {
1908     // Special case: if this is the bitcast (there is exactly 1 allowed) between
1909     // a musttail call and a ret, don't instrument. New instructions are not
1910     // allowed after a musttail call.
1911     if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
1912       if (CI->isMustTailCall())
1913         return;
1914     IRBuilder<> IRB(&I);
1915     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1916     setOrigin(&I, getOrigin(&I, 0));
1917   }
1918 
1919   void visitPtrToIntInst(PtrToIntInst &I) {
1920     IRBuilder<> IRB(&I);
1921     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1922              "_msprop_ptrtoint"));
1923     setOrigin(&I, getOrigin(&I, 0));
1924   }
1925 
1926   void visitIntToPtrInst(IntToPtrInst &I) {
1927     IRBuilder<> IRB(&I);
1928     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1929              "_msprop_inttoptr"));
1930     setOrigin(&I, getOrigin(&I, 0));
1931   }
1932 
1933   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1934   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1935   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1936   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1937   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1938   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1939 
1940   /// Propagate shadow for bitwise AND.
1941   ///
1942   /// This code is exact, i.e. if, for example, a bit in the left argument
1943   /// is defined and 0, then neither the value not definedness of the
1944   /// corresponding bit in B don't affect the resulting shadow.
1945   void visitAnd(BinaryOperator &I) {
1946     IRBuilder<> IRB(&I);
1947     //  "And" of 0 and a poisoned value results in unpoisoned value.
1948     //  1&1 => 1;     0&1 => 0;     p&1 => p;
1949     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
1950     //  1&p => p;     0&p => 0;     p&p => p;
1951     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1952     Value *S1 = getShadow(&I, 0);
1953     Value *S2 = getShadow(&I, 1);
1954     Value *V1 = I.getOperand(0);
1955     Value *V2 = I.getOperand(1);
1956     if (V1->getType() != S1->getType()) {
1957       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1958       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1959     }
1960     Value *S1S2 = IRB.CreateAnd(S1, S2);
1961     Value *V1S2 = IRB.CreateAnd(V1, S2);
1962     Value *S1V2 = IRB.CreateAnd(S1, V2);
1963     setShadow(&I, IRB.CreateOr({S1S2, V1S2, S1V2}));
1964     setOriginForNaryOp(I);
1965   }
1966 
1967   void visitOr(BinaryOperator &I) {
1968     IRBuilder<> IRB(&I);
1969     //  "Or" of 1 and a poisoned value results in unpoisoned value.
1970     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
1971     //  1|0 => 1;     0|0 => 0;     p|0 => p;
1972     //  1|p => 1;     0|p => p;     p|p => p;
1973     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1974     Value *S1 = getShadow(&I, 0);
1975     Value *S2 = getShadow(&I, 1);
1976     Value *V1 = IRB.CreateNot(I.getOperand(0));
1977     Value *V2 = IRB.CreateNot(I.getOperand(1));
1978     if (V1->getType() != S1->getType()) {
1979       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1980       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1981     }
1982     Value *S1S2 = IRB.CreateAnd(S1, S2);
1983     Value *V1S2 = IRB.CreateAnd(V1, S2);
1984     Value *S1V2 = IRB.CreateAnd(S1, V2);
1985     setShadow(&I, IRB.CreateOr({S1S2, V1S2, S1V2}));
1986     setOriginForNaryOp(I);
1987   }
1988 
1989   /// Default propagation of shadow and/or origin.
1990   ///
1991   /// This class implements the general case of shadow propagation, used in all
1992   /// cases where we don't know and/or don't care about what the operation
1993   /// actually does. It converts all input shadow values to a common type
1994   /// (extending or truncating as necessary), and bitwise OR's them.
1995   ///
1996   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1997   /// fully initialized), and less prone to false positives.
1998   ///
1999   /// This class also implements the general case of origin propagation. For a
2000   /// Nary operation, result origin is set to the origin of an argument that is
2001   /// not entirely initialized. If there is more than one such arguments, the
2002   /// rightmost of them is picked. It does not matter which one is picked if all
2003   /// arguments are initialized.
2004   template <bool CombineShadow>
2005   class Combiner {
2006     Value *Shadow = nullptr;
2007     Value *Origin = nullptr;
2008     IRBuilder<> &IRB;
2009     MemorySanitizerVisitor *MSV;
2010 
2011   public:
2012     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB)
2013         : IRB(IRB), MSV(MSV) {}
2014 
2015     /// Add a pair of shadow and origin values to the mix.
2016     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
2017       if (CombineShadow) {
2018         assert(OpShadow);
2019         if (!Shadow)
2020           Shadow = OpShadow;
2021         else {
2022           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
2023           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
2024         }
2025       }
2026 
2027       if (MSV->MS.TrackOrigins) {
2028         assert(OpOrigin);
2029         if (!Origin) {
2030           Origin = OpOrigin;
2031         } else {
2032           Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
2033           // No point in adding something that might result in 0 origin value.
2034           if (!ConstOrigin || !ConstOrigin->isNullValue()) {
2035             Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
2036             Value *Cond =
2037                 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
2038             Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
2039           }
2040         }
2041       }
2042       return *this;
2043     }
2044 
2045     /// Add an application value to the mix.
2046     Combiner &Add(Value *V) {
2047       Value *OpShadow = MSV->getShadow(V);
2048       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
2049       return Add(OpShadow, OpOrigin);
2050     }
2051 
2052     /// Set the current combined values as the given instruction's shadow
2053     /// and origin.
2054     void Done(Instruction *I) {
2055       if (CombineShadow) {
2056         assert(Shadow);
2057         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
2058         MSV->setShadow(I, Shadow);
2059       }
2060       if (MSV->MS.TrackOrigins) {
2061         assert(Origin);
2062         MSV->setOrigin(I, Origin);
2063       }
2064     }
2065   };
2066 
2067   using ShadowAndOriginCombiner = Combiner<true>;
2068   using OriginCombiner = Combiner<false>;
2069 
2070   /// Propagate origin for arbitrary operation.
2071   void setOriginForNaryOp(Instruction &I) {
2072     if (!MS.TrackOrigins) return;
2073     IRBuilder<> IRB(&I);
2074     OriginCombiner OC(this, IRB);
2075     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
2076       OC.Add(OI->get());
2077     OC.Done(&I);
2078   }
2079 
2080   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
2081     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
2082            "Vector of pointers is not a valid shadow type");
2083     return Ty->isVectorTy() ? cast<FixedVectorType>(Ty)->getNumElements() *
2084                                   Ty->getScalarSizeInBits()
2085                             : Ty->getPrimitiveSizeInBits();
2086   }
2087 
2088   /// Cast between two shadow types, extending or truncating as
2089   /// necessary.
2090   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
2091                           bool Signed = false) {
2092     Type *srcTy = V->getType();
2093     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
2094     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
2095     if (srcSizeInBits > 1 && dstSizeInBits == 1)
2096       return IRB.CreateICmpNE(V, getCleanShadow(V));
2097 
2098     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
2099       return IRB.CreateIntCast(V, dstTy, Signed);
2100     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
2101         cast<FixedVectorType>(dstTy)->getNumElements() ==
2102             cast<FixedVectorType>(srcTy)->getNumElements())
2103       return IRB.CreateIntCast(V, dstTy, Signed);
2104     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
2105     Value *V2 =
2106       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
2107     return IRB.CreateBitCast(V2, dstTy);
2108     // TODO: handle struct types.
2109   }
2110 
2111   /// Cast an application value to the type of its own shadow.
2112   Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
2113     Type *ShadowTy = getShadowTy(V);
2114     if (V->getType() == ShadowTy)
2115       return V;
2116     if (V->getType()->isPtrOrPtrVectorTy())
2117       return IRB.CreatePtrToInt(V, ShadowTy);
2118     else
2119       return IRB.CreateBitCast(V, ShadowTy);
2120   }
2121 
2122   /// Propagate shadow for arbitrary operation.
2123   void handleShadowOr(Instruction &I) {
2124     IRBuilder<> IRB(&I);
2125     ShadowAndOriginCombiner SC(this, IRB);
2126     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
2127       SC.Add(OI->get());
2128     SC.Done(&I);
2129   }
2130 
2131   void visitFNeg(UnaryOperator &I) { handleShadowOr(I); }
2132 
2133   // Handle multiplication by constant.
2134   //
2135   // Handle a special case of multiplication by constant that may have one or
2136   // more zeros in the lower bits. This makes corresponding number of lower bits
2137   // of the result zero as well. We model it by shifting the other operand
2138   // shadow left by the required number of bits. Effectively, we transform
2139   // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
2140   // We use multiplication by 2**N instead of shift to cover the case of
2141   // multiplication by 0, which may occur in some elements of a vector operand.
2142   void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
2143                            Value *OtherArg) {
2144     Constant *ShadowMul;
2145     Type *Ty = ConstArg->getType();
2146     if (auto *VTy = dyn_cast<VectorType>(Ty)) {
2147       unsigned NumElements = cast<FixedVectorType>(VTy)->getNumElements();
2148       Type *EltTy = VTy->getElementType();
2149       SmallVector<Constant *, 16> Elements;
2150       for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
2151         if (ConstantInt *Elt =
2152                 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx))) {
2153           const APInt &V = Elt->getValue();
2154           APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
2155           Elements.push_back(ConstantInt::get(EltTy, V2));
2156         } else {
2157           Elements.push_back(ConstantInt::get(EltTy, 1));
2158         }
2159       }
2160       ShadowMul = ConstantVector::get(Elements);
2161     } else {
2162       if (ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg)) {
2163         const APInt &V = Elt->getValue();
2164         APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
2165         ShadowMul = ConstantInt::get(Ty, V2);
2166       } else {
2167         ShadowMul = ConstantInt::get(Ty, 1);
2168       }
2169     }
2170 
2171     IRBuilder<> IRB(&I);
2172     setShadow(&I,
2173               IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
2174     setOrigin(&I, getOrigin(OtherArg));
2175   }
2176 
2177   void visitMul(BinaryOperator &I) {
2178     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
2179     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
2180     if (constOp0 && !constOp1)
2181       handleMulByConstant(I, constOp0, I.getOperand(1));
2182     else if (constOp1 && !constOp0)
2183       handleMulByConstant(I, constOp1, I.getOperand(0));
2184     else
2185       handleShadowOr(I);
2186   }
2187 
2188   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
2189   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
2190   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
2191   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
2192   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
2193   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
2194 
2195   void handleIntegerDiv(Instruction &I) {
2196     IRBuilder<> IRB(&I);
2197     // Strict on the second argument.
2198     insertShadowCheck(I.getOperand(1), &I);
2199     setShadow(&I, getShadow(&I, 0));
2200     setOrigin(&I, getOrigin(&I, 0));
2201   }
2202 
2203   void visitUDiv(BinaryOperator &I) { handleIntegerDiv(I); }
2204   void visitSDiv(BinaryOperator &I) { handleIntegerDiv(I); }
2205   void visitURem(BinaryOperator &I) { handleIntegerDiv(I); }
2206   void visitSRem(BinaryOperator &I) { handleIntegerDiv(I); }
2207 
2208   // Floating point division is side-effect free. We can not require that the
2209   // divisor is fully initialized and must propagate shadow. See PR37523.
2210   void visitFDiv(BinaryOperator &I) { handleShadowOr(I); }
2211   void visitFRem(BinaryOperator &I) { handleShadowOr(I); }
2212 
2213   /// Instrument == and != comparisons.
2214   ///
2215   /// Sometimes the comparison result is known even if some of the bits of the
2216   /// arguments are not.
2217   void handleEqualityComparison(ICmpInst &I) {
2218     IRBuilder<> IRB(&I);
2219     Value *A = I.getOperand(0);
2220     Value *B = I.getOperand(1);
2221     Value *Sa = getShadow(A);
2222     Value *Sb = getShadow(B);
2223 
2224     // Get rid of pointers and vectors of pointers.
2225     // For ints (and vectors of ints), types of A and Sa match,
2226     // and this is a no-op.
2227     A = IRB.CreatePointerCast(A, Sa->getType());
2228     B = IRB.CreatePointerCast(B, Sb->getType());
2229 
2230     // A == B  <==>  (C = A^B) == 0
2231     // A != B  <==>  (C = A^B) != 0
2232     // Sc = Sa | Sb
2233     Value *C = IRB.CreateXor(A, B);
2234     Value *Sc = IRB.CreateOr(Sa, Sb);
2235     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
2236     // Result is defined if one of the following is true
2237     // * there is a defined 1 bit in C
2238     // * C is fully defined
2239     // Si = !(C & ~Sc) && Sc
2240     Value *Zero = Constant::getNullValue(Sc->getType());
2241     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
2242     Value *Si =
2243       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
2244                     IRB.CreateICmpEQ(
2245                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
2246     Si->setName("_msprop_icmp");
2247     setShadow(&I, Si);
2248     setOriginForNaryOp(I);
2249   }
2250 
2251   /// Build the lowest possible value of V, taking into account V's
2252   ///        uninitialized bits.
2253   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
2254                                 bool isSigned) {
2255     if (isSigned) {
2256       // Split shadow into sign bit and other bits.
2257       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
2258       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
2259       // Maximise the undefined shadow bit, minimize other undefined bits.
2260       return
2261         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
2262     } else {
2263       // Minimize undefined bits.
2264       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
2265     }
2266   }
2267 
2268   /// Build the highest possible value of V, taking into account V's
2269   ///        uninitialized bits.
2270   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
2271                                 bool isSigned) {
2272     if (isSigned) {
2273       // Split shadow into sign bit and other bits.
2274       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
2275       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
2276       // Minimise the undefined shadow bit, maximise other undefined bits.
2277       return
2278         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
2279     } else {
2280       // Maximize undefined bits.
2281       return IRB.CreateOr(A, Sa);
2282     }
2283   }
2284 
2285   /// Instrument relational comparisons.
2286   ///
2287   /// This function does exact shadow propagation for all relational
2288   /// comparisons of integers, pointers and vectors of those.
2289   /// FIXME: output seems suboptimal when one of the operands is a constant
2290   void handleRelationalComparisonExact(ICmpInst &I) {
2291     IRBuilder<> IRB(&I);
2292     Value *A = I.getOperand(0);
2293     Value *B = I.getOperand(1);
2294     Value *Sa = getShadow(A);
2295     Value *Sb = getShadow(B);
2296 
2297     // Get rid of pointers and vectors of pointers.
2298     // For ints (and vectors of ints), types of A and Sa match,
2299     // and this is a no-op.
2300     A = IRB.CreatePointerCast(A, Sa->getType());
2301     B = IRB.CreatePointerCast(B, Sb->getType());
2302 
2303     // Let [a0, a1] be the interval of possible values of A, taking into account
2304     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
2305     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
2306     bool IsSigned = I.isSigned();
2307     Value *S1 = IRB.CreateICmp(I.getPredicate(),
2308                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
2309                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
2310     Value *S2 = IRB.CreateICmp(I.getPredicate(),
2311                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
2312                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
2313     Value *Si = IRB.CreateXor(S1, S2);
2314     setShadow(&I, Si);
2315     setOriginForNaryOp(I);
2316   }
2317 
2318   /// Instrument signed relational comparisons.
2319   ///
2320   /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest
2321   /// bit of the shadow. Everything else is delegated to handleShadowOr().
2322   void handleSignedRelationalComparison(ICmpInst &I) {
2323     Constant *constOp;
2324     Value *op = nullptr;
2325     CmpInst::Predicate pre;
2326     if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) {
2327       op = I.getOperand(0);
2328       pre = I.getPredicate();
2329     } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) {
2330       op = I.getOperand(1);
2331       pre = I.getSwappedPredicate();
2332     } else {
2333       handleShadowOr(I);
2334       return;
2335     }
2336 
2337     if ((constOp->isNullValue() &&
2338          (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) ||
2339         (constOp->isAllOnesValue() &&
2340          (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) {
2341       IRBuilder<> IRB(&I);
2342       Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op),
2343                                         "_msprop_icmp_s");
2344       setShadow(&I, Shadow);
2345       setOrigin(&I, getOrigin(op));
2346     } else {
2347       handleShadowOr(I);
2348     }
2349   }
2350 
2351   void visitICmpInst(ICmpInst &I) {
2352     if (!ClHandleICmp) {
2353       handleShadowOr(I);
2354       return;
2355     }
2356     if (I.isEquality()) {
2357       handleEqualityComparison(I);
2358       return;
2359     }
2360 
2361     assert(I.isRelational());
2362     if (ClHandleICmpExact) {
2363       handleRelationalComparisonExact(I);
2364       return;
2365     }
2366     if (I.isSigned()) {
2367       handleSignedRelationalComparison(I);
2368       return;
2369     }
2370 
2371     assert(I.isUnsigned());
2372     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
2373       handleRelationalComparisonExact(I);
2374       return;
2375     }
2376 
2377     handleShadowOr(I);
2378   }
2379 
2380   void visitFCmpInst(FCmpInst &I) {
2381     handleShadowOr(I);
2382   }
2383 
2384   void handleShift(BinaryOperator &I) {
2385     IRBuilder<> IRB(&I);
2386     // If any of the S2 bits are poisoned, the whole thing is poisoned.
2387     // Otherwise perform the same shift on S1.
2388     Value *S1 = getShadow(&I, 0);
2389     Value *S2 = getShadow(&I, 1);
2390     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
2391                                    S2->getType());
2392     Value *V2 = I.getOperand(1);
2393     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
2394     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2395     setOriginForNaryOp(I);
2396   }
2397 
2398   void visitShl(BinaryOperator &I) { handleShift(I); }
2399   void visitAShr(BinaryOperator &I) { handleShift(I); }
2400   void visitLShr(BinaryOperator &I) { handleShift(I); }
2401 
2402   /// Instrument llvm.memmove
2403   ///
2404   /// At this point we don't know if llvm.memmove will be inlined or not.
2405   /// If we don't instrument it and it gets inlined,
2406   /// our interceptor will not kick in and we will lose the memmove.
2407   /// If we instrument the call here, but it does not get inlined,
2408   /// we will memove the shadow twice: which is bad in case
2409   /// of overlapping regions. So, we simply lower the intrinsic to a call.
2410   ///
2411   /// Similar situation exists for memcpy and memset.
2412   void visitMemMoveInst(MemMoveInst &I) {
2413     IRBuilder<> IRB(&I);
2414     IRB.CreateCall(
2415         MS.MemmoveFn,
2416         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2417          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
2418          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
2419     I.eraseFromParent();
2420   }
2421 
2422   // Similar to memmove: avoid copying shadow twice.
2423   // This is somewhat unfortunate as it may slowdown small constant memcpys.
2424   // FIXME: consider doing manual inline for small constant sizes and proper
2425   // alignment.
2426   void visitMemCpyInst(MemCpyInst &I) {
2427     IRBuilder<> IRB(&I);
2428     IRB.CreateCall(
2429         MS.MemcpyFn,
2430         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2431          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
2432          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
2433     I.eraseFromParent();
2434   }
2435 
2436   // Same as memcpy.
2437   void visitMemSetInst(MemSetInst &I) {
2438     IRBuilder<> IRB(&I);
2439     IRB.CreateCall(
2440         MS.MemsetFn,
2441         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2442          IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
2443          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
2444     I.eraseFromParent();
2445   }
2446 
2447   void visitVAStartInst(VAStartInst &I) {
2448     VAHelper->visitVAStartInst(I);
2449   }
2450 
2451   void visitVACopyInst(VACopyInst &I) {
2452     VAHelper->visitVACopyInst(I);
2453   }
2454 
2455   /// Handle vector store-like intrinsics.
2456   ///
2457   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
2458   /// has 1 pointer argument and 1 vector argument, returns void.
2459   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
2460     IRBuilder<> IRB(&I);
2461     Value* Addr = I.getArgOperand(0);
2462     Value *Shadow = getShadow(&I, 1);
2463     Value *ShadowPtr, *OriginPtr;
2464 
2465     // We don't know the pointer alignment (could be unaligned SSE store!).
2466     // Have to assume to worst case.
2467     std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr(
2468         Addr, IRB, Shadow->getType(), Align(1), /*isStore*/ true);
2469     IRB.CreateAlignedStore(Shadow, ShadowPtr, Align(1));
2470 
2471     if (ClCheckAccessAddress)
2472       insertShadowCheck(Addr, &I);
2473 
2474     // FIXME: factor out common code from materializeStores
2475     if (MS.TrackOrigins) IRB.CreateStore(getOrigin(&I, 1), OriginPtr);
2476     return true;
2477   }
2478 
2479   /// Handle vector load-like intrinsics.
2480   ///
2481   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
2482   /// has 1 pointer argument, returns a vector.
2483   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
2484     IRBuilder<> IRB(&I);
2485     Value *Addr = I.getArgOperand(0);
2486 
2487     Type *ShadowTy = getShadowTy(&I);
2488     Value *ShadowPtr = nullptr, *OriginPtr = nullptr;
2489     if (PropagateShadow) {
2490       // We don't know the pointer alignment (could be unaligned SSE load!).
2491       // Have to assume to worst case.
2492       const Align Alignment = Align(1);
2493       std::tie(ShadowPtr, OriginPtr) =
2494           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
2495       setShadow(&I,
2496                 IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Alignment, "_msld"));
2497     } else {
2498       setShadow(&I, getCleanShadow(&I));
2499     }
2500 
2501     if (ClCheckAccessAddress)
2502       insertShadowCheck(Addr, &I);
2503 
2504     if (MS.TrackOrigins) {
2505       if (PropagateShadow)
2506         setOrigin(&I, IRB.CreateLoad(MS.OriginTy, OriginPtr));
2507       else
2508         setOrigin(&I, getCleanOrigin());
2509     }
2510     return true;
2511   }
2512 
2513   /// Handle (SIMD arithmetic)-like intrinsics.
2514   ///
2515   /// Instrument intrinsics with any number of arguments of the same type,
2516   /// equal to the return type. The type should be simple (no aggregates or
2517   /// pointers; vectors are fine).
2518   /// Caller guarantees that this intrinsic does not access memory.
2519   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
2520     Type *RetTy = I.getType();
2521     if (!(RetTy->isIntOrIntVectorTy() ||
2522           RetTy->isFPOrFPVectorTy() ||
2523           RetTy->isX86_MMXTy()))
2524       return false;
2525 
2526     unsigned NumArgOperands = I.getNumArgOperands();
2527 
2528     for (unsigned i = 0; i < NumArgOperands; ++i) {
2529       Type *Ty = I.getArgOperand(i)->getType();
2530       if (Ty != RetTy)
2531         return false;
2532     }
2533 
2534     IRBuilder<> IRB(&I);
2535     ShadowAndOriginCombiner SC(this, IRB);
2536     for (unsigned i = 0; i < NumArgOperands; ++i)
2537       SC.Add(I.getArgOperand(i));
2538     SC.Done(&I);
2539 
2540     return true;
2541   }
2542 
2543   /// Heuristically instrument unknown intrinsics.
2544   ///
2545   /// The main purpose of this code is to do something reasonable with all
2546   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
2547   /// We recognize several classes of intrinsics by their argument types and
2548   /// ModRefBehaviour and apply special instrumentation when we are reasonably
2549   /// sure that we know what the intrinsic does.
2550   ///
2551   /// We special-case intrinsics where this approach fails. See llvm.bswap
2552   /// handling as an example of that.
2553   bool handleUnknownIntrinsic(IntrinsicInst &I) {
2554     unsigned NumArgOperands = I.getNumArgOperands();
2555     if (NumArgOperands == 0)
2556       return false;
2557 
2558     if (NumArgOperands == 2 &&
2559         I.getArgOperand(0)->getType()->isPointerTy() &&
2560         I.getArgOperand(1)->getType()->isVectorTy() &&
2561         I.getType()->isVoidTy() &&
2562         !I.onlyReadsMemory()) {
2563       // This looks like a vector store.
2564       return handleVectorStoreIntrinsic(I);
2565     }
2566 
2567     if (NumArgOperands == 1 &&
2568         I.getArgOperand(0)->getType()->isPointerTy() &&
2569         I.getType()->isVectorTy() &&
2570         I.onlyReadsMemory()) {
2571       // This looks like a vector load.
2572       return handleVectorLoadIntrinsic(I);
2573     }
2574 
2575     if (I.doesNotAccessMemory())
2576       if (maybeHandleSimpleNomemIntrinsic(I))
2577         return true;
2578 
2579     // FIXME: detect and handle SSE maskstore/maskload
2580     return false;
2581   }
2582 
2583   void handleInvariantGroup(IntrinsicInst &I) {
2584     setShadow(&I, getShadow(&I, 0));
2585     setOrigin(&I, getOrigin(&I, 0));
2586   }
2587 
2588   void handleLifetimeStart(IntrinsicInst &I) {
2589     if (!PoisonStack)
2590       return;
2591     DenseMap<Value *, AllocaInst *> AllocaForValue;
2592     AllocaInst *AI =
2593         llvm::findAllocaForValue(I.getArgOperand(1), AllocaForValue);
2594     if (!AI)
2595       InstrumentLifetimeStart = false;
2596     LifetimeStartList.push_back(std::make_pair(&I, AI));
2597   }
2598 
2599   void handleBswap(IntrinsicInst &I) {
2600     IRBuilder<> IRB(&I);
2601     Value *Op = I.getArgOperand(0);
2602     Type *OpType = Op->getType();
2603     Function *BswapFunc = Intrinsic::getDeclaration(
2604       F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
2605     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2606     setOrigin(&I, getOrigin(Op));
2607   }
2608 
2609   // Instrument vector convert intrinsic.
2610   //
2611   // This function instruments intrinsics like cvtsi2ss:
2612   // %Out = int_xxx_cvtyyy(%ConvertOp)
2613   // or
2614   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2615   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2616   // number \p Out elements, and (if has 2 arguments) copies the rest of the
2617   // elements from \p CopyOp.
2618   // In most cases conversion involves floating-point value which may trigger a
2619   // hardware exception when not fully initialized. For this reason we require
2620   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2621   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2622   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2623   // return a fully initialized value.
2624   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2625     IRBuilder<> IRB(&I);
2626     Value *CopyOp, *ConvertOp;
2627 
2628     switch (I.getNumArgOperands()) {
2629     case 3:
2630       assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
2631       LLVM_FALLTHROUGH;
2632     case 2:
2633       CopyOp = I.getArgOperand(0);
2634       ConvertOp = I.getArgOperand(1);
2635       break;
2636     case 1:
2637       ConvertOp = I.getArgOperand(0);
2638       CopyOp = nullptr;
2639       break;
2640     default:
2641       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2642     }
2643 
2644     // The first *NumUsedElements* elements of ConvertOp are converted to the
2645     // same number of output elements. The rest of the output is copied from
2646     // CopyOp, or (if not available) filled with zeroes.
2647     // Combine shadow for elements of ConvertOp that are used in this operation,
2648     // and insert a check.
2649     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2650     // int->any conversion.
2651     Value *ConvertShadow = getShadow(ConvertOp);
2652     Value *AggShadow = nullptr;
2653     if (ConvertOp->getType()->isVectorTy()) {
2654       AggShadow = IRB.CreateExtractElement(
2655           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2656       for (int i = 1; i < NumUsedElements; ++i) {
2657         Value *MoreShadow = IRB.CreateExtractElement(
2658             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2659         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2660       }
2661     } else {
2662       AggShadow = ConvertShadow;
2663     }
2664     assert(AggShadow->getType()->isIntegerTy());
2665     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2666 
2667     // Build result shadow by zero-filling parts of CopyOp shadow that come from
2668     // ConvertOp.
2669     if (CopyOp) {
2670       assert(CopyOp->getType() == I.getType());
2671       assert(CopyOp->getType()->isVectorTy());
2672       Value *ResultShadow = getShadow(CopyOp);
2673       Type *EltTy = cast<VectorType>(ResultShadow->getType())->getElementType();
2674       for (int i = 0; i < NumUsedElements; ++i) {
2675         ResultShadow = IRB.CreateInsertElement(
2676             ResultShadow, ConstantInt::getNullValue(EltTy),
2677             ConstantInt::get(IRB.getInt32Ty(), i));
2678       }
2679       setShadow(&I, ResultShadow);
2680       setOrigin(&I, getOrigin(CopyOp));
2681     } else {
2682       setShadow(&I, getCleanShadow(&I));
2683       setOrigin(&I, getCleanOrigin());
2684     }
2685   }
2686 
2687   // Given a scalar or vector, extract lower 64 bits (or less), and return all
2688   // zeroes if it is zero, and all ones otherwise.
2689   Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2690     if (S->getType()->isVectorTy())
2691       S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2692     assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2693     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2694     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2695   }
2696 
2697   // Given a vector, extract its first element, and return all
2698   // zeroes if it is zero, and all ones otherwise.
2699   Value *LowerElementShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2700     Value *S1 = IRB.CreateExtractElement(S, (uint64_t)0);
2701     Value *S2 = IRB.CreateICmpNE(S1, getCleanShadow(S1));
2702     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2703   }
2704 
2705   Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2706     Type *T = S->getType();
2707     assert(T->isVectorTy());
2708     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2709     return IRB.CreateSExt(S2, T);
2710   }
2711 
2712   // Instrument vector shift intrinsic.
2713   //
2714   // This function instruments intrinsics like int_x86_avx2_psll_w.
2715   // Intrinsic shifts %In by %ShiftSize bits.
2716   // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2717   // size, and the rest is ignored. Behavior is defined even if shift size is
2718   // greater than register (or field) width.
2719   void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2720     assert(I.getNumArgOperands() == 2);
2721     IRBuilder<> IRB(&I);
2722     // If any of the S2 bits are poisoned, the whole thing is poisoned.
2723     // Otherwise perform the same shift on S1.
2724     Value *S1 = getShadow(&I, 0);
2725     Value *S2 = getShadow(&I, 1);
2726     Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2727                              : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2728     Value *V1 = I.getOperand(0);
2729     Value *V2 = I.getOperand(1);
2730     Value *Shift = IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
2731                                   {IRB.CreateBitCast(S1, V1->getType()), V2});
2732     Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2733     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2734     setOriginForNaryOp(I);
2735   }
2736 
2737   // Get an X86_MMX-sized vector type.
2738   Type *getMMXVectorTy(unsigned EltSizeInBits) {
2739     const unsigned X86_MMXSizeInBits = 64;
2740     assert(EltSizeInBits != 0 && (X86_MMXSizeInBits % EltSizeInBits) == 0 &&
2741            "Illegal MMX vector element size");
2742     return FixedVectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2743                                 X86_MMXSizeInBits / EltSizeInBits);
2744   }
2745 
2746   // Returns a signed counterpart for an (un)signed-saturate-and-pack
2747   // intrinsic.
2748   Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2749     switch (id) {
2750       case Intrinsic::x86_sse2_packsswb_128:
2751       case Intrinsic::x86_sse2_packuswb_128:
2752         return Intrinsic::x86_sse2_packsswb_128;
2753 
2754       case Intrinsic::x86_sse2_packssdw_128:
2755       case Intrinsic::x86_sse41_packusdw:
2756         return Intrinsic::x86_sse2_packssdw_128;
2757 
2758       case Intrinsic::x86_avx2_packsswb:
2759       case Intrinsic::x86_avx2_packuswb:
2760         return Intrinsic::x86_avx2_packsswb;
2761 
2762       case Intrinsic::x86_avx2_packssdw:
2763       case Intrinsic::x86_avx2_packusdw:
2764         return Intrinsic::x86_avx2_packssdw;
2765 
2766       case Intrinsic::x86_mmx_packsswb:
2767       case Intrinsic::x86_mmx_packuswb:
2768         return Intrinsic::x86_mmx_packsswb;
2769 
2770       case Intrinsic::x86_mmx_packssdw:
2771         return Intrinsic::x86_mmx_packssdw;
2772       default:
2773         llvm_unreachable("unexpected intrinsic id");
2774     }
2775   }
2776 
2777   // Instrument vector pack intrinsic.
2778   //
2779   // This function instruments intrinsics like x86_mmx_packsswb, that
2780   // packs elements of 2 input vectors into half as many bits with saturation.
2781   // Shadow is propagated with the signed variant of the same intrinsic applied
2782   // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2783   // EltSizeInBits is used only for x86mmx arguments.
2784   void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
2785     assert(I.getNumArgOperands() == 2);
2786     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2787     IRBuilder<> IRB(&I);
2788     Value *S1 = getShadow(&I, 0);
2789     Value *S2 = getShadow(&I, 1);
2790     assert(isX86_MMX || S1->getType()->isVectorTy());
2791 
2792     // SExt and ICmpNE below must apply to individual elements of input vectors.
2793     // In case of x86mmx arguments, cast them to appropriate vector types and
2794     // back.
2795     Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2796     if (isX86_MMX) {
2797       S1 = IRB.CreateBitCast(S1, T);
2798       S2 = IRB.CreateBitCast(S2, T);
2799     }
2800     Value *S1_ext = IRB.CreateSExt(
2801         IRB.CreateICmpNE(S1, Constant::getNullValue(T)), T);
2802     Value *S2_ext = IRB.CreateSExt(
2803         IRB.CreateICmpNE(S2, Constant::getNullValue(T)), T);
2804     if (isX86_MMX) {
2805       Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2806       S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2807       S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2808     }
2809 
2810     Function *ShadowFn = Intrinsic::getDeclaration(
2811         F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2812 
2813     Value *S =
2814         IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
2815     if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2816     setShadow(&I, S);
2817     setOriginForNaryOp(I);
2818   }
2819 
2820   // Instrument sum-of-absolute-differences intrinsic.
2821   void handleVectorSadIntrinsic(IntrinsicInst &I) {
2822     const unsigned SignificantBitsPerResultElement = 16;
2823     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2824     Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2825     unsigned ZeroBitsPerResultElement =
2826         ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2827 
2828     IRBuilder<> IRB(&I);
2829     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2830     S = IRB.CreateBitCast(S, ResTy);
2831     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2832                        ResTy);
2833     S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2834     S = IRB.CreateBitCast(S, getShadowTy(&I));
2835     setShadow(&I, S);
2836     setOriginForNaryOp(I);
2837   }
2838 
2839   // Instrument multiply-add intrinsic.
2840   void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2841                                   unsigned EltSizeInBits = 0) {
2842     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2843     Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2844     IRBuilder<> IRB(&I);
2845     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2846     S = IRB.CreateBitCast(S, ResTy);
2847     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2848                        ResTy);
2849     S = IRB.CreateBitCast(S, getShadowTy(&I));
2850     setShadow(&I, S);
2851     setOriginForNaryOp(I);
2852   }
2853 
2854   // Instrument compare-packed intrinsic.
2855   // Basically, an or followed by sext(icmp ne 0) to end up with all-zeros or
2856   // all-ones shadow.
2857   void handleVectorComparePackedIntrinsic(IntrinsicInst &I) {
2858     IRBuilder<> IRB(&I);
2859     Type *ResTy = getShadowTy(&I);
2860     Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2861     Value *S = IRB.CreateSExt(
2862         IRB.CreateICmpNE(S0, Constant::getNullValue(ResTy)), ResTy);
2863     setShadow(&I, S);
2864     setOriginForNaryOp(I);
2865   }
2866 
2867   // Instrument compare-scalar intrinsic.
2868   // This handles both cmp* intrinsics which return the result in the first
2869   // element of a vector, and comi* which return the result as i32.
2870   void handleVectorCompareScalarIntrinsic(IntrinsicInst &I) {
2871     IRBuilder<> IRB(&I);
2872     Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2873     Value *S = LowerElementShadowExtend(IRB, S0, getShadowTy(&I));
2874     setShadow(&I, S);
2875     setOriginForNaryOp(I);
2876   }
2877 
2878   void handleStmxcsr(IntrinsicInst &I) {
2879     IRBuilder<> IRB(&I);
2880     Value* Addr = I.getArgOperand(0);
2881     Type *Ty = IRB.getInt32Ty();
2882     Value *ShadowPtr =
2883         getShadowOriginPtr(Addr, IRB, Ty, Align(1), /*isStore*/ true).first;
2884 
2885     IRB.CreateStore(getCleanShadow(Ty),
2886                     IRB.CreatePointerCast(ShadowPtr, Ty->getPointerTo()));
2887 
2888     if (ClCheckAccessAddress)
2889       insertShadowCheck(Addr, &I);
2890   }
2891 
2892   void handleLdmxcsr(IntrinsicInst &I) {
2893     if (!InsertChecks) return;
2894 
2895     IRBuilder<> IRB(&I);
2896     Value *Addr = I.getArgOperand(0);
2897     Type *Ty = IRB.getInt32Ty();
2898     const Align Alignment = Align(1);
2899     Value *ShadowPtr, *OriginPtr;
2900     std::tie(ShadowPtr, OriginPtr) =
2901         getShadowOriginPtr(Addr, IRB, Ty, Alignment, /*isStore*/ false);
2902 
2903     if (ClCheckAccessAddress)
2904       insertShadowCheck(Addr, &I);
2905 
2906     Value *Shadow = IRB.CreateAlignedLoad(Ty, ShadowPtr, Alignment, "_ldmxcsr");
2907     Value *Origin = MS.TrackOrigins ? IRB.CreateLoad(MS.OriginTy, OriginPtr)
2908                                     : getCleanOrigin();
2909     insertShadowCheck(Shadow, Origin, &I);
2910   }
2911 
2912   void handleMaskedStore(IntrinsicInst &I) {
2913     IRBuilder<> IRB(&I);
2914     Value *V = I.getArgOperand(0);
2915     Value *Addr = I.getArgOperand(1);
2916     const Align Alignment(
2917         cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
2918     Value *Mask = I.getArgOperand(3);
2919     Value *Shadow = getShadow(V);
2920 
2921     Value *ShadowPtr;
2922     Value *OriginPtr;
2923     std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr(
2924         Addr, IRB, Shadow->getType(), Alignment, /*isStore*/ true);
2925 
2926     if (ClCheckAccessAddress) {
2927       insertShadowCheck(Addr, &I);
2928       // Uninitialized mask is kind of like uninitialized address, but not as
2929       // scary.
2930       insertShadowCheck(Mask, &I);
2931     }
2932 
2933     IRB.CreateMaskedStore(Shadow, ShadowPtr, Alignment, Mask);
2934 
2935     if (MS.TrackOrigins) {
2936       auto &DL = F.getParent()->getDataLayout();
2937       paintOrigin(IRB, getOrigin(V), OriginPtr,
2938                   DL.getTypeStoreSize(Shadow->getType()),
2939                   std::max(Alignment, kMinOriginAlignment));
2940     }
2941   }
2942 
2943   bool handleMaskedLoad(IntrinsicInst &I) {
2944     IRBuilder<> IRB(&I);
2945     Value *Addr = I.getArgOperand(0);
2946     const Align Alignment(
2947         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
2948     Value *Mask = I.getArgOperand(2);
2949     Value *PassThru = I.getArgOperand(3);
2950 
2951     Type *ShadowTy = getShadowTy(&I);
2952     Value *ShadowPtr, *OriginPtr;
2953     if (PropagateShadow) {
2954       std::tie(ShadowPtr, OriginPtr) =
2955           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
2956       setShadow(&I, IRB.CreateMaskedLoad(ShadowPtr, Alignment, Mask,
2957                                          getShadow(PassThru), "_msmaskedld"));
2958     } else {
2959       setShadow(&I, getCleanShadow(&I));
2960     }
2961 
2962     if (ClCheckAccessAddress) {
2963       insertShadowCheck(Addr, &I);
2964       insertShadowCheck(Mask, &I);
2965     }
2966 
2967     if (MS.TrackOrigins) {
2968       if (PropagateShadow) {
2969         // Choose between PassThru's and the loaded value's origins.
2970         Value *MaskedPassThruShadow = IRB.CreateAnd(
2971             getShadow(PassThru), IRB.CreateSExt(IRB.CreateNeg(Mask), ShadowTy));
2972 
2973         Value *Acc = IRB.CreateExtractElement(
2974             MaskedPassThruShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2975         for (int i = 1, N = cast<FixedVectorType>(PassThru->getType())
2976                                 ->getNumElements();
2977              i < N; ++i) {
2978           Value *More = IRB.CreateExtractElement(
2979               MaskedPassThruShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2980           Acc = IRB.CreateOr(Acc, More);
2981         }
2982 
2983         Value *Origin = IRB.CreateSelect(
2984             IRB.CreateICmpNE(Acc, Constant::getNullValue(Acc->getType())),
2985             getOrigin(PassThru), IRB.CreateLoad(MS.OriginTy, OriginPtr));
2986 
2987         setOrigin(&I, Origin);
2988       } else {
2989         setOrigin(&I, getCleanOrigin());
2990       }
2991     }
2992     return true;
2993   }
2994 
2995   // Instrument BMI / BMI2 intrinsics.
2996   // All of these intrinsics are Z = I(X, Y)
2997   // where the types of all operands and the result match, and are either i32 or i64.
2998   // The following instrumentation happens to work for all of them:
2999   //   Sz = I(Sx, Y) | (sext (Sy != 0))
3000   void handleBmiIntrinsic(IntrinsicInst &I) {
3001     IRBuilder<> IRB(&I);
3002     Type *ShadowTy = getShadowTy(&I);
3003 
3004     // If any bit of the mask operand is poisoned, then the whole thing is.
3005     Value *SMask = getShadow(&I, 1);
3006     SMask = IRB.CreateSExt(IRB.CreateICmpNE(SMask, getCleanShadow(ShadowTy)),
3007                            ShadowTy);
3008     // Apply the same intrinsic to the shadow of the first operand.
3009     Value *S = IRB.CreateCall(I.getCalledFunction(),
3010                               {getShadow(&I, 0), I.getOperand(1)});
3011     S = IRB.CreateOr(SMask, S);
3012     setShadow(&I, S);
3013     setOriginForNaryOp(I);
3014   }
3015 
3016   SmallVector<int, 8> getPclmulMask(unsigned Width, bool OddElements) {
3017     SmallVector<int, 8> Mask;
3018     for (unsigned X = OddElements ? 1 : 0; X < Width; X += 2) {
3019       Mask.append(2, X);
3020     }
3021     return Mask;
3022   }
3023 
3024   // Instrument pclmul intrinsics.
3025   // These intrinsics operate either on odd or on even elements of the input
3026   // vectors, depending on the constant in the 3rd argument, ignoring the rest.
3027   // Replace the unused elements with copies of the used ones, ex:
3028   //   (0, 1, 2, 3) -> (0, 0, 2, 2) (even case)
3029   // or
3030   //   (0, 1, 2, 3) -> (1, 1, 3, 3) (odd case)
3031   // and then apply the usual shadow combining logic.
3032   void handlePclmulIntrinsic(IntrinsicInst &I) {
3033     IRBuilder<> IRB(&I);
3034     Type *ShadowTy = getShadowTy(&I);
3035     unsigned Width =
3036         cast<FixedVectorType>(I.getArgOperand(0)->getType())->getNumElements();
3037     assert(isa<ConstantInt>(I.getArgOperand(2)) &&
3038            "pclmul 3rd operand must be a constant");
3039     unsigned Imm = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3040     Value *Shuf0 =
3041         IRB.CreateShuffleVector(getShadow(&I, 0), UndefValue::get(ShadowTy),
3042                                 getPclmulMask(Width, Imm & 0x01));
3043     Value *Shuf1 =
3044         IRB.CreateShuffleVector(getShadow(&I, 1), UndefValue::get(ShadowTy),
3045                                 getPclmulMask(Width, Imm & 0x10));
3046     ShadowAndOriginCombiner SOC(this, IRB);
3047     SOC.Add(Shuf0, getOrigin(&I, 0));
3048     SOC.Add(Shuf1, getOrigin(&I, 1));
3049     SOC.Done(&I);
3050   }
3051 
3052   // Instrument _mm_*_sd intrinsics
3053   void handleUnarySdIntrinsic(IntrinsicInst &I) {
3054     IRBuilder<> IRB(&I);
3055     Value *First = getShadow(&I, 0);
3056     Value *Second = getShadow(&I, 1);
3057     // High word of first operand, low word of second
3058     Value *Shadow =
3059         IRB.CreateShuffleVector(First, Second, llvm::makeArrayRef<int>({2, 1}));
3060 
3061     setShadow(&I, Shadow);
3062     setOriginForNaryOp(I);
3063   }
3064 
3065   void handleBinarySdIntrinsic(IntrinsicInst &I) {
3066     IRBuilder<> IRB(&I);
3067     Value *First = getShadow(&I, 0);
3068     Value *Second = getShadow(&I, 1);
3069     Value *OrShadow = IRB.CreateOr(First, Second);
3070     // High word of first operand, low word of both OR'd together
3071     Value *Shadow = IRB.CreateShuffleVector(First, OrShadow,
3072                                             llvm::makeArrayRef<int>({2, 1}));
3073 
3074     setShadow(&I, Shadow);
3075     setOriginForNaryOp(I);
3076   }
3077 
3078   void visitIntrinsicInst(IntrinsicInst &I) {
3079     switch (I.getIntrinsicID()) {
3080     case Intrinsic::lifetime_start:
3081       handleLifetimeStart(I);
3082       break;
3083     case Intrinsic::launder_invariant_group:
3084     case Intrinsic::strip_invariant_group:
3085       handleInvariantGroup(I);
3086       break;
3087     case Intrinsic::bswap:
3088       handleBswap(I);
3089       break;
3090     case Intrinsic::masked_store:
3091       handleMaskedStore(I);
3092       break;
3093     case Intrinsic::masked_load:
3094       handleMaskedLoad(I);
3095       break;
3096     case Intrinsic::x86_sse_stmxcsr:
3097       handleStmxcsr(I);
3098       break;
3099     case Intrinsic::x86_sse_ldmxcsr:
3100       handleLdmxcsr(I);
3101       break;
3102     case Intrinsic::x86_avx512_vcvtsd2usi64:
3103     case Intrinsic::x86_avx512_vcvtsd2usi32:
3104     case Intrinsic::x86_avx512_vcvtss2usi64:
3105     case Intrinsic::x86_avx512_vcvtss2usi32:
3106     case Intrinsic::x86_avx512_cvttss2usi64:
3107     case Intrinsic::x86_avx512_cvttss2usi:
3108     case Intrinsic::x86_avx512_cvttsd2usi64:
3109     case Intrinsic::x86_avx512_cvttsd2usi:
3110     case Intrinsic::x86_avx512_cvtusi2ss:
3111     case Intrinsic::x86_avx512_cvtusi642sd:
3112     case Intrinsic::x86_avx512_cvtusi642ss:
3113     case Intrinsic::x86_sse2_cvtsd2si64:
3114     case Intrinsic::x86_sse2_cvtsd2si:
3115     case Intrinsic::x86_sse2_cvtsd2ss:
3116     case Intrinsic::x86_sse2_cvttsd2si64:
3117     case Intrinsic::x86_sse2_cvttsd2si:
3118     case Intrinsic::x86_sse_cvtss2si64:
3119     case Intrinsic::x86_sse_cvtss2si:
3120     case Intrinsic::x86_sse_cvttss2si64:
3121     case Intrinsic::x86_sse_cvttss2si:
3122       handleVectorConvertIntrinsic(I, 1);
3123       break;
3124     case Intrinsic::x86_sse_cvtps2pi:
3125     case Intrinsic::x86_sse_cvttps2pi:
3126       handleVectorConvertIntrinsic(I, 2);
3127       break;
3128 
3129     case Intrinsic::x86_avx512_psll_w_512:
3130     case Intrinsic::x86_avx512_psll_d_512:
3131     case Intrinsic::x86_avx512_psll_q_512:
3132     case Intrinsic::x86_avx512_pslli_w_512:
3133     case Intrinsic::x86_avx512_pslli_d_512:
3134     case Intrinsic::x86_avx512_pslli_q_512:
3135     case Intrinsic::x86_avx512_psrl_w_512:
3136     case Intrinsic::x86_avx512_psrl_d_512:
3137     case Intrinsic::x86_avx512_psrl_q_512:
3138     case Intrinsic::x86_avx512_psra_w_512:
3139     case Intrinsic::x86_avx512_psra_d_512:
3140     case Intrinsic::x86_avx512_psra_q_512:
3141     case Intrinsic::x86_avx512_psrli_w_512:
3142     case Intrinsic::x86_avx512_psrli_d_512:
3143     case Intrinsic::x86_avx512_psrli_q_512:
3144     case Intrinsic::x86_avx512_psrai_w_512:
3145     case Intrinsic::x86_avx512_psrai_d_512:
3146     case Intrinsic::x86_avx512_psrai_q_512:
3147     case Intrinsic::x86_avx512_psra_q_256:
3148     case Intrinsic::x86_avx512_psra_q_128:
3149     case Intrinsic::x86_avx512_psrai_q_256:
3150     case Intrinsic::x86_avx512_psrai_q_128:
3151     case Intrinsic::x86_avx2_psll_w:
3152     case Intrinsic::x86_avx2_psll_d:
3153     case Intrinsic::x86_avx2_psll_q:
3154     case Intrinsic::x86_avx2_pslli_w:
3155     case Intrinsic::x86_avx2_pslli_d:
3156     case Intrinsic::x86_avx2_pslli_q:
3157     case Intrinsic::x86_avx2_psrl_w:
3158     case Intrinsic::x86_avx2_psrl_d:
3159     case Intrinsic::x86_avx2_psrl_q:
3160     case Intrinsic::x86_avx2_psra_w:
3161     case Intrinsic::x86_avx2_psra_d:
3162     case Intrinsic::x86_avx2_psrli_w:
3163     case Intrinsic::x86_avx2_psrli_d:
3164     case Intrinsic::x86_avx2_psrli_q:
3165     case Intrinsic::x86_avx2_psrai_w:
3166     case Intrinsic::x86_avx2_psrai_d:
3167     case Intrinsic::x86_sse2_psll_w:
3168     case Intrinsic::x86_sse2_psll_d:
3169     case Intrinsic::x86_sse2_psll_q:
3170     case Intrinsic::x86_sse2_pslli_w:
3171     case Intrinsic::x86_sse2_pslli_d:
3172     case Intrinsic::x86_sse2_pslli_q:
3173     case Intrinsic::x86_sse2_psrl_w:
3174     case Intrinsic::x86_sse2_psrl_d:
3175     case Intrinsic::x86_sse2_psrl_q:
3176     case Intrinsic::x86_sse2_psra_w:
3177     case Intrinsic::x86_sse2_psra_d:
3178     case Intrinsic::x86_sse2_psrli_w:
3179     case Intrinsic::x86_sse2_psrli_d:
3180     case Intrinsic::x86_sse2_psrli_q:
3181     case Intrinsic::x86_sse2_psrai_w:
3182     case Intrinsic::x86_sse2_psrai_d:
3183     case Intrinsic::x86_mmx_psll_w:
3184     case Intrinsic::x86_mmx_psll_d:
3185     case Intrinsic::x86_mmx_psll_q:
3186     case Intrinsic::x86_mmx_pslli_w:
3187     case Intrinsic::x86_mmx_pslli_d:
3188     case Intrinsic::x86_mmx_pslli_q:
3189     case Intrinsic::x86_mmx_psrl_w:
3190     case Intrinsic::x86_mmx_psrl_d:
3191     case Intrinsic::x86_mmx_psrl_q:
3192     case Intrinsic::x86_mmx_psra_w:
3193     case Intrinsic::x86_mmx_psra_d:
3194     case Intrinsic::x86_mmx_psrli_w:
3195     case Intrinsic::x86_mmx_psrli_d:
3196     case Intrinsic::x86_mmx_psrli_q:
3197     case Intrinsic::x86_mmx_psrai_w:
3198     case Intrinsic::x86_mmx_psrai_d:
3199       handleVectorShiftIntrinsic(I, /* Variable */ false);
3200       break;
3201     case Intrinsic::x86_avx2_psllv_d:
3202     case Intrinsic::x86_avx2_psllv_d_256:
3203     case Intrinsic::x86_avx512_psllv_d_512:
3204     case Intrinsic::x86_avx2_psllv_q:
3205     case Intrinsic::x86_avx2_psllv_q_256:
3206     case Intrinsic::x86_avx512_psllv_q_512:
3207     case Intrinsic::x86_avx2_psrlv_d:
3208     case Intrinsic::x86_avx2_psrlv_d_256:
3209     case Intrinsic::x86_avx512_psrlv_d_512:
3210     case Intrinsic::x86_avx2_psrlv_q:
3211     case Intrinsic::x86_avx2_psrlv_q_256:
3212     case Intrinsic::x86_avx512_psrlv_q_512:
3213     case Intrinsic::x86_avx2_psrav_d:
3214     case Intrinsic::x86_avx2_psrav_d_256:
3215     case Intrinsic::x86_avx512_psrav_d_512:
3216     case Intrinsic::x86_avx512_psrav_q_128:
3217     case Intrinsic::x86_avx512_psrav_q_256:
3218     case Intrinsic::x86_avx512_psrav_q_512:
3219       handleVectorShiftIntrinsic(I, /* Variable */ true);
3220       break;
3221 
3222     case Intrinsic::x86_sse2_packsswb_128:
3223     case Intrinsic::x86_sse2_packssdw_128:
3224     case Intrinsic::x86_sse2_packuswb_128:
3225     case Intrinsic::x86_sse41_packusdw:
3226     case Intrinsic::x86_avx2_packsswb:
3227     case Intrinsic::x86_avx2_packssdw:
3228     case Intrinsic::x86_avx2_packuswb:
3229     case Intrinsic::x86_avx2_packusdw:
3230       handleVectorPackIntrinsic(I);
3231       break;
3232 
3233     case Intrinsic::x86_mmx_packsswb:
3234     case Intrinsic::x86_mmx_packuswb:
3235       handleVectorPackIntrinsic(I, 16);
3236       break;
3237 
3238     case Intrinsic::x86_mmx_packssdw:
3239       handleVectorPackIntrinsic(I, 32);
3240       break;
3241 
3242     case Intrinsic::x86_mmx_psad_bw:
3243     case Intrinsic::x86_sse2_psad_bw:
3244     case Intrinsic::x86_avx2_psad_bw:
3245       handleVectorSadIntrinsic(I);
3246       break;
3247 
3248     case Intrinsic::x86_sse2_pmadd_wd:
3249     case Intrinsic::x86_avx2_pmadd_wd:
3250     case Intrinsic::x86_ssse3_pmadd_ub_sw_128:
3251     case Intrinsic::x86_avx2_pmadd_ub_sw:
3252       handleVectorPmaddIntrinsic(I);
3253       break;
3254 
3255     case Intrinsic::x86_ssse3_pmadd_ub_sw:
3256       handleVectorPmaddIntrinsic(I, 8);
3257       break;
3258 
3259     case Intrinsic::x86_mmx_pmadd_wd:
3260       handleVectorPmaddIntrinsic(I, 16);
3261       break;
3262 
3263     case Intrinsic::x86_sse_cmp_ss:
3264     case Intrinsic::x86_sse2_cmp_sd:
3265     case Intrinsic::x86_sse_comieq_ss:
3266     case Intrinsic::x86_sse_comilt_ss:
3267     case Intrinsic::x86_sse_comile_ss:
3268     case Intrinsic::x86_sse_comigt_ss:
3269     case Intrinsic::x86_sse_comige_ss:
3270     case Intrinsic::x86_sse_comineq_ss:
3271     case Intrinsic::x86_sse_ucomieq_ss:
3272     case Intrinsic::x86_sse_ucomilt_ss:
3273     case Intrinsic::x86_sse_ucomile_ss:
3274     case Intrinsic::x86_sse_ucomigt_ss:
3275     case Intrinsic::x86_sse_ucomige_ss:
3276     case Intrinsic::x86_sse_ucomineq_ss:
3277     case Intrinsic::x86_sse2_comieq_sd:
3278     case Intrinsic::x86_sse2_comilt_sd:
3279     case Intrinsic::x86_sse2_comile_sd:
3280     case Intrinsic::x86_sse2_comigt_sd:
3281     case Intrinsic::x86_sse2_comige_sd:
3282     case Intrinsic::x86_sse2_comineq_sd:
3283     case Intrinsic::x86_sse2_ucomieq_sd:
3284     case Intrinsic::x86_sse2_ucomilt_sd:
3285     case Intrinsic::x86_sse2_ucomile_sd:
3286     case Intrinsic::x86_sse2_ucomigt_sd:
3287     case Intrinsic::x86_sse2_ucomige_sd:
3288     case Intrinsic::x86_sse2_ucomineq_sd:
3289       handleVectorCompareScalarIntrinsic(I);
3290       break;
3291 
3292     case Intrinsic::x86_sse_cmp_ps:
3293     case Intrinsic::x86_sse2_cmp_pd:
3294       // FIXME: For x86_avx_cmp_pd_256 and x86_avx_cmp_ps_256 this function
3295       // generates reasonably looking IR that fails in the backend with "Do not
3296       // know how to split the result of this operator!".
3297       handleVectorComparePackedIntrinsic(I);
3298       break;
3299 
3300     case Intrinsic::x86_bmi_bextr_32:
3301     case Intrinsic::x86_bmi_bextr_64:
3302     case Intrinsic::x86_bmi_bzhi_32:
3303     case Intrinsic::x86_bmi_bzhi_64:
3304     case Intrinsic::x86_bmi_pdep_32:
3305     case Intrinsic::x86_bmi_pdep_64:
3306     case Intrinsic::x86_bmi_pext_32:
3307     case Intrinsic::x86_bmi_pext_64:
3308       handleBmiIntrinsic(I);
3309       break;
3310 
3311     case Intrinsic::x86_pclmulqdq:
3312     case Intrinsic::x86_pclmulqdq_256:
3313     case Intrinsic::x86_pclmulqdq_512:
3314       handlePclmulIntrinsic(I);
3315       break;
3316 
3317     case Intrinsic::x86_sse41_round_sd:
3318       handleUnarySdIntrinsic(I);
3319       break;
3320     case Intrinsic::x86_sse2_max_sd:
3321     case Intrinsic::x86_sse2_min_sd:
3322       handleBinarySdIntrinsic(I);
3323       break;
3324 
3325     case Intrinsic::is_constant:
3326       // The result of llvm.is.constant() is always defined.
3327       setShadow(&I, getCleanShadow(&I));
3328       setOrigin(&I, getCleanOrigin());
3329       break;
3330 
3331     default:
3332       if (!handleUnknownIntrinsic(I))
3333         visitInstruction(I);
3334       break;
3335     }
3336   }
3337 
3338   void visitCallBase(CallBase &CB) {
3339     assert(!CB.getMetadata("nosanitize"));
3340     if (CB.isInlineAsm()) {
3341       // For inline asm (either a call to asm function, or callbr instruction),
3342       // do the usual thing: check argument shadow and mark all outputs as
3343       // clean. Note that any side effects of the inline asm that are not
3344       // immediately visible in its constraints are not handled.
3345       if (ClHandleAsmConservative && MS.CompileKernel)
3346         visitAsmInstruction(CB);
3347       else
3348         visitInstruction(CB);
3349       return;
3350     }
3351     if (auto *Call = dyn_cast<CallInst>(&CB)) {
3352       assert(!isa<IntrinsicInst>(Call) && "intrinsics are handled elsewhere");
3353 
3354       // We are going to insert code that relies on the fact that the callee
3355       // will become a non-readonly function after it is instrumented by us. To
3356       // prevent this code from being optimized out, mark that function
3357       // non-readonly in advance.
3358       if (Function *Func = Call->getCalledFunction()) {
3359         // Clear out readonly/readnone attributes.
3360         AttrBuilder B;
3361         B.addAttribute(Attribute::ReadOnly)
3362             .addAttribute(Attribute::ReadNone)
3363             .addAttribute(Attribute::WriteOnly)
3364             .addAttribute(Attribute::ArgMemOnly)
3365             .addAttribute(Attribute::Speculatable);
3366         Func->removeAttributes(AttributeList::FunctionIndex, B);
3367       }
3368 
3369       maybeMarkSanitizerLibraryCallNoBuiltin(Call, TLI);
3370     }
3371     IRBuilder<> IRB(&CB);
3372 
3373     unsigned ArgOffset = 0;
3374     LLVM_DEBUG(dbgs() << "  CallSite: " << CB << "\n");
3375     for (auto ArgIt = CB.arg_begin(), End = CB.arg_end(); ArgIt != End;
3376          ++ArgIt) {
3377       Value *A = *ArgIt;
3378       unsigned i = ArgIt - CB.arg_begin();
3379       if (!A->getType()->isSized()) {
3380         LLVM_DEBUG(dbgs() << "Arg " << i << " is not sized: " << CB << "\n");
3381         continue;
3382       }
3383       unsigned Size = 0;
3384       Value *Store = nullptr;
3385       // Compute the Shadow for arg even if it is ByVal, because
3386       // in that case getShadow() will copy the actual arg shadow to
3387       // __msan_param_tls.
3388       Value *ArgShadow = getShadow(A);
3389       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
3390       LLVM_DEBUG(dbgs() << "  Arg#" << i << ": " << *A
3391                         << " Shadow: " << *ArgShadow << "\n");
3392       bool ArgIsInitialized = false;
3393       const DataLayout &DL = F.getParent()->getDataLayout();
3394       if (CB.paramHasAttr(i, Attribute::ByVal)) {
3395         assert(A->getType()->isPointerTy() &&
3396                "ByVal argument is not a pointer!");
3397         Size = DL.getTypeAllocSize(CB.getParamByValType(i));
3398         if (ArgOffset + Size > kParamTLSSize) break;
3399         const MaybeAlign ParamAlignment(CB.getParamAlign(i));
3400         MaybeAlign Alignment = llvm::None;
3401         if (ParamAlignment)
3402           Alignment = std::min(*ParamAlignment, kShadowTLSAlignment);
3403         Value *AShadowPtr =
3404             getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), Alignment,
3405                                /*isStore*/ false)
3406                 .first;
3407 
3408         Store = IRB.CreateMemCpy(ArgShadowBase, Alignment, AShadowPtr,
3409                                  Alignment, Size);
3410         // TODO(glider): need to copy origins.
3411       } else {
3412         Size = DL.getTypeAllocSize(A->getType());
3413         if (ArgOffset + Size > kParamTLSSize) break;
3414         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
3415                                        kShadowTLSAlignment);
3416         Constant *Cst = dyn_cast<Constant>(ArgShadow);
3417         if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
3418       }
3419       if (MS.TrackOrigins && !ArgIsInitialized)
3420         IRB.CreateStore(getOrigin(A),
3421                         getOriginPtrForArgument(A, IRB, ArgOffset));
3422       (void)Store;
3423       assert(Size != 0 && Store != nullptr);
3424       LLVM_DEBUG(dbgs() << "  Param:" << *Store << "\n");
3425       ArgOffset += alignTo(Size, 8);
3426     }
3427     LLVM_DEBUG(dbgs() << "  done with call args\n");
3428 
3429     FunctionType *FT = CB.getFunctionType();
3430     if (FT->isVarArg()) {
3431       VAHelper->visitCallBase(CB, IRB);
3432     }
3433 
3434     // Now, get the shadow for the RetVal.
3435     if (!CB.getType()->isSized())
3436       return;
3437     // Don't emit the epilogue for musttail call returns.
3438     if (isa<CallInst>(CB) && cast<CallInst>(CB).isMustTailCall())
3439       return;
3440     IRBuilder<> IRBBefore(&CB);
3441     // Until we have full dynamic coverage, make sure the retval shadow is 0.
3442     Value *Base = getShadowPtrForRetval(&CB, IRBBefore);
3443     IRBBefore.CreateAlignedStore(getCleanShadow(&CB), Base,
3444                                  kShadowTLSAlignment);
3445     BasicBlock::iterator NextInsn;
3446     if (isa<CallInst>(CB)) {
3447       NextInsn = ++CB.getIterator();
3448       assert(NextInsn != CB.getParent()->end());
3449     } else {
3450       BasicBlock *NormalDest = cast<InvokeInst>(CB).getNormalDest();
3451       if (!NormalDest->getSinglePredecessor()) {
3452         // FIXME: this case is tricky, so we are just conservative here.
3453         // Perhaps we need to split the edge between this BB and NormalDest,
3454         // but a naive attempt to use SplitEdge leads to a crash.
3455         setShadow(&CB, getCleanShadow(&CB));
3456         setOrigin(&CB, getCleanOrigin());
3457         return;
3458       }
3459       // FIXME: NextInsn is likely in a basic block that has not been visited yet.
3460       // Anything inserted there will be instrumented by MSan later!
3461       NextInsn = NormalDest->getFirstInsertionPt();
3462       assert(NextInsn != NormalDest->end() &&
3463              "Could not find insertion point for retval shadow load");
3464     }
3465     IRBuilder<> IRBAfter(&*NextInsn);
3466     Value *RetvalShadow = IRBAfter.CreateAlignedLoad(
3467         getShadowTy(&CB), getShadowPtrForRetval(&CB, IRBAfter),
3468         kShadowTLSAlignment, "_msret");
3469     setShadow(&CB, RetvalShadow);
3470     if (MS.TrackOrigins)
3471       setOrigin(&CB, IRBAfter.CreateLoad(MS.OriginTy,
3472                                          getOriginPtrForRetval(IRBAfter)));
3473   }
3474 
3475   bool isAMustTailRetVal(Value *RetVal) {
3476     if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
3477       RetVal = I->getOperand(0);
3478     }
3479     if (auto *I = dyn_cast<CallInst>(RetVal)) {
3480       return I->isMustTailCall();
3481     }
3482     return false;
3483   }
3484 
3485   void visitReturnInst(ReturnInst &I) {
3486     IRBuilder<> IRB(&I);
3487     Value *RetVal = I.getReturnValue();
3488     if (!RetVal) return;
3489     // Don't emit the epilogue for musttail call returns.
3490     if (isAMustTailRetVal(RetVal)) return;
3491     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
3492     if (CheckReturnValue) {
3493       insertShadowCheck(RetVal, &I);
3494       Value *Shadow = getCleanShadow(RetVal);
3495       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
3496     } else {
3497       Value *Shadow = getShadow(RetVal);
3498       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
3499       if (MS.TrackOrigins)
3500         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
3501     }
3502   }
3503 
3504   void visitPHINode(PHINode &I) {
3505     IRBuilder<> IRB(&I);
3506     if (!PropagateShadow) {
3507       setShadow(&I, getCleanShadow(&I));
3508       setOrigin(&I, getCleanOrigin());
3509       return;
3510     }
3511 
3512     ShadowPHINodes.push_back(&I);
3513     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
3514                                 "_msphi_s"));
3515     if (MS.TrackOrigins)
3516       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
3517                                   "_msphi_o"));
3518   }
3519 
3520   Value *getLocalVarDescription(AllocaInst &I) {
3521     SmallString<2048> StackDescriptionStorage;
3522     raw_svector_ostream StackDescription(StackDescriptionStorage);
3523     // We create a string with a description of the stack allocation and
3524     // pass it into __msan_set_alloca_origin.
3525     // It will be printed by the run-time if stack-originated UMR is found.
3526     // The first 4 bytes of the string are set to '----' and will be replaced
3527     // by __msan_va_arg_overflow_size_tls at the first call.
3528     StackDescription << "----" << I.getName() << "@" << F.getName();
3529     return createPrivateNonConstGlobalForString(*F.getParent(),
3530                                                 StackDescription.str());
3531   }
3532 
3533   void poisonAllocaUserspace(AllocaInst &I, IRBuilder<> &IRB, Value *Len) {
3534     if (PoisonStack && ClPoisonStackWithCall) {
3535       IRB.CreateCall(MS.MsanPoisonStackFn,
3536                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len});
3537     } else {
3538       Value *ShadowBase, *OriginBase;
3539       std::tie(ShadowBase, OriginBase) = getShadowOriginPtr(
3540           &I, IRB, IRB.getInt8Ty(), Align(1), /*isStore*/ true);
3541 
3542       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
3543       IRB.CreateMemSet(ShadowBase, PoisonValue, Len,
3544                        MaybeAlign(I.getAlignment()));
3545     }
3546 
3547     if (PoisonStack && MS.TrackOrigins) {
3548       Value *Descr = getLocalVarDescription(I);
3549       IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
3550                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len,
3551                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
3552                       IRB.CreatePointerCast(&F, MS.IntptrTy)});
3553     }
3554   }
3555 
3556   void poisonAllocaKmsan(AllocaInst &I, IRBuilder<> &IRB, Value *Len) {
3557     Value *Descr = getLocalVarDescription(I);
3558     if (PoisonStack) {
3559       IRB.CreateCall(MS.MsanPoisonAllocaFn,
3560                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len,
3561                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy())});
3562     } else {
3563       IRB.CreateCall(MS.MsanUnpoisonAllocaFn,
3564                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len});
3565     }
3566   }
3567 
3568   void instrumentAlloca(AllocaInst &I, Instruction *InsPoint = nullptr) {
3569     if (!InsPoint)
3570       InsPoint = &I;
3571     IRBuilder<> IRB(InsPoint->getNextNode());
3572     const DataLayout &DL = F.getParent()->getDataLayout();
3573     uint64_t TypeSize = DL.getTypeAllocSize(I.getAllocatedType());
3574     Value *Len = ConstantInt::get(MS.IntptrTy, TypeSize);
3575     if (I.isArrayAllocation())
3576       Len = IRB.CreateMul(Len, I.getArraySize());
3577 
3578     if (MS.CompileKernel)
3579       poisonAllocaKmsan(I, IRB, Len);
3580     else
3581       poisonAllocaUserspace(I, IRB, Len);
3582   }
3583 
3584   void visitAllocaInst(AllocaInst &I) {
3585     setShadow(&I, getCleanShadow(&I));
3586     setOrigin(&I, getCleanOrigin());
3587     // We'll get to this alloca later unless it's poisoned at the corresponding
3588     // llvm.lifetime.start.
3589     AllocaSet.insert(&I);
3590   }
3591 
3592   void visitSelectInst(SelectInst& I) {
3593     IRBuilder<> IRB(&I);
3594     // a = select b, c, d
3595     Value *B = I.getCondition();
3596     Value *C = I.getTrueValue();
3597     Value *D = I.getFalseValue();
3598     Value *Sb = getShadow(B);
3599     Value *Sc = getShadow(C);
3600     Value *Sd = getShadow(D);
3601 
3602     // Result shadow if condition shadow is 0.
3603     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
3604     Value *Sa1;
3605     if (I.getType()->isAggregateType()) {
3606       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
3607       // an extra "select". This results in much more compact IR.
3608       // Sa = select Sb, poisoned, (select b, Sc, Sd)
3609       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
3610     } else {
3611       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
3612       // If Sb (condition is poisoned), look for bits in c and d that are equal
3613       // and both unpoisoned.
3614       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
3615 
3616       // Cast arguments to shadow-compatible type.
3617       C = CreateAppToShadowCast(IRB, C);
3618       D = CreateAppToShadowCast(IRB, D);
3619 
3620       // Result shadow if condition shadow is 1.
3621       Sa1 = IRB.CreateOr({IRB.CreateXor(C, D), Sc, Sd});
3622     }
3623     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
3624     setShadow(&I, Sa);
3625     if (MS.TrackOrigins) {
3626       // Origins are always i32, so any vector conditions must be flattened.
3627       // FIXME: consider tracking vector origins for app vectors?
3628       if (B->getType()->isVectorTy()) {
3629         Type *FlatTy = getShadowTyNoVec(B->getType());
3630         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
3631                                 ConstantInt::getNullValue(FlatTy));
3632         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
3633                                       ConstantInt::getNullValue(FlatTy));
3634       }
3635       // a = select b, c, d
3636       // Oa = Sb ? Ob : (b ? Oc : Od)
3637       setOrigin(
3638           &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
3639                                IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
3640                                                 getOrigin(I.getFalseValue()))));
3641     }
3642   }
3643 
3644   void visitLandingPadInst(LandingPadInst &I) {
3645     // Do nothing.
3646     // See https://github.com/google/sanitizers/issues/504
3647     setShadow(&I, getCleanShadow(&I));
3648     setOrigin(&I, getCleanOrigin());
3649   }
3650 
3651   void visitCatchSwitchInst(CatchSwitchInst &I) {
3652     setShadow(&I, getCleanShadow(&I));
3653     setOrigin(&I, getCleanOrigin());
3654   }
3655 
3656   void visitFuncletPadInst(FuncletPadInst &I) {
3657     setShadow(&I, getCleanShadow(&I));
3658     setOrigin(&I, getCleanOrigin());
3659   }
3660 
3661   void visitGetElementPtrInst(GetElementPtrInst &I) {
3662     handleShadowOr(I);
3663   }
3664 
3665   void visitExtractValueInst(ExtractValueInst &I) {
3666     IRBuilder<> IRB(&I);
3667     Value *Agg = I.getAggregateOperand();
3668     LLVM_DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
3669     Value *AggShadow = getShadow(Agg);
3670     LLVM_DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
3671     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
3672     LLVM_DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
3673     setShadow(&I, ResShadow);
3674     setOriginForNaryOp(I);
3675   }
3676 
3677   void visitInsertValueInst(InsertValueInst &I) {
3678     IRBuilder<> IRB(&I);
3679     LLVM_DEBUG(dbgs() << "InsertValue:  " << I << "\n");
3680     Value *AggShadow = getShadow(I.getAggregateOperand());
3681     Value *InsShadow = getShadow(I.getInsertedValueOperand());
3682     LLVM_DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
3683     LLVM_DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
3684     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
3685     LLVM_DEBUG(dbgs() << "   Res:        " << *Res << "\n");
3686     setShadow(&I, Res);
3687     setOriginForNaryOp(I);
3688   }
3689 
3690   void dumpInst(Instruction &I) {
3691     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
3692       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
3693     } else {
3694       errs() << "ZZZ " << I.getOpcodeName() << "\n";
3695     }
3696     errs() << "QQQ " << I << "\n";
3697   }
3698 
3699   void visitResumeInst(ResumeInst &I) {
3700     LLVM_DEBUG(dbgs() << "Resume: " << I << "\n");
3701     // Nothing to do here.
3702   }
3703 
3704   void visitCleanupReturnInst(CleanupReturnInst &CRI) {
3705     LLVM_DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
3706     // Nothing to do here.
3707   }
3708 
3709   void visitCatchReturnInst(CatchReturnInst &CRI) {
3710     LLVM_DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
3711     // Nothing to do here.
3712   }
3713 
3714   void instrumentAsmArgument(Value *Operand, Instruction &I, IRBuilder<> &IRB,
3715                              const DataLayout &DL, bool isOutput) {
3716     // For each assembly argument, we check its value for being initialized.
3717     // If the argument is a pointer, we assume it points to a single element
3718     // of the corresponding type (or to a 8-byte word, if the type is unsized).
3719     // Each such pointer is instrumented with a call to the runtime library.
3720     Type *OpType = Operand->getType();
3721     // Check the operand value itself.
3722     insertShadowCheck(Operand, &I);
3723     if (!OpType->isPointerTy() || !isOutput) {
3724       assert(!isOutput);
3725       return;
3726     }
3727     Type *ElType = OpType->getPointerElementType();
3728     if (!ElType->isSized())
3729       return;
3730     int Size = DL.getTypeStoreSize(ElType);
3731     Value *Ptr = IRB.CreatePointerCast(Operand, IRB.getInt8PtrTy());
3732     Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size);
3733     IRB.CreateCall(MS.MsanInstrumentAsmStoreFn, {Ptr, SizeVal});
3734   }
3735 
3736   /// Get the number of output arguments returned by pointers.
3737   int getNumOutputArgs(InlineAsm *IA, CallBase *CB) {
3738     int NumRetOutputs = 0;
3739     int NumOutputs = 0;
3740     Type *RetTy = cast<Value>(CB)->getType();
3741     if (!RetTy->isVoidTy()) {
3742       // Register outputs are returned via the CallInst return value.
3743       auto *ST = dyn_cast<StructType>(RetTy);
3744       if (ST)
3745         NumRetOutputs = ST->getNumElements();
3746       else
3747         NumRetOutputs = 1;
3748     }
3749     InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
3750     for (size_t i = 0, n = Constraints.size(); i < n; i++) {
3751       InlineAsm::ConstraintInfo Info = Constraints[i];
3752       switch (Info.Type) {
3753       case InlineAsm::isOutput:
3754         NumOutputs++;
3755         break;
3756       default:
3757         break;
3758       }
3759     }
3760     return NumOutputs - NumRetOutputs;
3761   }
3762 
3763   void visitAsmInstruction(Instruction &I) {
3764     // Conservative inline assembly handling: check for poisoned shadow of
3765     // asm() arguments, then unpoison the result and all the memory locations
3766     // pointed to by those arguments.
3767     // An inline asm() statement in C++ contains lists of input and output
3768     // arguments used by the assembly code. These are mapped to operands of the
3769     // CallInst as follows:
3770     //  - nR register outputs ("=r) are returned by value in a single structure
3771     //  (SSA value of the CallInst);
3772     //  - nO other outputs ("=m" and others) are returned by pointer as first
3773     // nO operands of the CallInst;
3774     //  - nI inputs ("r", "m" and others) are passed to CallInst as the
3775     // remaining nI operands.
3776     // The total number of asm() arguments in the source is nR+nO+nI, and the
3777     // corresponding CallInst has nO+nI+1 operands (the last operand is the
3778     // function to be called).
3779     const DataLayout &DL = F.getParent()->getDataLayout();
3780     CallBase *CB = cast<CallBase>(&I);
3781     IRBuilder<> IRB(&I);
3782     InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
3783     int OutputArgs = getNumOutputArgs(IA, CB);
3784     // The last operand of a CallInst is the function itself.
3785     int NumOperands = CB->getNumOperands() - 1;
3786 
3787     // Check input arguments. Doing so before unpoisoning output arguments, so
3788     // that we won't overwrite uninit values before checking them.
3789     for (int i = OutputArgs; i < NumOperands; i++) {
3790       Value *Operand = CB->getOperand(i);
3791       instrumentAsmArgument(Operand, I, IRB, DL, /*isOutput*/ false);
3792     }
3793     // Unpoison output arguments. This must happen before the actual InlineAsm
3794     // call, so that the shadow for memory published in the asm() statement
3795     // remains valid.
3796     for (int i = 0; i < OutputArgs; i++) {
3797       Value *Operand = CB->getOperand(i);
3798       instrumentAsmArgument(Operand, I, IRB, DL, /*isOutput*/ true);
3799     }
3800 
3801     setShadow(&I, getCleanShadow(&I));
3802     setOrigin(&I, getCleanOrigin());
3803   }
3804 
3805   void visitInstruction(Instruction &I) {
3806     // Everything else: stop propagating and check for poisoned shadow.
3807     if (ClDumpStrictInstructions)
3808       dumpInst(I);
3809     LLVM_DEBUG(dbgs() << "DEFAULT: " << I << "\n");
3810     for (size_t i = 0, n = I.getNumOperands(); i < n; i++) {
3811       Value *Operand = I.getOperand(i);
3812       if (Operand->getType()->isSized())
3813         insertShadowCheck(Operand, &I);
3814     }
3815     setShadow(&I, getCleanShadow(&I));
3816     setOrigin(&I, getCleanOrigin());
3817   }
3818 };
3819 
3820 /// AMD64-specific implementation of VarArgHelper.
3821 struct VarArgAMD64Helper : public VarArgHelper {
3822   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
3823   // See a comment in visitCallBase for more details.
3824   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
3825   static const unsigned AMD64FpEndOffsetSSE = 176;
3826   // If SSE is disabled, fp_offset in va_list is zero.
3827   static const unsigned AMD64FpEndOffsetNoSSE = AMD64GpEndOffset;
3828 
3829   unsigned AMD64FpEndOffset;
3830   Function &F;
3831   MemorySanitizer &MS;
3832   MemorySanitizerVisitor &MSV;
3833   Value *VAArgTLSCopy = nullptr;
3834   Value *VAArgTLSOriginCopy = nullptr;
3835   Value *VAArgOverflowSize = nullptr;
3836 
3837   SmallVector<CallInst*, 16> VAStartInstrumentationList;
3838 
3839   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
3840 
3841   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
3842                     MemorySanitizerVisitor &MSV)
3843       : F(F), MS(MS), MSV(MSV) {
3844     AMD64FpEndOffset = AMD64FpEndOffsetSSE;
3845     for (const auto &Attr : F.getAttributes().getFnAttributes()) {
3846       if (Attr.isStringAttribute() &&
3847           (Attr.getKindAsString() == "target-features")) {
3848         if (Attr.getValueAsString().contains("-sse"))
3849           AMD64FpEndOffset = AMD64FpEndOffsetNoSSE;
3850         break;
3851       }
3852     }
3853   }
3854 
3855   ArgKind classifyArgument(Value* arg) {
3856     // A very rough approximation of X86_64 argument classification rules.
3857     Type *T = arg->getType();
3858     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
3859       return AK_FloatingPoint;
3860     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
3861       return AK_GeneralPurpose;
3862     if (T->isPointerTy())
3863       return AK_GeneralPurpose;
3864     return AK_Memory;
3865   }
3866 
3867   // For VarArg functions, store the argument shadow in an ABI-specific format
3868   // that corresponds to va_list layout.
3869   // We do this because Clang lowers va_arg in the frontend, and this pass
3870   // only sees the low level code that deals with va_list internals.
3871   // A much easier alternative (provided that Clang emits va_arg instructions)
3872   // would have been to associate each live instance of va_list with a copy of
3873   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
3874   // order.
3875   void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
3876     unsigned GpOffset = 0;
3877     unsigned FpOffset = AMD64GpEndOffset;
3878     unsigned OverflowOffset = AMD64FpEndOffset;
3879     const DataLayout &DL = F.getParent()->getDataLayout();
3880     for (auto ArgIt = CB.arg_begin(), End = CB.arg_end(); ArgIt != End;
3881          ++ArgIt) {
3882       Value *A = *ArgIt;
3883       unsigned ArgNo = CB.getArgOperandNo(ArgIt);
3884       bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
3885       bool IsByVal = CB.paramHasAttr(ArgNo, Attribute::ByVal);
3886       if (IsByVal) {
3887         // ByVal arguments always go to the overflow area.
3888         // Fixed arguments passed through the overflow area will be stepped
3889         // over by va_start, so don't count them towards the offset.
3890         if (IsFixed)
3891           continue;
3892         assert(A->getType()->isPointerTy());
3893         Type *RealTy = CB.getParamByValType(ArgNo);
3894         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
3895         Value *ShadowBase = getShadowPtrForVAArgument(
3896             RealTy, IRB, OverflowOffset, alignTo(ArgSize, 8));
3897         Value *OriginBase = nullptr;
3898         if (MS.TrackOrigins)
3899           OriginBase = getOriginPtrForVAArgument(RealTy, IRB, OverflowOffset);
3900         OverflowOffset += alignTo(ArgSize, 8);
3901         if (!ShadowBase)
3902           continue;
3903         Value *ShadowPtr, *OriginPtr;
3904         std::tie(ShadowPtr, OriginPtr) =
3905             MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), kShadowTLSAlignment,
3906                                    /*isStore*/ false);
3907 
3908         IRB.CreateMemCpy(ShadowBase, kShadowTLSAlignment, ShadowPtr,
3909                          kShadowTLSAlignment, ArgSize);
3910         if (MS.TrackOrigins)
3911           IRB.CreateMemCpy(OriginBase, kShadowTLSAlignment, OriginPtr,
3912                            kShadowTLSAlignment, ArgSize);
3913       } else {
3914         ArgKind AK = classifyArgument(A);
3915         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
3916           AK = AK_Memory;
3917         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
3918           AK = AK_Memory;
3919         Value *ShadowBase, *OriginBase = nullptr;
3920         switch (AK) {
3921           case AK_GeneralPurpose:
3922             ShadowBase =
3923                 getShadowPtrForVAArgument(A->getType(), IRB, GpOffset, 8);
3924             if (MS.TrackOrigins)
3925               OriginBase =
3926                   getOriginPtrForVAArgument(A->getType(), IRB, GpOffset);
3927             GpOffset += 8;
3928             break;
3929           case AK_FloatingPoint:
3930             ShadowBase =
3931                 getShadowPtrForVAArgument(A->getType(), IRB, FpOffset, 16);
3932             if (MS.TrackOrigins)
3933               OriginBase =
3934                   getOriginPtrForVAArgument(A->getType(), IRB, FpOffset);
3935             FpOffset += 16;
3936             break;
3937           case AK_Memory:
3938             if (IsFixed)
3939               continue;
3940             uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
3941             ShadowBase =
3942                 getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset, 8);
3943             if (MS.TrackOrigins)
3944               OriginBase =
3945                   getOriginPtrForVAArgument(A->getType(), IRB, OverflowOffset);
3946             OverflowOffset += alignTo(ArgSize, 8);
3947         }
3948         // Take fixed arguments into account for GpOffset and FpOffset,
3949         // but don't actually store shadows for them.
3950         // TODO(glider): don't call get*PtrForVAArgument() for them.
3951         if (IsFixed)
3952           continue;
3953         if (!ShadowBase)
3954           continue;
3955         Value *Shadow = MSV.getShadow(A);
3956         IRB.CreateAlignedStore(Shadow, ShadowBase, kShadowTLSAlignment);
3957         if (MS.TrackOrigins) {
3958           Value *Origin = MSV.getOrigin(A);
3959           unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
3960           MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize,
3961                           std::max(kShadowTLSAlignment, kMinOriginAlignment));
3962         }
3963       }
3964     }
3965     Constant *OverflowSize =
3966       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
3967     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
3968   }
3969 
3970   /// Compute the shadow address for a given va_arg.
3971   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3972                                    unsigned ArgOffset, unsigned ArgSize) {
3973     // Make sure we don't overflow __msan_va_arg_tls.
3974     if (ArgOffset + ArgSize > kParamTLSSize)
3975       return nullptr;
3976     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3977     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3978     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3979                               "_msarg_va_s");
3980   }
3981 
3982   /// Compute the origin address for a given va_arg.
3983   Value *getOriginPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, int ArgOffset) {
3984     Value *Base = IRB.CreatePointerCast(MS.VAArgOriginTLS, MS.IntptrTy);
3985     // getOriginPtrForVAArgument() is always called after
3986     // getShadowPtrForVAArgument(), so __msan_va_arg_origin_tls can never
3987     // overflow.
3988     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3989     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
3990                               "_msarg_va_o");
3991   }
3992 
3993   void unpoisonVAListTagForInst(IntrinsicInst &I) {
3994     IRBuilder<> IRB(&I);
3995     Value *VAListTag = I.getArgOperand(0);
3996     Value *ShadowPtr, *OriginPtr;
3997     const Align Alignment = Align(8);
3998     std::tie(ShadowPtr, OriginPtr) =
3999         MSV.getShadowOriginPtr(VAListTag, IRB, IRB.getInt8Ty(), Alignment,
4000                                /*isStore*/ true);
4001 
4002     // Unpoison the whole __va_list_tag.
4003     // FIXME: magic ABI constants.
4004     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4005                      /* size */ 24, Alignment, false);
4006     // We shouldn't need to zero out the origins, as they're only checked for
4007     // nonzero shadow.
4008   }
4009 
4010   void visitVAStartInst(VAStartInst &I) override {
4011     if (F.getCallingConv() == CallingConv::Win64)
4012       return;
4013     VAStartInstrumentationList.push_back(&I);
4014     unpoisonVAListTagForInst(I);
4015   }
4016 
4017   void visitVACopyInst(VACopyInst &I) override {
4018     if (F.getCallingConv() == CallingConv::Win64) return;
4019     unpoisonVAListTagForInst(I);
4020   }
4021 
4022   void finalizeInstrumentation() override {
4023     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
4024            "finalizeInstrumentation called twice");
4025     if (!VAStartInstrumentationList.empty()) {
4026       // If there is a va_start in this function, make a backup copy of
4027       // va_arg_tls somewhere in the function entry block.
4028       IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4029       VAArgOverflowSize =
4030           IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4031       Value *CopySize =
4032         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
4033                       VAArgOverflowSize);
4034       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4035       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4036       if (MS.TrackOrigins) {
4037         VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4038         IRB.CreateMemCpy(VAArgTLSOriginCopy, Align(8), MS.VAArgOriginTLS,
4039                          Align(8), CopySize);
4040       }
4041     }
4042 
4043     // Instrument va_start.
4044     // Copy va_list shadow from the backup copy of the TLS contents.
4045     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4046       CallInst *OrigInst = VAStartInstrumentationList[i];
4047       IRBuilder<> IRB(OrigInst->getNextNode());
4048       Value *VAListTag = OrigInst->getArgOperand(0);
4049 
4050       Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4051       Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr(
4052           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4053                         ConstantInt::get(MS.IntptrTy, 16)),
4054           PointerType::get(RegSaveAreaPtrTy, 0));
4055       Value *RegSaveAreaPtr =
4056           IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr);
4057       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
4058       const Align Alignment = Align(16);
4059       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
4060           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4061                                  Alignment, /*isStore*/ true);
4062       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
4063                        AMD64FpEndOffset);
4064       if (MS.TrackOrigins)
4065         IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy,
4066                          Alignment, AMD64FpEndOffset);
4067       Type *OverflowArgAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4068       Value *OverflowArgAreaPtrPtr = IRB.CreateIntToPtr(
4069           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4070                         ConstantInt::get(MS.IntptrTy, 8)),
4071           PointerType::get(OverflowArgAreaPtrTy, 0));
4072       Value *OverflowArgAreaPtr =
4073           IRB.CreateLoad(OverflowArgAreaPtrTy, OverflowArgAreaPtrPtr);
4074       Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr;
4075       std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) =
4076           MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(),
4077                                  Alignment, /*isStore*/ true);
4078       Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
4079                                              AMD64FpEndOffset);
4080       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment,
4081                        VAArgOverflowSize);
4082       if (MS.TrackOrigins) {
4083         SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy,
4084                                         AMD64FpEndOffset);
4085         IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment,
4086                          VAArgOverflowSize);
4087       }
4088     }
4089   }
4090 };
4091 
4092 /// MIPS64-specific implementation of VarArgHelper.
4093 struct VarArgMIPS64Helper : public VarArgHelper {
4094   Function &F;
4095   MemorySanitizer &MS;
4096   MemorySanitizerVisitor &MSV;
4097   Value *VAArgTLSCopy = nullptr;
4098   Value *VAArgSize = nullptr;
4099 
4100   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4101 
4102   VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
4103                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4104 
4105   void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
4106     unsigned VAArgOffset = 0;
4107     const DataLayout &DL = F.getParent()->getDataLayout();
4108     for (auto ArgIt = CB.arg_begin() + CB.getFunctionType()->getNumParams(),
4109               End = CB.arg_end();
4110          ArgIt != End; ++ArgIt) {
4111       Triple TargetTriple(F.getParent()->getTargetTriple());
4112       Value *A = *ArgIt;
4113       Value *Base;
4114       uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4115       if (TargetTriple.getArch() == Triple::mips64) {
4116         // Adjusting the shadow for argument with size < 8 to match the placement
4117         // of bits in big endian system
4118         if (ArgSize < 8)
4119           VAArgOffset += (8 - ArgSize);
4120       }
4121       Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset, ArgSize);
4122       VAArgOffset += ArgSize;
4123       VAArgOffset = alignTo(VAArgOffset, 8);
4124       if (!Base)
4125         continue;
4126       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4127     }
4128 
4129     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
4130     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
4131     // a new class member i.e. it is the total size of all VarArgs.
4132     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
4133   }
4134 
4135   /// Compute the shadow address for a given va_arg.
4136   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4137                                    unsigned ArgOffset, unsigned ArgSize) {
4138     // Make sure we don't overflow __msan_va_arg_tls.
4139     if (ArgOffset + ArgSize > kParamTLSSize)
4140       return nullptr;
4141     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4142     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4143     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4144                               "_msarg");
4145   }
4146 
4147   void visitVAStartInst(VAStartInst &I) override {
4148     IRBuilder<> IRB(&I);
4149     VAStartInstrumentationList.push_back(&I);
4150     Value *VAListTag = I.getArgOperand(0);
4151     Value *ShadowPtr, *OriginPtr;
4152     const Align Alignment = Align(8);
4153     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4154         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4155     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4156                      /* size */ 8, Alignment, false);
4157   }
4158 
4159   void visitVACopyInst(VACopyInst &I) override {
4160     IRBuilder<> IRB(&I);
4161     VAStartInstrumentationList.push_back(&I);
4162     Value *VAListTag = I.getArgOperand(0);
4163     Value *ShadowPtr, *OriginPtr;
4164     const Align Alignment = Align(8);
4165     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4166         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4167     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4168                      /* size */ 8, Alignment, false);
4169   }
4170 
4171   void finalizeInstrumentation() override {
4172     assert(!VAArgSize && !VAArgTLSCopy &&
4173            "finalizeInstrumentation called twice");
4174     IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4175     VAArgSize = IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4176     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
4177                                     VAArgSize);
4178 
4179     if (!VAStartInstrumentationList.empty()) {
4180       // If there is a va_start in this function, make a backup copy of
4181       // va_arg_tls somewhere in the function entry block.
4182       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4183       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4184     }
4185 
4186     // Instrument va_start.
4187     // Copy va_list shadow from the backup copy of the TLS contents.
4188     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4189       CallInst *OrigInst = VAStartInstrumentationList[i];
4190       IRBuilder<> IRB(OrigInst->getNextNode());
4191       Value *VAListTag = OrigInst->getArgOperand(0);
4192       Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4193       Value *RegSaveAreaPtrPtr =
4194           IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4195                              PointerType::get(RegSaveAreaPtrTy, 0));
4196       Value *RegSaveAreaPtr =
4197           IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr);
4198       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
4199       const Align Alignment = Align(8);
4200       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
4201           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4202                                  Alignment, /*isStore*/ true);
4203       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
4204                        CopySize);
4205     }
4206   }
4207 };
4208 
4209 /// AArch64-specific implementation of VarArgHelper.
4210 struct VarArgAArch64Helper : public VarArgHelper {
4211   static const unsigned kAArch64GrArgSize = 64;
4212   static const unsigned kAArch64VrArgSize = 128;
4213 
4214   static const unsigned AArch64GrBegOffset = 0;
4215   static const unsigned AArch64GrEndOffset = kAArch64GrArgSize;
4216   // Make VR space aligned to 16 bytes.
4217   static const unsigned AArch64VrBegOffset = AArch64GrEndOffset;
4218   static const unsigned AArch64VrEndOffset = AArch64VrBegOffset
4219                                              + kAArch64VrArgSize;
4220   static const unsigned AArch64VAEndOffset = AArch64VrEndOffset;
4221 
4222   Function &F;
4223   MemorySanitizer &MS;
4224   MemorySanitizerVisitor &MSV;
4225   Value *VAArgTLSCopy = nullptr;
4226   Value *VAArgOverflowSize = nullptr;
4227 
4228   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4229 
4230   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
4231 
4232   VarArgAArch64Helper(Function &F, MemorySanitizer &MS,
4233                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4234 
4235   ArgKind classifyArgument(Value* arg) {
4236     Type *T = arg->getType();
4237     if (T->isFPOrFPVectorTy())
4238       return AK_FloatingPoint;
4239     if ((T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
4240         || (T->isPointerTy()))
4241       return AK_GeneralPurpose;
4242     return AK_Memory;
4243   }
4244 
4245   // The instrumentation stores the argument shadow in a non ABI-specific
4246   // format because it does not know which argument is named (since Clang,
4247   // like x86_64 case, lowers the va_args in the frontend and this pass only
4248   // sees the low level code that deals with va_list internals).
4249   // The first seven GR registers are saved in the first 56 bytes of the
4250   // va_arg tls arra, followers by the first 8 FP/SIMD registers, and then
4251   // the remaining arguments.
4252   // Using constant offset within the va_arg TLS array allows fast copy
4253   // in the finalize instrumentation.
4254   void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
4255     unsigned GrOffset = AArch64GrBegOffset;
4256     unsigned VrOffset = AArch64VrBegOffset;
4257     unsigned OverflowOffset = AArch64VAEndOffset;
4258 
4259     const DataLayout &DL = F.getParent()->getDataLayout();
4260     for (auto ArgIt = CB.arg_begin(), End = CB.arg_end(); ArgIt != End;
4261          ++ArgIt) {
4262       Value *A = *ArgIt;
4263       unsigned ArgNo = CB.getArgOperandNo(ArgIt);
4264       bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
4265       ArgKind AK = classifyArgument(A);
4266       if (AK == AK_GeneralPurpose && GrOffset >= AArch64GrEndOffset)
4267         AK = AK_Memory;
4268       if (AK == AK_FloatingPoint && VrOffset >= AArch64VrEndOffset)
4269         AK = AK_Memory;
4270       Value *Base;
4271       switch (AK) {
4272         case AK_GeneralPurpose:
4273           Base = getShadowPtrForVAArgument(A->getType(), IRB, GrOffset, 8);
4274           GrOffset += 8;
4275           break;
4276         case AK_FloatingPoint:
4277           Base = getShadowPtrForVAArgument(A->getType(), IRB, VrOffset, 8);
4278           VrOffset += 16;
4279           break;
4280         case AK_Memory:
4281           // Don't count fixed arguments in the overflow area - va_start will
4282           // skip right over them.
4283           if (IsFixed)
4284             continue;
4285           uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4286           Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset,
4287                                            alignTo(ArgSize, 8));
4288           OverflowOffset += alignTo(ArgSize, 8);
4289           break;
4290       }
4291       // Count Gp/Vr fixed arguments to their respective offsets, but don't
4292       // bother to actually store a shadow.
4293       if (IsFixed)
4294         continue;
4295       if (!Base)
4296         continue;
4297       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4298     }
4299     Constant *OverflowSize =
4300       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AArch64VAEndOffset);
4301     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
4302   }
4303 
4304   /// Compute the shadow address for a given va_arg.
4305   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4306                                    unsigned ArgOffset, unsigned ArgSize) {
4307     // Make sure we don't overflow __msan_va_arg_tls.
4308     if (ArgOffset + ArgSize > kParamTLSSize)
4309       return nullptr;
4310     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4311     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4312     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4313                               "_msarg");
4314   }
4315 
4316   void visitVAStartInst(VAStartInst &I) override {
4317     IRBuilder<> IRB(&I);
4318     VAStartInstrumentationList.push_back(&I);
4319     Value *VAListTag = I.getArgOperand(0);
4320     Value *ShadowPtr, *OriginPtr;
4321     const Align Alignment = Align(8);
4322     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4323         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4324     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4325                      /* size */ 32, Alignment, false);
4326   }
4327 
4328   void visitVACopyInst(VACopyInst &I) override {
4329     IRBuilder<> IRB(&I);
4330     VAStartInstrumentationList.push_back(&I);
4331     Value *VAListTag = I.getArgOperand(0);
4332     Value *ShadowPtr, *OriginPtr;
4333     const Align Alignment = Align(8);
4334     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4335         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4336     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4337                      /* size */ 32, Alignment, false);
4338   }
4339 
4340   // Retrieve a va_list field of 'void*' size.
4341   Value* getVAField64(IRBuilder<> &IRB, Value *VAListTag, int offset) {
4342     Value *SaveAreaPtrPtr =
4343       IRB.CreateIntToPtr(
4344         IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4345                       ConstantInt::get(MS.IntptrTy, offset)),
4346         Type::getInt64PtrTy(*MS.C));
4347     return IRB.CreateLoad(Type::getInt64Ty(*MS.C), SaveAreaPtrPtr);
4348   }
4349 
4350   // Retrieve a va_list field of 'int' size.
4351   Value* getVAField32(IRBuilder<> &IRB, Value *VAListTag, int offset) {
4352     Value *SaveAreaPtr =
4353       IRB.CreateIntToPtr(
4354         IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4355                       ConstantInt::get(MS.IntptrTy, offset)),
4356         Type::getInt32PtrTy(*MS.C));
4357     Value *SaveArea32 = IRB.CreateLoad(IRB.getInt32Ty(), SaveAreaPtr);
4358     return IRB.CreateSExt(SaveArea32, MS.IntptrTy);
4359   }
4360 
4361   void finalizeInstrumentation() override {
4362     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
4363            "finalizeInstrumentation called twice");
4364     if (!VAStartInstrumentationList.empty()) {
4365       // If there is a va_start in this function, make a backup copy of
4366       // va_arg_tls somewhere in the function entry block.
4367       IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4368       VAArgOverflowSize =
4369           IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4370       Value *CopySize =
4371         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AArch64VAEndOffset),
4372                       VAArgOverflowSize);
4373       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4374       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4375     }
4376 
4377     Value *GrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64GrArgSize);
4378     Value *VrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64VrArgSize);
4379 
4380     // Instrument va_start, copy va_list shadow from the backup copy of
4381     // the TLS contents.
4382     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4383       CallInst *OrigInst = VAStartInstrumentationList[i];
4384       IRBuilder<> IRB(OrigInst->getNextNode());
4385 
4386       Value *VAListTag = OrigInst->getArgOperand(0);
4387 
4388       // The variadic ABI for AArch64 creates two areas to save the incoming
4389       // argument registers (one for 64-bit general register xn-x7 and another
4390       // for 128-bit FP/SIMD vn-v7).
4391       // We need then to propagate the shadow arguments on both regions
4392       // 'va::__gr_top + va::__gr_offs' and 'va::__vr_top + va::__vr_offs'.
4393       // The remaining arguments are saved on shadow for 'va::stack'.
4394       // One caveat is it requires only to propagate the non-named arguments,
4395       // however on the call site instrumentation 'all' the arguments are
4396       // saved. So to copy the shadow values from the va_arg TLS array
4397       // we need to adjust the offset for both GR and VR fields based on
4398       // the __{gr,vr}_offs value (since they are stores based on incoming
4399       // named arguments).
4400 
4401       // Read the stack pointer from the va_list.
4402       Value *StackSaveAreaPtr = getVAField64(IRB, VAListTag, 0);
4403 
4404       // Read both the __gr_top and __gr_off and add them up.
4405       Value *GrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 8);
4406       Value *GrOffSaveArea = getVAField32(IRB, VAListTag, 24);
4407 
4408       Value *GrRegSaveAreaPtr = IRB.CreateAdd(GrTopSaveAreaPtr, GrOffSaveArea);
4409 
4410       // Read both the __vr_top and __vr_off and add them up.
4411       Value *VrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 16);
4412       Value *VrOffSaveArea = getVAField32(IRB, VAListTag, 28);
4413 
4414       Value *VrRegSaveAreaPtr = IRB.CreateAdd(VrTopSaveAreaPtr, VrOffSaveArea);
4415 
4416       // It does not know how many named arguments is being used and, on the
4417       // callsite all the arguments were saved.  Since __gr_off is defined as
4418       // '0 - ((8 - named_gr) * 8)', the idea is to just propagate the variadic
4419       // argument by ignoring the bytes of shadow from named arguments.
4420       Value *GrRegSaveAreaShadowPtrOff =
4421         IRB.CreateAdd(GrArgSize, GrOffSaveArea);
4422 
4423       Value *GrRegSaveAreaShadowPtr =
4424           MSV.getShadowOriginPtr(GrRegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4425                                  Align(8), /*isStore*/ true)
4426               .first;
4427 
4428       Value *GrSrcPtr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4429                                               GrRegSaveAreaShadowPtrOff);
4430       Value *GrCopySize = IRB.CreateSub(GrArgSize, GrRegSaveAreaShadowPtrOff);
4431 
4432       IRB.CreateMemCpy(GrRegSaveAreaShadowPtr, Align(8), GrSrcPtr, Align(8),
4433                        GrCopySize);
4434 
4435       // Again, but for FP/SIMD values.
4436       Value *VrRegSaveAreaShadowPtrOff =
4437           IRB.CreateAdd(VrArgSize, VrOffSaveArea);
4438 
4439       Value *VrRegSaveAreaShadowPtr =
4440           MSV.getShadowOriginPtr(VrRegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4441                                  Align(8), /*isStore*/ true)
4442               .first;
4443 
4444       Value *VrSrcPtr = IRB.CreateInBoundsGEP(
4445         IRB.getInt8Ty(),
4446         IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4447                               IRB.getInt32(AArch64VrBegOffset)),
4448         VrRegSaveAreaShadowPtrOff);
4449       Value *VrCopySize = IRB.CreateSub(VrArgSize, VrRegSaveAreaShadowPtrOff);
4450 
4451       IRB.CreateMemCpy(VrRegSaveAreaShadowPtr, Align(8), VrSrcPtr, Align(8),
4452                        VrCopySize);
4453 
4454       // And finally for remaining arguments.
4455       Value *StackSaveAreaShadowPtr =
4456           MSV.getShadowOriginPtr(StackSaveAreaPtr, IRB, IRB.getInt8Ty(),
4457                                  Align(16), /*isStore*/ true)
4458               .first;
4459 
4460       Value *StackSrcPtr =
4461         IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4462                               IRB.getInt32(AArch64VAEndOffset));
4463 
4464       IRB.CreateMemCpy(StackSaveAreaShadowPtr, Align(16), StackSrcPtr,
4465                        Align(16), VAArgOverflowSize);
4466     }
4467   }
4468 };
4469 
4470 /// PowerPC64-specific implementation of VarArgHelper.
4471 struct VarArgPowerPC64Helper : public VarArgHelper {
4472   Function &F;
4473   MemorySanitizer &MS;
4474   MemorySanitizerVisitor &MSV;
4475   Value *VAArgTLSCopy = nullptr;
4476   Value *VAArgSize = nullptr;
4477 
4478   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4479 
4480   VarArgPowerPC64Helper(Function &F, MemorySanitizer &MS,
4481                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4482 
4483   void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
4484     // For PowerPC, we need to deal with alignment of stack arguments -
4485     // they are mostly aligned to 8 bytes, but vectors and i128 arrays
4486     // are aligned to 16 bytes, byvals can be aligned to 8 or 16 bytes,
4487     // and QPX vectors are aligned to 32 bytes.  For that reason, we
4488     // compute current offset from stack pointer (which is always properly
4489     // aligned), and offset for the first vararg, then subtract them.
4490     unsigned VAArgBase;
4491     Triple TargetTriple(F.getParent()->getTargetTriple());
4492     // Parameter save area starts at 48 bytes from frame pointer for ABIv1,
4493     // and 32 bytes for ABIv2.  This is usually determined by target
4494     // endianness, but in theory could be overridden by function attribute.
4495     // For simplicity, we ignore it here (it'd only matter for QPX vectors).
4496     if (TargetTriple.getArch() == Triple::ppc64)
4497       VAArgBase = 48;
4498     else
4499       VAArgBase = 32;
4500     unsigned VAArgOffset = VAArgBase;
4501     const DataLayout &DL = F.getParent()->getDataLayout();
4502     for (auto ArgIt = CB.arg_begin(), End = CB.arg_end(); ArgIt != End;
4503          ++ArgIt) {
4504       Value *A = *ArgIt;
4505       unsigned ArgNo = CB.getArgOperandNo(ArgIt);
4506       bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
4507       bool IsByVal = CB.paramHasAttr(ArgNo, Attribute::ByVal);
4508       if (IsByVal) {
4509         assert(A->getType()->isPointerTy());
4510         Type *RealTy = CB.getParamByValType(ArgNo);
4511         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
4512         MaybeAlign ArgAlign = CB.getParamAlign(ArgNo);
4513         if (!ArgAlign || *ArgAlign < Align(8))
4514           ArgAlign = Align(8);
4515         VAArgOffset = alignTo(VAArgOffset, ArgAlign);
4516         if (!IsFixed) {
4517           Value *Base = getShadowPtrForVAArgument(
4518               RealTy, IRB, VAArgOffset - VAArgBase, ArgSize);
4519           if (Base) {
4520             Value *AShadowPtr, *AOriginPtr;
4521             std::tie(AShadowPtr, AOriginPtr) =
4522                 MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(),
4523                                        kShadowTLSAlignment, /*isStore*/ false);
4524 
4525             IRB.CreateMemCpy(Base, kShadowTLSAlignment, AShadowPtr,
4526                              kShadowTLSAlignment, ArgSize);
4527           }
4528         }
4529         VAArgOffset += alignTo(ArgSize, 8);
4530       } else {
4531         Value *Base;
4532         uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4533         uint64_t ArgAlign = 8;
4534         if (A->getType()->isArrayTy()) {
4535           // Arrays are aligned to element size, except for long double
4536           // arrays, which are aligned to 8 bytes.
4537           Type *ElementTy = A->getType()->getArrayElementType();
4538           if (!ElementTy->isPPC_FP128Ty())
4539             ArgAlign = DL.getTypeAllocSize(ElementTy);
4540         } else if (A->getType()->isVectorTy()) {
4541           // Vectors are naturally aligned.
4542           ArgAlign = DL.getTypeAllocSize(A->getType());
4543         }
4544         if (ArgAlign < 8)
4545           ArgAlign = 8;
4546         VAArgOffset = alignTo(VAArgOffset, ArgAlign);
4547         if (DL.isBigEndian()) {
4548           // Adjusting the shadow for argument with size < 8 to match the placement
4549           // of bits in big endian system
4550           if (ArgSize < 8)
4551             VAArgOffset += (8 - ArgSize);
4552         }
4553         if (!IsFixed) {
4554           Base = getShadowPtrForVAArgument(A->getType(), IRB,
4555                                            VAArgOffset - VAArgBase, ArgSize);
4556           if (Base)
4557             IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4558         }
4559         VAArgOffset += ArgSize;
4560         VAArgOffset = alignTo(VAArgOffset, 8);
4561       }
4562       if (IsFixed)
4563         VAArgBase = VAArgOffset;
4564     }
4565 
4566     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(),
4567                                                 VAArgOffset - VAArgBase);
4568     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
4569     // a new class member i.e. it is the total size of all VarArgs.
4570     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
4571   }
4572 
4573   /// Compute the shadow address for a given va_arg.
4574   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4575                                    unsigned ArgOffset, unsigned ArgSize) {
4576     // Make sure we don't overflow __msan_va_arg_tls.
4577     if (ArgOffset + ArgSize > kParamTLSSize)
4578       return nullptr;
4579     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4580     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4581     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4582                               "_msarg");
4583   }
4584 
4585   void visitVAStartInst(VAStartInst &I) override {
4586     IRBuilder<> IRB(&I);
4587     VAStartInstrumentationList.push_back(&I);
4588     Value *VAListTag = I.getArgOperand(0);
4589     Value *ShadowPtr, *OriginPtr;
4590     const Align Alignment = Align(8);
4591     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4592         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4593     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4594                      /* size */ 8, Alignment, false);
4595   }
4596 
4597   void visitVACopyInst(VACopyInst &I) override {
4598     IRBuilder<> IRB(&I);
4599     Value *VAListTag = I.getArgOperand(0);
4600     Value *ShadowPtr, *OriginPtr;
4601     const Align Alignment = Align(8);
4602     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4603         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4604     // Unpoison the whole __va_list_tag.
4605     // FIXME: magic ABI constants.
4606     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4607                      /* size */ 8, Alignment, false);
4608   }
4609 
4610   void finalizeInstrumentation() override {
4611     assert(!VAArgSize && !VAArgTLSCopy &&
4612            "finalizeInstrumentation called twice");
4613     IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4614     VAArgSize = IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4615     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
4616                                     VAArgSize);
4617 
4618     if (!VAStartInstrumentationList.empty()) {
4619       // If there is a va_start in this function, make a backup copy of
4620       // va_arg_tls somewhere in the function entry block.
4621       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4622       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4623     }
4624 
4625     // Instrument va_start.
4626     // Copy va_list shadow from the backup copy of the TLS contents.
4627     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4628       CallInst *OrigInst = VAStartInstrumentationList[i];
4629       IRBuilder<> IRB(OrigInst->getNextNode());
4630       Value *VAListTag = OrigInst->getArgOperand(0);
4631       Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4632       Value *RegSaveAreaPtrPtr =
4633           IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4634                              PointerType::get(RegSaveAreaPtrTy, 0));
4635       Value *RegSaveAreaPtr =
4636           IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr);
4637       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
4638       const Align Alignment = Align(8);
4639       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
4640           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4641                                  Alignment, /*isStore*/ true);
4642       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
4643                        CopySize);
4644     }
4645   }
4646 };
4647 
4648 /// SystemZ-specific implementation of VarArgHelper.
4649 struct VarArgSystemZHelper : public VarArgHelper {
4650   static const unsigned SystemZGpOffset = 16;
4651   static const unsigned SystemZGpEndOffset = 56;
4652   static const unsigned SystemZFpOffset = 128;
4653   static const unsigned SystemZFpEndOffset = 160;
4654   static const unsigned SystemZMaxVrArgs = 8;
4655   static const unsigned SystemZRegSaveAreaSize = 160;
4656   static const unsigned SystemZOverflowOffset = 160;
4657   static const unsigned SystemZVAListTagSize = 32;
4658   static const unsigned SystemZOverflowArgAreaPtrOffset = 16;
4659   static const unsigned SystemZRegSaveAreaPtrOffset = 24;
4660 
4661   Function &F;
4662   MemorySanitizer &MS;
4663   MemorySanitizerVisitor &MSV;
4664   Value *VAArgTLSCopy = nullptr;
4665   Value *VAArgTLSOriginCopy = nullptr;
4666   Value *VAArgOverflowSize = nullptr;
4667 
4668   SmallVector<CallInst *, 16> VAStartInstrumentationList;
4669 
4670   enum class ArgKind {
4671     GeneralPurpose,
4672     FloatingPoint,
4673     Vector,
4674     Memory,
4675     Indirect,
4676   };
4677 
4678   enum class ShadowExtension { None, Zero, Sign };
4679 
4680   VarArgSystemZHelper(Function &F, MemorySanitizer &MS,
4681                       MemorySanitizerVisitor &MSV)
4682       : F(F), MS(MS), MSV(MSV) {}
4683 
4684   ArgKind classifyArgument(Type *T, bool IsSoftFloatABI) {
4685     // T is a SystemZABIInfo::classifyArgumentType() output, and there are
4686     // only a few possibilities of what it can be. In particular, enums, single
4687     // element structs and large types have already been taken care of.
4688 
4689     // Some i128 and fp128 arguments are converted to pointers only in the
4690     // back end.
4691     if (T->isIntegerTy(128) || T->isFP128Ty())
4692       return ArgKind::Indirect;
4693     if (T->isFloatingPointTy())
4694       return IsSoftFloatABI ? ArgKind::GeneralPurpose : ArgKind::FloatingPoint;
4695     if (T->isIntegerTy() || T->isPointerTy())
4696       return ArgKind::GeneralPurpose;
4697     if (T->isVectorTy())
4698       return ArgKind::Vector;
4699     return ArgKind::Memory;
4700   }
4701 
4702   ShadowExtension getShadowExtension(const CallBase &CB, unsigned ArgNo) {
4703     // ABI says: "One of the simple integer types no more than 64 bits wide.
4704     // ... If such an argument is shorter than 64 bits, replace it by a full
4705     // 64-bit integer representing the same number, using sign or zero
4706     // extension". Shadow for an integer argument has the same type as the
4707     // argument itself, so it can be sign or zero extended as well.
4708     bool ZExt = CB.paramHasAttr(ArgNo, Attribute::ZExt);
4709     bool SExt = CB.paramHasAttr(ArgNo, Attribute::SExt);
4710     if (ZExt) {
4711       assert(!SExt);
4712       return ShadowExtension::Zero;
4713     }
4714     if (SExt) {
4715       assert(!ZExt);
4716       return ShadowExtension::Sign;
4717     }
4718     return ShadowExtension::None;
4719   }
4720 
4721   void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {
4722     bool IsSoftFloatABI = CB.getCalledFunction()
4723                               ->getFnAttribute("use-soft-float")
4724                               .getValueAsString() == "true";
4725     unsigned GpOffset = SystemZGpOffset;
4726     unsigned FpOffset = SystemZFpOffset;
4727     unsigned VrIndex = 0;
4728     unsigned OverflowOffset = SystemZOverflowOffset;
4729     const DataLayout &DL = F.getParent()->getDataLayout();
4730     for (auto ArgIt = CB.arg_begin(), End = CB.arg_end(); ArgIt != End;
4731          ++ArgIt) {
4732       Value *A = *ArgIt;
4733       unsigned ArgNo = CB.getArgOperandNo(ArgIt);
4734       bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams();
4735       // SystemZABIInfo does not produce ByVal parameters.
4736       assert(!CB.paramHasAttr(ArgNo, Attribute::ByVal));
4737       Type *T = A->getType();
4738       ArgKind AK = classifyArgument(T, IsSoftFloatABI);
4739       if (AK == ArgKind::Indirect) {
4740         T = PointerType::get(T, 0);
4741         AK = ArgKind::GeneralPurpose;
4742       }
4743       if (AK == ArgKind::GeneralPurpose && GpOffset >= SystemZGpEndOffset)
4744         AK = ArgKind::Memory;
4745       if (AK == ArgKind::FloatingPoint && FpOffset >= SystemZFpEndOffset)
4746         AK = ArgKind::Memory;
4747       if (AK == ArgKind::Vector && (VrIndex >= SystemZMaxVrArgs || !IsFixed))
4748         AK = ArgKind::Memory;
4749       Value *ShadowBase = nullptr;
4750       Value *OriginBase = nullptr;
4751       ShadowExtension SE = ShadowExtension::None;
4752       switch (AK) {
4753       case ArgKind::GeneralPurpose: {
4754         // Always keep track of GpOffset, but store shadow only for varargs.
4755         uint64_t ArgSize = 8;
4756         if (GpOffset + ArgSize <= kParamTLSSize) {
4757           if (!IsFixed) {
4758             SE = getShadowExtension(CB, ArgNo);
4759             uint64_t GapSize = 0;
4760             if (SE == ShadowExtension::None) {
4761               uint64_t ArgAllocSize = DL.getTypeAllocSize(T);
4762               assert(ArgAllocSize <= ArgSize);
4763               GapSize = ArgSize - ArgAllocSize;
4764             }
4765             ShadowBase = getShadowAddrForVAArgument(IRB, GpOffset + GapSize);
4766             if (MS.TrackOrigins)
4767               OriginBase = getOriginPtrForVAArgument(IRB, GpOffset + GapSize);
4768           }
4769           GpOffset += ArgSize;
4770         } else {
4771           GpOffset = kParamTLSSize;
4772         }
4773         break;
4774       }
4775       case ArgKind::FloatingPoint: {
4776         // Always keep track of FpOffset, but store shadow only for varargs.
4777         uint64_t ArgSize = 8;
4778         if (FpOffset + ArgSize <= kParamTLSSize) {
4779           if (!IsFixed) {
4780             // PoP says: "A short floating-point datum requires only the
4781             // left-most 32 bit positions of a floating-point register".
4782             // Therefore, in contrast to AK_GeneralPurpose and AK_Memory,
4783             // don't extend shadow and don't mind the gap.
4784             ShadowBase = getShadowAddrForVAArgument(IRB, FpOffset);
4785             if (MS.TrackOrigins)
4786               OriginBase = getOriginPtrForVAArgument(IRB, FpOffset);
4787           }
4788           FpOffset += ArgSize;
4789         } else {
4790           FpOffset = kParamTLSSize;
4791         }
4792         break;
4793       }
4794       case ArgKind::Vector: {
4795         // Keep track of VrIndex. No need to store shadow, since vector varargs
4796         // go through AK_Memory.
4797         assert(IsFixed);
4798         VrIndex++;
4799         break;
4800       }
4801       case ArgKind::Memory: {
4802         // Keep track of OverflowOffset and store shadow only for varargs.
4803         // Ignore fixed args, since we need to copy only the vararg portion of
4804         // the overflow area shadow.
4805         if (!IsFixed) {
4806           uint64_t ArgAllocSize = DL.getTypeAllocSize(T);
4807           uint64_t ArgSize = alignTo(ArgAllocSize, 8);
4808           if (OverflowOffset + ArgSize <= kParamTLSSize) {
4809             SE = getShadowExtension(CB, ArgNo);
4810             uint64_t GapSize =
4811                 SE == ShadowExtension::None ? ArgSize - ArgAllocSize : 0;
4812             ShadowBase =
4813                 getShadowAddrForVAArgument(IRB, OverflowOffset + GapSize);
4814             if (MS.TrackOrigins)
4815               OriginBase =
4816                   getOriginPtrForVAArgument(IRB, OverflowOffset + GapSize);
4817             OverflowOffset += ArgSize;
4818           } else {
4819             OverflowOffset = kParamTLSSize;
4820           }
4821         }
4822         break;
4823       }
4824       case ArgKind::Indirect:
4825         llvm_unreachable("Indirect must be converted to GeneralPurpose");
4826       }
4827       if (ShadowBase == nullptr)
4828         continue;
4829       Value *Shadow = MSV.getShadow(A);
4830       if (SE != ShadowExtension::None)
4831         Shadow = MSV.CreateShadowCast(IRB, Shadow, IRB.getInt64Ty(),
4832                                       /*Signed*/ SE == ShadowExtension::Sign);
4833       ShadowBase = IRB.CreateIntToPtr(
4834           ShadowBase, PointerType::get(Shadow->getType(), 0), "_msarg_va_s");
4835       IRB.CreateStore(Shadow, ShadowBase);
4836       if (MS.TrackOrigins) {
4837         Value *Origin = MSV.getOrigin(A);
4838         unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
4839         MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize,
4840                         kMinOriginAlignment);
4841       }
4842     }
4843     Constant *OverflowSize = ConstantInt::get(
4844         IRB.getInt64Ty(), OverflowOffset - SystemZOverflowOffset);
4845     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
4846   }
4847 
4848   Value *getShadowAddrForVAArgument(IRBuilder<> &IRB, unsigned ArgOffset) {
4849     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4850     return IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4851   }
4852 
4853   Value *getOriginPtrForVAArgument(IRBuilder<> &IRB, int ArgOffset) {
4854     Value *Base = IRB.CreatePointerCast(MS.VAArgOriginTLS, MS.IntptrTy);
4855     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4856     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
4857                               "_msarg_va_o");
4858   }
4859 
4860   void unpoisonVAListTagForInst(IntrinsicInst &I) {
4861     IRBuilder<> IRB(&I);
4862     Value *VAListTag = I.getArgOperand(0);
4863     Value *ShadowPtr, *OriginPtr;
4864     const Align Alignment = Align(8);
4865     std::tie(ShadowPtr, OriginPtr) =
4866         MSV.getShadowOriginPtr(VAListTag, IRB, IRB.getInt8Ty(), Alignment,
4867                                /*isStore*/ true);
4868     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4869                      SystemZVAListTagSize, Alignment, false);
4870   }
4871 
4872   void visitVAStartInst(VAStartInst &I) override {
4873     VAStartInstrumentationList.push_back(&I);
4874     unpoisonVAListTagForInst(I);
4875   }
4876 
4877   void visitVACopyInst(VACopyInst &I) override { unpoisonVAListTagForInst(I); }
4878 
4879   void copyRegSaveArea(IRBuilder<> &IRB, Value *VAListTag) {
4880     Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4881     Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr(
4882         IRB.CreateAdd(
4883             IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4884             ConstantInt::get(MS.IntptrTy, SystemZRegSaveAreaPtrOffset)),
4885         PointerType::get(RegSaveAreaPtrTy, 0));
4886     Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr);
4887     Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
4888     const Align Alignment = Align(8);
4889     std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
4890         MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(), Alignment,
4891                                /*isStore*/ true);
4892     // TODO(iii): copy only fragments filled by visitCallBase()
4893     IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
4894                      SystemZRegSaveAreaSize);
4895     if (MS.TrackOrigins)
4896       IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy,
4897                        Alignment, SystemZRegSaveAreaSize);
4898   }
4899 
4900   void copyOverflowArea(IRBuilder<> &IRB, Value *VAListTag) {
4901     Type *OverflowArgAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4902     Value *OverflowArgAreaPtrPtr = IRB.CreateIntToPtr(
4903         IRB.CreateAdd(
4904             IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4905             ConstantInt::get(MS.IntptrTy, SystemZOverflowArgAreaPtrOffset)),
4906         PointerType::get(OverflowArgAreaPtrTy, 0));
4907     Value *OverflowArgAreaPtr =
4908         IRB.CreateLoad(OverflowArgAreaPtrTy, OverflowArgAreaPtrPtr);
4909     Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr;
4910     const Align Alignment = Align(8);
4911     std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) =
4912         MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(),
4913                                Alignment, /*isStore*/ true);
4914     Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
4915                                            SystemZOverflowOffset);
4916     IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment,
4917                      VAArgOverflowSize);
4918     if (MS.TrackOrigins) {
4919       SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy,
4920                                       SystemZOverflowOffset);
4921       IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment,
4922                        VAArgOverflowSize);
4923     }
4924   }
4925 
4926   void finalizeInstrumentation() override {
4927     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
4928            "finalizeInstrumentation called twice");
4929     if (!VAStartInstrumentationList.empty()) {
4930       // If there is a va_start in this function, make a backup copy of
4931       // va_arg_tls somewhere in the function entry block.
4932       IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4933       VAArgOverflowSize =
4934           IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4935       Value *CopySize =
4936           IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, SystemZOverflowOffset),
4937                         VAArgOverflowSize);
4938       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4939       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4940       if (MS.TrackOrigins) {
4941         VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4942         IRB.CreateMemCpy(VAArgTLSOriginCopy, Align(8), MS.VAArgOriginTLS,
4943                          Align(8), CopySize);
4944       }
4945     }
4946 
4947     // Instrument va_start.
4948     // Copy va_list shadow from the backup copy of the TLS contents.
4949     for (size_t VaStartNo = 0, VaStartNum = VAStartInstrumentationList.size();
4950          VaStartNo < VaStartNum; VaStartNo++) {
4951       CallInst *OrigInst = VAStartInstrumentationList[VaStartNo];
4952       IRBuilder<> IRB(OrigInst->getNextNode());
4953       Value *VAListTag = OrigInst->getArgOperand(0);
4954       copyRegSaveArea(IRB, VAListTag);
4955       copyOverflowArea(IRB, VAListTag);
4956     }
4957   }
4958 };
4959 
4960 /// A no-op implementation of VarArgHelper.
4961 struct VarArgNoOpHelper : public VarArgHelper {
4962   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
4963                    MemorySanitizerVisitor &MSV) {}
4964 
4965   void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {}
4966 
4967   void visitVAStartInst(VAStartInst &I) override {}
4968 
4969   void visitVACopyInst(VACopyInst &I) override {}
4970 
4971   void finalizeInstrumentation() override {}
4972 };
4973 
4974 } // end anonymous namespace
4975 
4976 static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
4977                                         MemorySanitizerVisitor &Visitor) {
4978   // VarArg handling is only implemented on AMD64. False positives are possible
4979   // on other platforms.
4980   Triple TargetTriple(Func.getParent()->getTargetTriple());
4981   if (TargetTriple.getArch() == Triple::x86_64)
4982     return new VarArgAMD64Helper(Func, Msan, Visitor);
4983   else if (TargetTriple.isMIPS64())
4984     return new VarArgMIPS64Helper(Func, Msan, Visitor);
4985   else if (TargetTriple.getArch() == Triple::aarch64)
4986     return new VarArgAArch64Helper(Func, Msan, Visitor);
4987   else if (TargetTriple.getArch() == Triple::ppc64 ||
4988            TargetTriple.getArch() == Triple::ppc64le)
4989     return new VarArgPowerPC64Helper(Func, Msan, Visitor);
4990   else if (TargetTriple.getArch() == Triple::systemz)
4991     return new VarArgSystemZHelper(Func, Msan, Visitor);
4992   else
4993     return new VarArgNoOpHelper(Func, Msan, Visitor);
4994 }
4995 
4996 bool MemorySanitizer::sanitizeFunction(Function &F, TargetLibraryInfo &TLI) {
4997   if (!CompileKernel && F.getName() == kMsanModuleCtorName)
4998     return false;
4999 
5000   MemorySanitizerVisitor Visitor(F, *this, TLI);
5001 
5002   // Clear out readonly/readnone attributes.
5003   AttrBuilder B;
5004   B.addAttribute(Attribute::ReadOnly)
5005       .addAttribute(Attribute::ReadNone)
5006       .addAttribute(Attribute::WriteOnly)
5007       .addAttribute(Attribute::ArgMemOnly)
5008       .addAttribute(Attribute::Speculatable);
5009   F.removeAttributes(AttributeList::FunctionIndex, B);
5010 
5011   return Visitor.runOnFunction();
5012 }
5013