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