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