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