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