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