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