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