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 overwritting 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 unitialized 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::None(),
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     insertShadowCheck(I.getOperand(2), &I);
1871     IRBuilder<> IRB(&I);
1872     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1873               I.getOperand(2), "_msprop"));
1874     setOriginForNaryOp(I);
1875   }
1876 
1877   // Casts.
1878   void visitSExtInst(SExtInst &I) {
1879     IRBuilder<> IRB(&I);
1880     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1881     setOrigin(&I, getOrigin(&I, 0));
1882   }
1883 
1884   void visitZExtInst(ZExtInst &I) {
1885     IRBuilder<> IRB(&I);
1886     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1887     setOrigin(&I, getOrigin(&I, 0));
1888   }
1889 
1890   void visitTruncInst(TruncInst &I) {
1891     IRBuilder<> IRB(&I);
1892     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1893     setOrigin(&I, getOrigin(&I, 0));
1894   }
1895 
1896   void visitBitCastInst(BitCastInst &I) {
1897     // Special case: if this is the bitcast (there is exactly 1 allowed) between
1898     // a musttail call and a ret, don't instrument. New instructions are not
1899     // allowed after a musttail call.
1900     if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
1901       if (CI->isMustTailCall())
1902         return;
1903     IRBuilder<> IRB(&I);
1904     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1905     setOrigin(&I, getOrigin(&I, 0));
1906   }
1907 
1908   void visitPtrToIntInst(PtrToIntInst &I) {
1909     IRBuilder<> IRB(&I);
1910     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1911              "_msprop_ptrtoint"));
1912     setOrigin(&I, getOrigin(&I, 0));
1913   }
1914 
1915   void visitIntToPtrInst(IntToPtrInst &I) {
1916     IRBuilder<> IRB(&I);
1917     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1918              "_msprop_inttoptr"));
1919     setOrigin(&I, getOrigin(&I, 0));
1920   }
1921 
1922   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1923   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1924   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1925   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1926   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1927   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1928 
1929   /// Propagate shadow for bitwise AND.
1930   ///
1931   /// This code is exact, i.e. if, for example, a bit in the left argument
1932   /// is defined and 0, then neither the value not definedness of the
1933   /// corresponding bit in B don't affect the resulting shadow.
1934   void visitAnd(BinaryOperator &I) {
1935     IRBuilder<> IRB(&I);
1936     //  "And" of 0 and a poisoned value results in unpoisoned value.
1937     //  1&1 => 1;     0&1 => 0;     p&1 => p;
1938     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
1939     //  1&p => p;     0&p => 0;     p&p => p;
1940     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1941     Value *S1 = getShadow(&I, 0);
1942     Value *S2 = getShadow(&I, 1);
1943     Value *V1 = I.getOperand(0);
1944     Value *V2 = I.getOperand(1);
1945     if (V1->getType() != S1->getType()) {
1946       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1947       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1948     }
1949     Value *S1S2 = IRB.CreateAnd(S1, S2);
1950     Value *V1S2 = IRB.CreateAnd(V1, S2);
1951     Value *S1V2 = IRB.CreateAnd(S1, V2);
1952     setShadow(&I, IRB.CreateOr({S1S2, V1S2, S1V2}));
1953     setOriginForNaryOp(I);
1954   }
1955 
1956   void visitOr(BinaryOperator &I) {
1957     IRBuilder<> IRB(&I);
1958     //  "Or" of 1 and a poisoned value results in unpoisoned value.
1959     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
1960     //  1|0 => 1;     0|0 => 0;     p|0 => p;
1961     //  1|p => 1;     0|p => p;     p|p => p;
1962     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1963     Value *S1 = getShadow(&I, 0);
1964     Value *S2 = getShadow(&I, 1);
1965     Value *V1 = IRB.CreateNot(I.getOperand(0));
1966     Value *V2 = IRB.CreateNot(I.getOperand(1));
1967     if (V1->getType() != S1->getType()) {
1968       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1969       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1970     }
1971     Value *S1S2 = IRB.CreateAnd(S1, S2);
1972     Value *V1S2 = IRB.CreateAnd(V1, S2);
1973     Value *S1V2 = IRB.CreateAnd(S1, V2);
1974     setShadow(&I, IRB.CreateOr({S1S2, V1S2, S1V2}));
1975     setOriginForNaryOp(I);
1976   }
1977 
1978   /// Default propagation of shadow and/or origin.
1979   ///
1980   /// This class implements the general case of shadow propagation, used in all
1981   /// cases where we don't know and/or don't care about what the operation
1982   /// actually does. It converts all input shadow values to a common type
1983   /// (extending or truncating as necessary), and bitwise OR's them.
1984   ///
1985   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1986   /// fully initialized), and less prone to false positives.
1987   ///
1988   /// This class also implements the general case of origin propagation. For a
1989   /// Nary operation, result origin is set to the origin of an argument that is
1990   /// not entirely initialized. If there is more than one such arguments, the
1991   /// rightmost of them is picked. It does not matter which one is picked if all
1992   /// arguments are initialized.
1993   template <bool CombineShadow>
1994   class Combiner {
1995     Value *Shadow = nullptr;
1996     Value *Origin = nullptr;
1997     IRBuilder<> &IRB;
1998     MemorySanitizerVisitor *MSV;
1999 
2000   public:
2001     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB)
2002         : IRB(IRB), MSV(MSV) {}
2003 
2004     /// Add a pair of shadow and origin values to the mix.
2005     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
2006       if (CombineShadow) {
2007         assert(OpShadow);
2008         if (!Shadow)
2009           Shadow = OpShadow;
2010         else {
2011           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
2012           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
2013         }
2014       }
2015 
2016       if (MSV->MS.TrackOrigins) {
2017         assert(OpOrigin);
2018         if (!Origin) {
2019           Origin = OpOrigin;
2020         } else {
2021           Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
2022           // No point in adding something that might result in 0 origin value.
2023           if (!ConstOrigin || !ConstOrigin->isNullValue()) {
2024             Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
2025             Value *Cond =
2026                 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
2027             Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
2028           }
2029         }
2030       }
2031       return *this;
2032     }
2033 
2034     /// Add an application value to the mix.
2035     Combiner &Add(Value *V) {
2036       Value *OpShadow = MSV->getShadow(V);
2037       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
2038       return Add(OpShadow, OpOrigin);
2039     }
2040 
2041     /// Set the current combined values as the given instruction's shadow
2042     /// and origin.
2043     void Done(Instruction *I) {
2044       if (CombineShadow) {
2045         assert(Shadow);
2046         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
2047         MSV->setShadow(I, Shadow);
2048       }
2049       if (MSV->MS.TrackOrigins) {
2050         assert(Origin);
2051         MSV->setOrigin(I, Origin);
2052       }
2053     }
2054   };
2055 
2056   using ShadowAndOriginCombiner = Combiner<true>;
2057   using OriginCombiner = Combiner<false>;
2058 
2059   /// Propagate origin for arbitrary operation.
2060   void setOriginForNaryOp(Instruction &I) {
2061     if (!MS.TrackOrigins) return;
2062     IRBuilder<> IRB(&I);
2063     OriginCombiner OC(this, IRB);
2064     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
2065       OC.Add(OI->get());
2066     OC.Done(&I);
2067   }
2068 
2069   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
2070     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
2071            "Vector of pointers is not a valid shadow type");
2072     return Ty->isVectorTy() ?
2073       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
2074       Ty->getPrimitiveSizeInBits();
2075   }
2076 
2077   /// Cast between two shadow types, extending or truncating as
2078   /// necessary.
2079   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
2080                           bool Signed = false) {
2081     Type *srcTy = V->getType();
2082     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
2083     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
2084     if (srcSizeInBits > 1 && dstSizeInBits == 1)
2085       return IRB.CreateICmpNE(V, getCleanShadow(V));
2086 
2087     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
2088       return IRB.CreateIntCast(V, dstTy, Signed);
2089     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
2090         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
2091       return IRB.CreateIntCast(V, dstTy, Signed);
2092     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
2093     Value *V2 =
2094       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
2095     return IRB.CreateBitCast(V2, dstTy);
2096     // TODO: handle struct types.
2097   }
2098 
2099   /// Cast an application value to the type of its own shadow.
2100   Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
2101     Type *ShadowTy = getShadowTy(V);
2102     if (V->getType() == ShadowTy)
2103       return V;
2104     if (V->getType()->isPtrOrPtrVectorTy())
2105       return IRB.CreatePtrToInt(V, ShadowTy);
2106     else
2107       return IRB.CreateBitCast(V, ShadowTy);
2108   }
2109 
2110   /// Propagate shadow for arbitrary operation.
2111   void handleShadowOr(Instruction &I) {
2112     IRBuilder<> IRB(&I);
2113     ShadowAndOriginCombiner SC(this, IRB);
2114     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
2115       SC.Add(OI->get());
2116     SC.Done(&I);
2117   }
2118 
2119   void visitFNeg(UnaryOperator &I) { handleShadowOr(I); }
2120 
2121   // Handle multiplication by constant.
2122   //
2123   // Handle a special case of multiplication by constant that may have one or
2124   // more zeros in the lower bits. This makes corresponding number of lower bits
2125   // of the result zero as well. We model it by shifting the other operand
2126   // shadow left by the required number of bits. Effectively, we transform
2127   // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
2128   // We use multiplication by 2**N instead of shift to cover the case of
2129   // multiplication by 0, which may occur in some elements of a vector operand.
2130   void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
2131                            Value *OtherArg) {
2132     Constant *ShadowMul;
2133     Type *Ty = ConstArg->getType();
2134     if (Ty->isVectorTy()) {
2135       unsigned NumElements = Ty->getVectorNumElements();
2136       Type *EltTy = Ty->getSequentialElementType();
2137       SmallVector<Constant *, 16> Elements;
2138       for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
2139         if (ConstantInt *Elt =
2140                 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx))) {
2141           const APInt &V = Elt->getValue();
2142           APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
2143           Elements.push_back(ConstantInt::get(EltTy, V2));
2144         } else {
2145           Elements.push_back(ConstantInt::get(EltTy, 1));
2146         }
2147       }
2148       ShadowMul = ConstantVector::get(Elements);
2149     } else {
2150       if (ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg)) {
2151         const APInt &V = Elt->getValue();
2152         APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
2153         ShadowMul = ConstantInt::get(Ty, V2);
2154       } else {
2155         ShadowMul = ConstantInt::get(Ty, 1);
2156       }
2157     }
2158 
2159     IRBuilder<> IRB(&I);
2160     setShadow(&I,
2161               IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
2162     setOrigin(&I, getOrigin(OtherArg));
2163   }
2164 
2165   void visitMul(BinaryOperator &I) {
2166     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
2167     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
2168     if (constOp0 && !constOp1)
2169       handleMulByConstant(I, constOp0, I.getOperand(1));
2170     else if (constOp1 && !constOp0)
2171       handleMulByConstant(I, constOp1, I.getOperand(0));
2172     else
2173       handleShadowOr(I);
2174   }
2175 
2176   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
2177   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
2178   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
2179   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
2180   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
2181   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
2182 
2183   void handleIntegerDiv(Instruction &I) {
2184     IRBuilder<> IRB(&I);
2185     // Strict on the second argument.
2186     insertShadowCheck(I.getOperand(1), &I);
2187     setShadow(&I, getShadow(&I, 0));
2188     setOrigin(&I, getOrigin(&I, 0));
2189   }
2190 
2191   void visitUDiv(BinaryOperator &I) { handleIntegerDiv(I); }
2192   void visitSDiv(BinaryOperator &I) { handleIntegerDiv(I); }
2193   void visitURem(BinaryOperator &I) { handleIntegerDiv(I); }
2194   void visitSRem(BinaryOperator &I) { handleIntegerDiv(I); }
2195 
2196   // Floating point division is side-effect free. We can not require that the
2197   // divisor is fully initialized and must propagate shadow. See PR37523.
2198   void visitFDiv(BinaryOperator &I) { handleShadowOr(I); }
2199   void visitFRem(BinaryOperator &I) { handleShadowOr(I); }
2200 
2201   /// Instrument == and != comparisons.
2202   ///
2203   /// Sometimes the comparison result is known even if some of the bits of the
2204   /// arguments are not.
2205   void handleEqualityComparison(ICmpInst &I) {
2206     IRBuilder<> IRB(&I);
2207     Value *A = I.getOperand(0);
2208     Value *B = I.getOperand(1);
2209     Value *Sa = getShadow(A);
2210     Value *Sb = getShadow(B);
2211 
2212     // Get rid of pointers and vectors of pointers.
2213     // For ints (and vectors of ints), types of A and Sa match,
2214     // and this is a no-op.
2215     A = IRB.CreatePointerCast(A, Sa->getType());
2216     B = IRB.CreatePointerCast(B, Sb->getType());
2217 
2218     // A == B  <==>  (C = A^B) == 0
2219     // A != B  <==>  (C = A^B) != 0
2220     // Sc = Sa | Sb
2221     Value *C = IRB.CreateXor(A, B);
2222     Value *Sc = IRB.CreateOr(Sa, Sb);
2223     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
2224     // Result is defined if one of the following is true
2225     // * there is a defined 1 bit in C
2226     // * C is fully defined
2227     // Si = !(C & ~Sc) && Sc
2228     Value *Zero = Constant::getNullValue(Sc->getType());
2229     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
2230     Value *Si =
2231       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
2232                     IRB.CreateICmpEQ(
2233                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
2234     Si->setName("_msprop_icmp");
2235     setShadow(&I, Si);
2236     setOriginForNaryOp(I);
2237   }
2238 
2239   /// Build the lowest possible value of V, taking into account V's
2240   ///        uninitialized bits.
2241   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
2242                                 bool isSigned) {
2243     if (isSigned) {
2244       // Split shadow into sign bit and other bits.
2245       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
2246       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
2247       // Maximise the undefined shadow bit, minimize other undefined bits.
2248       return
2249         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
2250     } else {
2251       // Minimize undefined bits.
2252       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
2253     }
2254   }
2255 
2256   /// Build the highest possible value of V, taking into account V's
2257   ///        uninitialized bits.
2258   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
2259                                 bool isSigned) {
2260     if (isSigned) {
2261       // Split shadow into sign bit and other bits.
2262       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
2263       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
2264       // Minimise the undefined shadow bit, maximise other undefined bits.
2265       return
2266         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
2267     } else {
2268       // Maximize undefined bits.
2269       return IRB.CreateOr(A, Sa);
2270     }
2271   }
2272 
2273   /// Instrument relational comparisons.
2274   ///
2275   /// This function does exact shadow propagation for all relational
2276   /// comparisons of integers, pointers and vectors of those.
2277   /// FIXME: output seems suboptimal when one of the operands is a constant
2278   void handleRelationalComparisonExact(ICmpInst &I) {
2279     IRBuilder<> IRB(&I);
2280     Value *A = I.getOperand(0);
2281     Value *B = I.getOperand(1);
2282     Value *Sa = getShadow(A);
2283     Value *Sb = getShadow(B);
2284 
2285     // Get rid of pointers and vectors of pointers.
2286     // For ints (and vectors of ints), types of A and Sa match,
2287     // and this is a no-op.
2288     A = IRB.CreatePointerCast(A, Sa->getType());
2289     B = IRB.CreatePointerCast(B, Sb->getType());
2290 
2291     // Let [a0, a1] be the interval of possible values of A, taking into account
2292     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
2293     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
2294     bool IsSigned = I.isSigned();
2295     Value *S1 = IRB.CreateICmp(I.getPredicate(),
2296                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
2297                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
2298     Value *S2 = IRB.CreateICmp(I.getPredicate(),
2299                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
2300                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
2301     Value *Si = IRB.CreateXor(S1, S2);
2302     setShadow(&I, Si);
2303     setOriginForNaryOp(I);
2304   }
2305 
2306   /// Instrument signed relational comparisons.
2307   ///
2308   /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest
2309   /// bit of the shadow. Everything else is delegated to handleShadowOr().
2310   void handleSignedRelationalComparison(ICmpInst &I) {
2311     Constant *constOp;
2312     Value *op = nullptr;
2313     CmpInst::Predicate pre;
2314     if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) {
2315       op = I.getOperand(0);
2316       pre = I.getPredicate();
2317     } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) {
2318       op = I.getOperand(1);
2319       pre = I.getSwappedPredicate();
2320     } else {
2321       handleShadowOr(I);
2322       return;
2323     }
2324 
2325     if ((constOp->isNullValue() &&
2326          (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) ||
2327         (constOp->isAllOnesValue() &&
2328          (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) {
2329       IRBuilder<> IRB(&I);
2330       Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op),
2331                                         "_msprop_icmp_s");
2332       setShadow(&I, Shadow);
2333       setOrigin(&I, getOrigin(op));
2334     } else {
2335       handleShadowOr(I);
2336     }
2337   }
2338 
2339   void visitICmpInst(ICmpInst &I) {
2340     if (!ClHandleICmp) {
2341       handleShadowOr(I);
2342       return;
2343     }
2344     if (I.isEquality()) {
2345       handleEqualityComparison(I);
2346       return;
2347     }
2348 
2349     assert(I.isRelational());
2350     if (ClHandleICmpExact) {
2351       handleRelationalComparisonExact(I);
2352       return;
2353     }
2354     if (I.isSigned()) {
2355       handleSignedRelationalComparison(I);
2356       return;
2357     }
2358 
2359     assert(I.isUnsigned());
2360     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
2361       handleRelationalComparisonExact(I);
2362       return;
2363     }
2364 
2365     handleShadowOr(I);
2366   }
2367 
2368   void visitFCmpInst(FCmpInst &I) {
2369     handleShadowOr(I);
2370   }
2371 
2372   void handleShift(BinaryOperator &I) {
2373     IRBuilder<> IRB(&I);
2374     // If any of the S2 bits are poisoned, the whole thing is poisoned.
2375     // Otherwise perform the same shift on S1.
2376     Value *S1 = getShadow(&I, 0);
2377     Value *S2 = getShadow(&I, 1);
2378     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
2379                                    S2->getType());
2380     Value *V2 = I.getOperand(1);
2381     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
2382     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2383     setOriginForNaryOp(I);
2384   }
2385 
2386   void visitShl(BinaryOperator &I) { handleShift(I); }
2387   void visitAShr(BinaryOperator &I) { handleShift(I); }
2388   void visitLShr(BinaryOperator &I) { handleShift(I); }
2389 
2390   /// Instrument llvm.memmove
2391   ///
2392   /// At this point we don't know if llvm.memmove will be inlined or not.
2393   /// If we don't instrument it and it gets inlined,
2394   /// our interceptor will not kick in and we will lose the memmove.
2395   /// If we instrument the call here, but it does not get inlined,
2396   /// we will memove the shadow twice: which is bad in case
2397   /// of overlapping regions. So, we simply lower the intrinsic to a call.
2398   ///
2399   /// Similar situation exists for memcpy and memset.
2400   void visitMemMoveInst(MemMoveInst &I) {
2401     IRBuilder<> IRB(&I);
2402     IRB.CreateCall(
2403         MS.MemmoveFn,
2404         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2405          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
2406          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
2407     I.eraseFromParent();
2408   }
2409 
2410   // Similar to memmove: avoid copying shadow twice.
2411   // This is somewhat unfortunate as it may slowdown small constant memcpys.
2412   // FIXME: consider doing manual inline for small constant sizes and proper
2413   // alignment.
2414   void visitMemCpyInst(MemCpyInst &I) {
2415     IRBuilder<> IRB(&I);
2416     IRB.CreateCall(
2417         MS.MemcpyFn,
2418         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2419          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
2420          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
2421     I.eraseFromParent();
2422   }
2423 
2424   // Same as memcpy.
2425   void visitMemSetInst(MemSetInst &I) {
2426     IRBuilder<> IRB(&I);
2427     IRB.CreateCall(
2428         MS.MemsetFn,
2429         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2430          IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
2431          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
2432     I.eraseFromParent();
2433   }
2434 
2435   void visitVAStartInst(VAStartInst &I) {
2436     VAHelper->visitVAStartInst(I);
2437   }
2438 
2439   void visitVACopyInst(VACopyInst &I) {
2440     VAHelper->visitVACopyInst(I);
2441   }
2442 
2443   /// Handle vector store-like intrinsics.
2444   ///
2445   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
2446   /// has 1 pointer argument and 1 vector argument, returns void.
2447   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
2448     IRBuilder<> IRB(&I);
2449     Value* Addr = I.getArgOperand(0);
2450     Value *Shadow = getShadow(&I, 1);
2451     Value *ShadowPtr, *OriginPtr;
2452 
2453     // We don't know the pointer alignment (could be unaligned SSE store!).
2454     // Have to assume to worst case.
2455     std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr(
2456         Addr, IRB, Shadow->getType(), Align::None(), /*isStore*/ true);
2457     IRB.CreateAlignedStore(Shadow, ShadowPtr, Align(1));
2458 
2459     if (ClCheckAccessAddress)
2460       insertShadowCheck(Addr, &I);
2461 
2462     // FIXME: factor out common code from materializeStores
2463     if (MS.TrackOrigins) IRB.CreateStore(getOrigin(&I, 1), OriginPtr);
2464     return true;
2465   }
2466 
2467   /// Handle vector load-like intrinsics.
2468   ///
2469   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
2470   /// has 1 pointer argument, returns a vector.
2471   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
2472     IRBuilder<> IRB(&I);
2473     Value *Addr = I.getArgOperand(0);
2474 
2475     Type *ShadowTy = getShadowTy(&I);
2476     Value *ShadowPtr = nullptr, *OriginPtr = nullptr;
2477     if (PropagateShadow) {
2478       // We don't know the pointer alignment (could be unaligned SSE load!).
2479       // Have to assume to worst case.
2480       const Align Alignment = Align::None();
2481       std::tie(ShadowPtr, OriginPtr) =
2482           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
2483       setShadow(&I,
2484                 IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Alignment, "_msld"));
2485     } else {
2486       setShadow(&I, getCleanShadow(&I));
2487     }
2488 
2489     if (ClCheckAccessAddress)
2490       insertShadowCheck(Addr, &I);
2491 
2492     if (MS.TrackOrigins) {
2493       if (PropagateShadow)
2494         setOrigin(&I, IRB.CreateLoad(MS.OriginTy, OriginPtr));
2495       else
2496         setOrigin(&I, getCleanOrigin());
2497     }
2498     return true;
2499   }
2500 
2501   /// Handle (SIMD arithmetic)-like intrinsics.
2502   ///
2503   /// Instrument intrinsics with any number of arguments of the same type,
2504   /// equal to the return type. The type should be simple (no aggregates or
2505   /// pointers; vectors are fine).
2506   /// Caller guarantees that this intrinsic does not access memory.
2507   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
2508     Type *RetTy = I.getType();
2509     if (!(RetTy->isIntOrIntVectorTy() ||
2510           RetTy->isFPOrFPVectorTy() ||
2511           RetTy->isX86_MMXTy()))
2512       return false;
2513 
2514     unsigned NumArgOperands = I.getNumArgOperands();
2515 
2516     for (unsigned i = 0; i < NumArgOperands; ++i) {
2517       Type *Ty = I.getArgOperand(i)->getType();
2518       if (Ty != RetTy)
2519         return false;
2520     }
2521 
2522     IRBuilder<> IRB(&I);
2523     ShadowAndOriginCombiner SC(this, IRB);
2524     for (unsigned i = 0; i < NumArgOperands; ++i)
2525       SC.Add(I.getArgOperand(i));
2526     SC.Done(&I);
2527 
2528     return true;
2529   }
2530 
2531   /// Heuristically instrument unknown intrinsics.
2532   ///
2533   /// The main purpose of this code is to do something reasonable with all
2534   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
2535   /// We recognize several classes of intrinsics by their argument types and
2536   /// ModRefBehaviour and apply special intrumentation when we are reasonably
2537   /// sure that we know what the intrinsic does.
2538   ///
2539   /// We special-case intrinsics where this approach fails. See llvm.bswap
2540   /// handling as an example of that.
2541   bool handleUnknownIntrinsic(IntrinsicInst &I) {
2542     unsigned NumArgOperands = I.getNumArgOperands();
2543     if (NumArgOperands == 0)
2544       return false;
2545 
2546     if (NumArgOperands == 2 &&
2547         I.getArgOperand(0)->getType()->isPointerTy() &&
2548         I.getArgOperand(1)->getType()->isVectorTy() &&
2549         I.getType()->isVoidTy() &&
2550         !I.onlyReadsMemory()) {
2551       // This looks like a vector store.
2552       return handleVectorStoreIntrinsic(I);
2553     }
2554 
2555     if (NumArgOperands == 1 &&
2556         I.getArgOperand(0)->getType()->isPointerTy() &&
2557         I.getType()->isVectorTy() &&
2558         I.onlyReadsMemory()) {
2559       // This looks like a vector load.
2560       return handleVectorLoadIntrinsic(I);
2561     }
2562 
2563     if (I.doesNotAccessMemory())
2564       if (maybeHandleSimpleNomemIntrinsic(I))
2565         return true;
2566 
2567     // FIXME: detect and handle SSE maskstore/maskload
2568     return false;
2569   }
2570 
2571   void handleInvariantGroup(IntrinsicInst &I) {
2572     setShadow(&I, getShadow(&I, 0));
2573     setOrigin(&I, getOrigin(&I, 0));
2574   }
2575 
2576   void handleLifetimeStart(IntrinsicInst &I) {
2577     if (!PoisonStack)
2578       return;
2579     DenseMap<Value *, AllocaInst *> AllocaForValue;
2580     AllocaInst *AI =
2581         llvm::findAllocaForValue(I.getArgOperand(1), AllocaForValue);
2582     if (!AI)
2583       InstrumentLifetimeStart = false;
2584     LifetimeStartList.push_back(std::make_pair(&I, AI));
2585   }
2586 
2587   void handleBswap(IntrinsicInst &I) {
2588     IRBuilder<> IRB(&I);
2589     Value *Op = I.getArgOperand(0);
2590     Type *OpType = Op->getType();
2591     Function *BswapFunc = Intrinsic::getDeclaration(
2592       F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
2593     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2594     setOrigin(&I, getOrigin(Op));
2595   }
2596 
2597   // Instrument vector convert instrinsic.
2598   //
2599   // This function instruments intrinsics like cvtsi2ss:
2600   // %Out = int_xxx_cvtyyy(%ConvertOp)
2601   // or
2602   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2603   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2604   // number \p Out elements, and (if has 2 arguments) copies the rest of the
2605   // elements from \p CopyOp.
2606   // In most cases conversion involves floating-point value which may trigger a
2607   // hardware exception when not fully initialized. For this reason we require
2608   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2609   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2610   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2611   // return a fully initialized value.
2612   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2613     IRBuilder<> IRB(&I);
2614     Value *CopyOp, *ConvertOp;
2615 
2616     switch (I.getNumArgOperands()) {
2617     case 3:
2618       assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
2619       LLVM_FALLTHROUGH;
2620     case 2:
2621       CopyOp = I.getArgOperand(0);
2622       ConvertOp = I.getArgOperand(1);
2623       break;
2624     case 1:
2625       ConvertOp = I.getArgOperand(0);
2626       CopyOp = nullptr;
2627       break;
2628     default:
2629       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2630     }
2631 
2632     // The first *NumUsedElements* elements of ConvertOp are converted to the
2633     // same number of output elements. The rest of the output is copied from
2634     // CopyOp, or (if not available) filled with zeroes.
2635     // Combine shadow for elements of ConvertOp that are used in this operation,
2636     // and insert a check.
2637     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2638     // int->any conversion.
2639     Value *ConvertShadow = getShadow(ConvertOp);
2640     Value *AggShadow = nullptr;
2641     if (ConvertOp->getType()->isVectorTy()) {
2642       AggShadow = IRB.CreateExtractElement(
2643           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2644       for (int i = 1; i < NumUsedElements; ++i) {
2645         Value *MoreShadow = IRB.CreateExtractElement(
2646             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2647         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2648       }
2649     } else {
2650       AggShadow = ConvertShadow;
2651     }
2652     assert(AggShadow->getType()->isIntegerTy());
2653     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2654 
2655     // Build result shadow by zero-filling parts of CopyOp shadow that come from
2656     // ConvertOp.
2657     if (CopyOp) {
2658       assert(CopyOp->getType() == I.getType());
2659       assert(CopyOp->getType()->isVectorTy());
2660       Value *ResultShadow = getShadow(CopyOp);
2661       Type *EltTy = ResultShadow->getType()->getVectorElementType();
2662       for (int i = 0; i < NumUsedElements; ++i) {
2663         ResultShadow = IRB.CreateInsertElement(
2664             ResultShadow, ConstantInt::getNullValue(EltTy),
2665             ConstantInt::get(IRB.getInt32Ty(), i));
2666       }
2667       setShadow(&I, ResultShadow);
2668       setOrigin(&I, getOrigin(CopyOp));
2669     } else {
2670       setShadow(&I, getCleanShadow(&I));
2671       setOrigin(&I, getCleanOrigin());
2672     }
2673   }
2674 
2675   // Given a scalar or vector, extract lower 64 bits (or less), and return all
2676   // zeroes if it is zero, and all ones otherwise.
2677   Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2678     if (S->getType()->isVectorTy())
2679       S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2680     assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2681     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2682     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2683   }
2684 
2685   // Given a vector, extract its first element, and return all
2686   // zeroes if it is zero, and all ones otherwise.
2687   Value *LowerElementShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2688     Value *S1 = IRB.CreateExtractElement(S, (uint64_t)0);
2689     Value *S2 = IRB.CreateICmpNE(S1, getCleanShadow(S1));
2690     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2691   }
2692 
2693   Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2694     Type *T = S->getType();
2695     assert(T->isVectorTy());
2696     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2697     return IRB.CreateSExt(S2, T);
2698   }
2699 
2700   // Instrument vector shift instrinsic.
2701   //
2702   // This function instruments intrinsics like int_x86_avx2_psll_w.
2703   // Intrinsic shifts %In by %ShiftSize bits.
2704   // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2705   // size, and the rest is ignored. Behavior is defined even if shift size is
2706   // greater than register (or field) width.
2707   void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2708     assert(I.getNumArgOperands() == 2);
2709     IRBuilder<> IRB(&I);
2710     // If any of the S2 bits are poisoned, the whole thing is poisoned.
2711     // Otherwise perform the same shift on S1.
2712     Value *S1 = getShadow(&I, 0);
2713     Value *S2 = getShadow(&I, 1);
2714     Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2715                              : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2716     Value *V1 = I.getOperand(0);
2717     Value *V2 = I.getOperand(1);
2718     Value *Shift = IRB.CreateCall(I.getFunctionType(), I.getCalledValue(),
2719                                   {IRB.CreateBitCast(S1, V1->getType()), V2});
2720     Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2721     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2722     setOriginForNaryOp(I);
2723   }
2724 
2725   // Get an X86_MMX-sized vector type.
2726   Type *getMMXVectorTy(unsigned EltSizeInBits) {
2727     const unsigned X86_MMXSizeInBits = 64;
2728     assert(EltSizeInBits != 0 && (X86_MMXSizeInBits % EltSizeInBits) == 0 &&
2729            "Illegal MMX vector element size");
2730     return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2731                            X86_MMXSizeInBits / EltSizeInBits);
2732   }
2733 
2734   // Returns a signed counterpart for an (un)signed-saturate-and-pack
2735   // intrinsic.
2736   Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2737     switch (id) {
2738       case Intrinsic::x86_sse2_packsswb_128:
2739       case Intrinsic::x86_sse2_packuswb_128:
2740         return Intrinsic::x86_sse2_packsswb_128;
2741 
2742       case Intrinsic::x86_sse2_packssdw_128:
2743       case Intrinsic::x86_sse41_packusdw:
2744         return Intrinsic::x86_sse2_packssdw_128;
2745 
2746       case Intrinsic::x86_avx2_packsswb:
2747       case Intrinsic::x86_avx2_packuswb:
2748         return Intrinsic::x86_avx2_packsswb;
2749 
2750       case Intrinsic::x86_avx2_packssdw:
2751       case Intrinsic::x86_avx2_packusdw:
2752         return Intrinsic::x86_avx2_packssdw;
2753 
2754       case Intrinsic::x86_mmx_packsswb:
2755       case Intrinsic::x86_mmx_packuswb:
2756         return Intrinsic::x86_mmx_packsswb;
2757 
2758       case Intrinsic::x86_mmx_packssdw:
2759         return Intrinsic::x86_mmx_packssdw;
2760       default:
2761         llvm_unreachable("unexpected intrinsic id");
2762     }
2763   }
2764 
2765   // Instrument vector pack instrinsic.
2766   //
2767   // This function instruments intrinsics like x86_mmx_packsswb, that
2768   // packs elements of 2 input vectors into half as many bits with saturation.
2769   // Shadow is propagated with the signed variant of the same intrinsic applied
2770   // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2771   // EltSizeInBits is used only for x86mmx arguments.
2772   void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
2773     assert(I.getNumArgOperands() == 2);
2774     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2775     IRBuilder<> IRB(&I);
2776     Value *S1 = getShadow(&I, 0);
2777     Value *S2 = getShadow(&I, 1);
2778     assert(isX86_MMX || S1->getType()->isVectorTy());
2779 
2780     // SExt and ICmpNE below must apply to individual elements of input vectors.
2781     // In case of x86mmx arguments, cast them to appropriate vector types and
2782     // back.
2783     Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2784     if (isX86_MMX) {
2785       S1 = IRB.CreateBitCast(S1, T);
2786       S2 = IRB.CreateBitCast(S2, T);
2787     }
2788     Value *S1_ext = IRB.CreateSExt(
2789         IRB.CreateICmpNE(S1, Constant::getNullValue(T)), T);
2790     Value *S2_ext = IRB.CreateSExt(
2791         IRB.CreateICmpNE(S2, Constant::getNullValue(T)), T);
2792     if (isX86_MMX) {
2793       Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2794       S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2795       S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2796     }
2797 
2798     Function *ShadowFn = Intrinsic::getDeclaration(
2799         F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2800 
2801     Value *S =
2802         IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
2803     if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2804     setShadow(&I, S);
2805     setOriginForNaryOp(I);
2806   }
2807 
2808   // Instrument sum-of-absolute-differencies intrinsic.
2809   void handleVectorSadIntrinsic(IntrinsicInst &I) {
2810     const unsigned SignificantBitsPerResultElement = 16;
2811     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2812     Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2813     unsigned ZeroBitsPerResultElement =
2814         ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2815 
2816     IRBuilder<> IRB(&I);
2817     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2818     S = IRB.CreateBitCast(S, ResTy);
2819     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2820                        ResTy);
2821     S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2822     S = IRB.CreateBitCast(S, getShadowTy(&I));
2823     setShadow(&I, S);
2824     setOriginForNaryOp(I);
2825   }
2826 
2827   // Instrument multiply-add intrinsic.
2828   void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2829                                   unsigned EltSizeInBits = 0) {
2830     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2831     Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2832     IRBuilder<> IRB(&I);
2833     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2834     S = IRB.CreateBitCast(S, ResTy);
2835     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2836                        ResTy);
2837     S = IRB.CreateBitCast(S, getShadowTy(&I));
2838     setShadow(&I, S);
2839     setOriginForNaryOp(I);
2840   }
2841 
2842   // Instrument compare-packed intrinsic.
2843   // Basically, an or followed by sext(icmp ne 0) to end up with all-zeros or
2844   // all-ones shadow.
2845   void handleVectorComparePackedIntrinsic(IntrinsicInst &I) {
2846     IRBuilder<> IRB(&I);
2847     Type *ResTy = getShadowTy(&I);
2848     Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2849     Value *S = IRB.CreateSExt(
2850         IRB.CreateICmpNE(S0, Constant::getNullValue(ResTy)), ResTy);
2851     setShadow(&I, S);
2852     setOriginForNaryOp(I);
2853   }
2854 
2855   // Instrument compare-scalar intrinsic.
2856   // This handles both cmp* intrinsics which return the result in the first
2857   // element of a vector, and comi* which return the result as i32.
2858   void handleVectorCompareScalarIntrinsic(IntrinsicInst &I) {
2859     IRBuilder<> IRB(&I);
2860     Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2861     Value *S = LowerElementShadowExtend(IRB, S0, getShadowTy(&I));
2862     setShadow(&I, S);
2863     setOriginForNaryOp(I);
2864   }
2865 
2866   void handleStmxcsr(IntrinsicInst &I) {
2867     IRBuilder<> IRB(&I);
2868     Value* Addr = I.getArgOperand(0);
2869     Type *Ty = IRB.getInt32Ty();
2870     Value *ShadowPtr =
2871         getShadowOriginPtr(Addr, IRB, Ty, Align::None(), /*isStore*/ true)
2872             .first;
2873 
2874     IRB.CreateStore(getCleanShadow(Ty),
2875                     IRB.CreatePointerCast(ShadowPtr, Ty->getPointerTo()));
2876 
2877     if (ClCheckAccessAddress)
2878       insertShadowCheck(Addr, &I);
2879   }
2880 
2881   void handleLdmxcsr(IntrinsicInst &I) {
2882     if (!InsertChecks) return;
2883 
2884     IRBuilder<> IRB(&I);
2885     Value *Addr = I.getArgOperand(0);
2886     Type *Ty = IRB.getInt32Ty();
2887     const Align Alignment = Align::None();
2888     Value *ShadowPtr, *OriginPtr;
2889     std::tie(ShadowPtr, OriginPtr) =
2890         getShadowOriginPtr(Addr, IRB, Ty, Alignment, /*isStore*/ false);
2891 
2892     if (ClCheckAccessAddress)
2893       insertShadowCheck(Addr, &I);
2894 
2895     Value *Shadow = IRB.CreateAlignedLoad(Ty, ShadowPtr, Alignment, "_ldmxcsr");
2896     Value *Origin = MS.TrackOrigins ? IRB.CreateLoad(MS.OriginTy, OriginPtr)
2897                                     : getCleanOrigin();
2898     insertShadowCheck(Shadow, Origin, &I);
2899   }
2900 
2901   void handleMaskedStore(IntrinsicInst &I) {
2902     IRBuilder<> IRB(&I);
2903     Value *V = I.getArgOperand(0);
2904     Value *Addr = I.getArgOperand(1);
2905     const Align Alignment(
2906         cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
2907     Value *Mask = I.getArgOperand(3);
2908     Value *Shadow = getShadow(V);
2909 
2910     Value *ShadowPtr;
2911     Value *OriginPtr;
2912     std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr(
2913         Addr, IRB, Shadow->getType(), Alignment, /*isStore*/ true);
2914 
2915     if (ClCheckAccessAddress) {
2916       insertShadowCheck(Addr, &I);
2917       // Uninitialized mask is kind of like uninitialized address, but not as
2918       // scary.
2919       insertShadowCheck(Mask, &I);
2920     }
2921 
2922     IRB.CreateMaskedStore(Shadow, ShadowPtr, Alignment, Mask);
2923 
2924     if (MS.TrackOrigins) {
2925       auto &DL = F.getParent()->getDataLayout();
2926       paintOrigin(IRB, getOrigin(V), OriginPtr,
2927                   DL.getTypeStoreSize(Shadow->getType()),
2928                   std::max(Alignment, kMinOriginAlignment));
2929     }
2930   }
2931 
2932   bool handleMaskedLoad(IntrinsicInst &I) {
2933     IRBuilder<> IRB(&I);
2934     Value *Addr = I.getArgOperand(0);
2935     const Align Alignment(
2936         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
2937     Value *Mask = I.getArgOperand(2);
2938     Value *PassThru = I.getArgOperand(3);
2939 
2940     Type *ShadowTy = getShadowTy(&I);
2941     Value *ShadowPtr, *OriginPtr;
2942     if (PropagateShadow) {
2943       std::tie(ShadowPtr, OriginPtr) =
2944           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
2945       setShadow(&I, IRB.CreateMaskedLoad(ShadowPtr, Alignment, Mask,
2946                                          getShadow(PassThru), "_msmaskedld"));
2947     } else {
2948       setShadow(&I, getCleanShadow(&I));
2949     }
2950 
2951     if (ClCheckAccessAddress) {
2952       insertShadowCheck(Addr, &I);
2953       insertShadowCheck(Mask, &I);
2954     }
2955 
2956     if (MS.TrackOrigins) {
2957       if (PropagateShadow) {
2958         // Choose between PassThru's and the loaded value's origins.
2959         Value *MaskedPassThruShadow = IRB.CreateAnd(
2960             getShadow(PassThru), IRB.CreateSExt(IRB.CreateNeg(Mask), ShadowTy));
2961 
2962         Value *Acc = IRB.CreateExtractElement(
2963             MaskedPassThruShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2964         for (int i = 1, N = PassThru->getType()->getVectorNumElements(); i < N;
2965              ++i) {
2966           Value *More = IRB.CreateExtractElement(
2967               MaskedPassThruShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2968           Acc = IRB.CreateOr(Acc, More);
2969         }
2970 
2971         Value *Origin = IRB.CreateSelect(
2972             IRB.CreateICmpNE(Acc, Constant::getNullValue(Acc->getType())),
2973             getOrigin(PassThru), IRB.CreateLoad(MS.OriginTy, OriginPtr));
2974 
2975         setOrigin(&I, Origin);
2976       } else {
2977         setOrigin(&I, getCleanOrigin());
2978       }
2979     }
2980     return true;
2981   }
2982 
2983   // Instrument BMI / BMI2 intrinsics.
2984   // All of these intrinsics are Z = I(X, Y)
2985   // where the types of all operands and the result match, and are either i32 or i64.
2986   // The following instrumentation happens to work for all of them:
2987   //   Sz = I(Sx, Y) | (sext (Sy != 0))
2988   void handleBmiIntrinsic(IntrinsicInst &I) {
2989     IRBuilder<> IRB(&I);
2990     Type *ShadowTy = getShadowTy(&I);
2991 
2992     // If any bit of the mask operand is poisoned, then the whole thing is.
2993     Value *SMask = getShadow(&I, 1);
2994     SMask = IRB.CreateSExt(IRB.CreateICmpNE(SMask, getCleanShadow(ShadowTy)),
2995                            ShadowTy);
2996     // Apply the same intrinsic to the shadow of the first operand.
2997     Value *S = IRB.CreateCall(I.getCalledFunction(),
2998                               {getShadow(&I, 0), I.getOperand(1)});
2999     S = IRB.CreateOr(SMask, S);
3000     setShadow(&I, S);
3001     setOriginForNaryOp(I);
3002   }
3003 
3004   void visitIntrinsicInst(IntrinsicInst &I) {
3005     switch (I.getIntrinsicID()) {
3006     case Intrinsic::lifetime_start:
3007       handleLifetimeStart(I);
3008       break;
3009     case Intrinsic::launder_invariant_group:
3010     case Intrinsic::strip_invariant_group:
3011       handleInvariantGroup(I);
3012       break;
3013     case Intrinsic::bswap:
3014       handleBswap(I);
3015       break;
3016     case Intrinsic::masked_store:
3017       handleMaskedStore(I);
3018       break;
3019     case Intrinsic::masked_load:
3020       handleMaskedLoad(I);
3021       break;
3022     case Intrinsic::x86_sse_stmxcsr:
3023       handleStmxcsr(I);
3024       break;
3025     case Intrinsic::x86_sse_ldmxcsr:
3026       handleLdmxcsr(I);
3027       break;
3028     case Intrinsic::x86_avx512_vcvtsd2usi64:
3029     case Intrinsic::x86_avx512_vcvtsd2usi32:
3030     case Intrinsic::x86_avx512_vcvtss2usi64:
3031     case Intrinsic::x86_avx512_vcvtss2usi32:
3032     case Intrinsic::x86_avx512_cvttss2usi64:
3033     case Intrinsic::x86_avx512_cvttss2usi:
3034     case Intrinsic::x86_avx512_cvttsd2usi64:
3035     case Intrinsic::x86_avx512_cvttsd2usi:
3036     case Intrinsic::x86_avx512_cvtusi2ss:
3037     case Intrinsic::x86_avx512_cvtusi642sd:
3038     case Intrinsic::x86_avx512_cvtusi642ss:
3039     case Intrinsic::x86_sse2_cvtsd2si64:
3040     case Intrinsic::x86_sse2_cvtsd2si:
3041     case Intrinsic::x86_sse2_cvtsd2ss:
3042     case Intrinsic::x86_sse2_cvttsd2si64:
3043     case Intrinsic::x86_sse2_cvttsd2si:
3044     case Intrinsic::x86_sse_cvtss2si64:
3045     case Intrinsic::x86_sse_cvtss2si:
3046     case Intrinsic::x86_sse_cvttss2si64:
3047     case Intrinsic::x86_sse_cvttss2si:
3048       handleVectorConvertIntrinsic(I, 1);
3049       break;
3050     case Intrinsic::x86_sse_cvtps2pi:
3051     case Intrinsic::x86_sse_cvttps2pi:
3052       handleVectorConvertIntrinsic(I, 2);
3053       break;
3054 
3055     case Intrinsic::x86_avx512_psll_w_512:
3056     case Intrinsic::x86_avx512_psll_d_512:
3057     case Intrinsic::x86_avx512_psll_q_512:
3058     case Intrinsic::x86_avx512_pslli_w_512:
3059     case Intrinsic::x86_avx512_pslli_d_512:
3060     case Intrinsic::x86_avx512_pslli_q_512:
3061     case Intrinsic::x86_avx512_psrl_w_512:
3062     case Intrinsic::x86_avx512_psrl_d_512:
3063     case Intrinsic::x86_avx512_psrl_q_512:
3064     case Intrinsic::x86_avx512_psra_w_512:
3065     case Intrinsic::x86_avx512_psra_d_512:
3066     case Intrinsic::x86_avx512_psra_q_512:
3067     case Intrinsic::x86_avx512_psrli_w_512:
3068     case Intrinsic::x86_avx512_psrli_d_512:
3069     case Intrinsic::x86_avx512_psrli_q_512:
3070     case Intrinsic::x86_avx512_psrai_w_512:
3071     case Intrinsic::x86_avx512_psrai_d_512:
3072     case Intrinsic::x86_avx512_psrai_q_512:
3073     case Intrinsic::x86_avx512_psra_q_256:
3074     case Intrinsic::x86_avx512_psra_q_128:
3075     case Intrinsic::x86_avx512_psrai_q_256:
3076     case Intrinsic::x86_avx512_psrai_q_128:
3077     case Intrinsic::x86_avx2_psll_w:
3078     case Intrinsic::x86_avx2_psll_d:
3079     case Intrinsic::x86_avx2_psll_q:
3080     case Intrinsic::x86_avx2_pslli_w:
3081     case Intrinsic::x86_avx2_pslli_d:
3082     case Intrinsic::x86_avx2_pslli_q:
3083     case Intrinsic::x86_avx2_psrl_w:
3084     case Intrinsic::x86_avx2_psrl_d:
3085     case Intrinsic::x86_avx2_psrl_q:
3086     case Intrinsic::x86_avx2_psra_w:
3087     case Intrinsic::x86_avx2_psra_d:
3088     case Intrinsic::x86_avx2_psrli_w:
3089     case Intrinsic::x86_avx2_psrli_d:
3090     case Intrinsic::x86_avx2_psrli_q:
3091     case Intrinsic::x86_avx2_psrai_w:
3092     case Intrinsic::x86_avx2_psrai_d:
3093     case Intrinsic::x86_sse2_psll_w:
3094     case Intrinsic::x86_sse2_psll_d:
3095     case Intrinsic::x86_sse2_psll_q:
3096     case Intrinsic::x86_sse2_pslli_w:
3097     case Intrinsic::x86_sse2_pslli_d:
3098     case Intrinsic::x86_sse2_pslli_q:
3099     case Intrinsic::x86_sse2_psrl_w:
3100     case Intrinsic::x86_sse2_psrl_d:
3101     case Intrinsic::x86_sse2_psrl_q:
3102     case Intrinsic::x86_sse2_psra_w:
3103     case Intrinsic::x86_sse2_psra_d:
3104     case Intrinsic::x86_sse2_psrli_w:
3105     case Intrinsic::x86_sse2_psrli_d:
3106     case Intrinsic::x86_sse2_psrli_q:
3107     case Intrinsic::x86_sse2_psrai_w:
3108     case Intrinsic::x86_sse2_psrai_d:
3109     case Intrinsic::x86_mmx_psll_w:
3110     case Intrinsic::x86_mmx_psll_d:
3111     case Intrinsic::x86_mmx_psll_q:
3112     case Intrinsic::x86_mmx_pslli_w:
3113     case Intrinsic::x86_mmx_pslli_d:
3114     case Intrinsic::x86_mmx_pslli_q:
3115     case Intrinsic::x86_mmx_psrl_w:
3116     case Intrinsic::x86_mmx_psrl_d:
3117     case Intrinsic::x86_mmx_psrl_q:
3118     case Intrinsic::x86_mmx_psra_w:
3119     case Intrinsic::x86_mmx_psra_d:
3120     case Intrinsic::x86_mmx_psrli_w:
3121     case Intrinsic::x86_mmx_psrli_d:
3122     case Intrinsic::x86_mmx_psrli_q:
3123     case Intrinsic::x86_mmx_psrai_w:
3124     case Intrinsic::x86_mmx_psrai_d:
3125       handleVectorShiftIntrinsic(I, /* Variable */ false);
3126       break;
3127     case Intrinsic::x86_avx2_psllv_d:
3128     case Intrinsic::x86_avx2_psllv_d_256:
3129     case Intrinsic::x86_avx512_psllv_d_512:
3130     case Intrinsic::x86_avx2_psllv_q:
3131     case Intrinsic::x86_avx2_psllv_q_256:
3132     case Intrinsic::x86_avx512_psllv_q_512:
3133     case Intrinsic::x86_avx2_psrlv_d:
3134     case Intrinsic::x86_avx2_psrlv_d_256:
3135     case Intrinsic::x86_avx512_psrlv_d_512:
3136     case Intrinsic::x86_avx2_psrlv_q:
3137     case Intrinsic::x86_avx2_psrlv_q_256:
3138     case Intrinsic::x86_avx512_psrlv_q_512:
3139     case Intrinsic::x86_avx2_psrav_d:
3140     case Intrinsic::x86_avx2_psrav_d_256:
3141     case Intrinsic::x86_avx512_psrav_d_512:
3142     case Intrinsic::x86_avx512_psrav_q_128:
3143     case Intrinsic::x86_avx512_psrav_q_256:
3144     case Intrinsic::x86_avx512_psrav_q_512:
3145       handleVectorShiftIntrinsic(I, /* Variable */ true);
3146       break;
3147 
3148     case Intrinsic::x86_sse2_packsswb_128:
3149     case Intrinsic::x86_sse2_packssdw_128:
3150     case Intrinsic::x86_sse2_packuswb_128:
3151     case Intrinsic::x86_sse41_packusdw:
3152     case Intrinsic::x86_avx2_packsswb:
3153     case Intrinsic::x86_avx2_packssdw:
3154     case Intrinsic::x86_avx2_packuswb:
3155     case Intrinsic::x86_avx2_packusdw:
3156       handleVectorPackIntrinsic(I);
3157       break;
3158 
3159     case Intrinsic::x86_mmx_packsswb:
3160     case Intrinsic::x86_mmx_packuswb:
3161       handleVectorPackIntrinsic(I, 16);
3162       break;
3163 
3164     case Intrinsic::x86_mmx_packssdw:
3165       handleVectorPackIntrinsic(I, 32);
3166       break;
3167 
3168     case Intrinsic::x86_mmx_psad_bw:
3169     case Intrinsic::x86_sse2_psad_bw:
3170     case Intrinsic::x86_avx2_psad_bw:
3171       handleVectorSadIntrinsic(I);
3172       break;
3173 
3174     case Intrinsic::x86_sse2_pmadd_wd:
3175     case Intrinsic::x86_avx2_pmadd_wd:
3176     case Intrinsic::x86_ssse3_pmadd_ub_sw_128:
3177     case Intrinsic::x86_avx2_pmadd_ub_sw:
3178       handleVectorPmaddIntrinsic(I);
3179       break;
3180 
3181     case Intrinsic::x86_ssse3_pmadd_ub_sw:
3182       handleVectorPmaddIntrinsic(I, 8);
3183       break;
3184 
3185     case Intrinsic::x86_mmx_pmadd_wd:
3186       handleVectorPmaddIntrinsic(I, 16);
3187       break;
3188 
3189     case Intrinsic::x86_sse_cmp_ss:
3190     case Intrinsic::x86_sse2_cmp_sd:
3191     case Intrinsic::x86_sse_comieq_ss:
3192     case Intrinsic::x86_sse_comilt_ss:
3193     case Intrinsic::x86_sse_comile_ss:
3194     case Intrinsic::x86_sse_comigt_ss:
3195     case Intrinsic::x86_sse_comige_ss:
3196     case Intrinsic::x86_sse_comineq_ss:
3197     case Intrinsic::x86_sse_ucomieq_ss:
3198     case Intrinsic::x86_sse_ucomilt_ss:
3199     case Intrinsic::x86_sse_ucomile_ss:
3200     case Intrinsic::x86_sse_ucomigt_ss:
3201     case Intrinsic::x86_sse_ucomige_ss:
3202     case Intrinsic::x86_sse_ucomineq_ss:
3203     case Intrinsic::x86_sse2_comieq_sd:
3204     case Intrinsic::x86_sse2_comilt_sd:
3205     case Intrinsic::x86_sse2_comile_sd:
3206     case Intrinsic::x86_sse2_comigt_sd:
3207     case Intrinsic::x86_sse2_comige_sd:
3208     case Intrinsic::x86_sse2_comineq_sd:
3209     case Intrinsic::x86_sse2_ucomieq_sd:
3210     case Intrinsic::x86_sse2_ucomilt_sd:
3211     case Intrinsic::x86_sse2_ucomile_sd:
3212     case Intrinsic::x86_sse2_ucomigt_sd:
3213     case Intrinsic::x86_sse2_ucomige_sd:
3214     case Intrinsic::x86_sse2_ucomineq_sd:
3215       handleVectorCompareScalarIntrinsic(I);
3216       break;
3217 
3218     case Intrinsic::x86_sse_cmp_ps:
3219     case Intrinsic::x86_sse2_cmp_pd:
3220       // FIXME: For x86_avx_cmp_pd_256 and x86_avx_cmp_ps_256 this function
3221       // generates reasonably looking IR that fails in the backend with "Do not
3222       // know how to split the result of this operator!".
3223       handleVectorComparePackedIntrinsic(I);
3224       break;
3225 
3226     case Intrinsic::x86_bmi_bextr_32:
3227     case Intrinsic::x86_bmi_bextr_64:
3228     case Intrinsic::x86_bmi_bzhi_32:
3229     case Intrinsic::x86_bmi_bzhi_64:
3230     case Intrinsic::x86_bmi_pdep_32:
3231     case Intrinsic::x86_bmi_pdep_64:
3232     case Intrinsic::x86_bmi_pext_32:
3233     case Intrinsic::x86_bmi_pext_64:
3234       handleBmiIntrinsic(I);
3235       break;
3236 
3237     case Intrinsic::is_constant:
3238       // The result of llvm.is.constant() is always defined.
3239       setShadow(&I, getCleanShadow(&I));
3240       setOrigin(&I, getCleanOrigin());
3241       break;
3242 
3243     default:
3244       if (!handleUnknownIntrinsic(I))
3245         visitInstruction(I);
3246       break;
3247     }
3248   }
3249 
3250   void visitCallSite(CallSite CS) {
3251     Instruction &I = *CS.getInstruction();
3252     assert(!I.getMetadata("nosanitize"));
3253     assert((CS.isCall() || CS.isInvoke() || CS.isCallBr()) &&
3254            "Unknown type of CallSite");
3255     if (CS.isCallBr() || (CS.isCall() && cast<CallInst>(&I)->isInlineAsm())) {
3256       // For inline asm (either a call to asm function, or callbr instruction),
3257       // do the usual thing: check argument shadow and mark all outputs as
3258       // clean. Note that any side effects of the inline asm that are not
3259       // immediately visible in its constraints are not handled.
3260       if (ClHandleAsmConservative && MS.CompileKernel)
3261         visitAsmInstruction(I);
3262       else
3263         visitInstruction(I);
3264       return;
3265     }
3266     if (CS.isCall()) {
3267       CallInst *Call = cast<CallInst>(&I);
3268       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
3269 
3270       // We are going to insert code that relies on the fact that the callee
3271       // will become a non-readonly function after it is instrumented by us. To
3272       // prevent this code from being optimized out, mark that function
3273       // non-readonly in advance.
3274       if (Function *Func = Call->getCalledFunction()) {
3275         // Clear out readonly/readnone attributes.
3276         AttrBuilder B;
3277         B.addAttribute(Attribute::ReadOnly)
3278             .addAttribute(Attribute::ReadNone)
3279             .addAttribute(Attribute::WriteOnly)
3280             .addAttribute(Attribute::ArgMemOnly)
3281             .addAttribute(Attribute::Speculatable);
3282         Func->removeAttributes(AttributeList::FunctionIndex, B);
3283       }
3284 
3285       maybeMarkSanitizerLibraryCallNoBuiltin(Call, TLI);
3286     }
3287     IRBuilder<> IRB(&I);
3288 
3289     unsigned ArgOffset = 0;
3290     LLVM_DEBUG(dbgs() << "  CallSite: " << I << "\n");
3291     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
3292          ArgIt != End; ++ArgIt) {
3293       Value *A = *ArgIt;
3294       unsigned i = ArgIt - CS.arg_begin();
3295       if (!A->getType()->isSized()) {
3296         LLVM_DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
3297         continue;
3298       }
3299       unsigned Size = 0;
3300       Value *Store = nullptr;
3301       // Compute the Shadow for arg even if it is ByVal, because
3302       // in that case getShadow() will copy the actual arg shadow to
3303       // __msan_param_tls.
3304       Value *ArgShadow = getShadow(A);
3305       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
3306       LLVM_DEBUG(dbgs() << "  Arg#" << i << ": " << *A
3307                         << " Shadow: " << *ArgShadow << "\n");
3308       bool ArgIsInitialized = false;
3309       const DataLayout &DL = F.getParent()->getDataLayout();
3310       if (CS.paramHasAttr(i, Attribute::ByVal)) {
3311         assert(A->getType()->isPointerTy() &&
3312                "ByVal argument is not a pointer!");
3313         Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
3314         if (ArgOffset + Size > kParamTLSSize) break;
3315         const MaybeAlign ParamAlignment(CS.getParamAlignment(i));
3316         MaybeAlign Alignment = llvm::None;
3317         if (ParamAlignment)
3318           Alignment = std::min(*ParamAlignment, kShadowTLSAlignment);
3319         Value *AShadowPtr =
3320             getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), Alignment,
3321                                /*isStore*/ false)
3322                 .first;
3323 
3324         Store = IRB.CreateMemCpy(ArgShadowBase, Alignment, AShadowPtr,
3325                                  Alignment, Size);
3326         // TODO(glider): need to copy origins.
3327       } else {
3328         Size = DL.getTypeAllocSize(A->getType());
3329         if (ArgOffset + Size > kParamTLSSize) break;
3330         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
3331                                        kShadowTLSAlignment);
3332         Constant *Cst = dyn_cast<Constant>(ArgShadow);
3333         if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
3334       }
3335       if (MS.TrackOrigins && !ArgIsInitialized)
3336         IRB.CreateStore(getOrigin(A),
3337                         getOriginPtrForArgument(A, IRB, ArgOffset));
3338       (void)Store;
3339       assert(Size != 0 && Store != nullptr);
3340       LLVM_DEBUG(dbgs() << "  Param:" << *Store << "\n");
3341       ArgOffset += alignTo(Size, 8);
3342     }
3343     LLVM_DEBUG(dbgs() << "  done with call args\n");
3344 
3345     FunctionType *FT = CS.getFunctionType();
3346     if (FT->isVarArg()) {
3347       VAHelper->visitCallSite(CS, IRB);
3348     }
3349 
3350     // Now, get the shadow for the RetVal.
3351     if (!I.getType()->isSized()) return;
3352     // Don't emit the epilogue for musttail call returns.
3353     if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
3354     IRBuilder<> IRBBefore(&I);
3355     // Until we have full dynamic coverage, make sure the retval shadow is 0.
3356     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
3357     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
3358     BasicBlock::iterator NextInsn;
3359     if (CS.isCall()) {
3360       NextInsn = ++I.getIterator();
3361       assert(NextInsn != I.getParent()->end());
3362     } else {
3363       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
3364       if (!NormalDest->getSinglePredecessor()) {
3365         // FIXME: this case is tricky, so we are just conservative here.
3366         // Perhaps we need to split the edge between this BB and NormalDest,
3367         // but a naive attempt to use SplitEdge leads to a crash.
3368         setShadow(&I, getCleanShadow(&I));
3369         setOrigin(&I, getCleanOrigin());
3370         return;
3371       }
3372       // FIXME: NextInsn is likely in a basic block that has not been visited yet.
3373       // Anything inserted there will be instrumented by MSan later!
3374       NextInsn = NormalDest->getFirstInsertionPt();
3375       assert(NextInsn != NormalDest->end() &&
3376              "Could not find insertion point for retval shadow load");
3377     }
3378     IRBuilder<> IRBAfter(&*NextInsn);
3379     Value *RetvalShadow = IRBAfter.CreateAlignedLoad(
3380         getShadowTy(&I), getShadowPtrForRetval(&I, IRBAfter),
3381         kShadowTLSAlignment, "_msret");
3382     setShadow(&I, RetvalShadow);
3383     if (MS.TrackOrigins)
3384       setOrigin(&I, IRBAfter.CreateLoad(MS.OriginTy,
3385                                         getOriginPtrForRetval(IRBAfter)));
3386   }
3387 
3388   bool isAMustTailRetVal(Value *RetVal) {
3389     if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
3390       RetVal = I->getOperand(0);
3391     }
3392     if (auto *I = dyn_cast<CallInst>(RetVal)) {
3393       return I->isMustTailCall();
3394     }
3395     return false;
3396   }
3397 
3398   void visitReturnInst(ReturnInst &I) {
3399     IRBuilder<> IRB(&I);
3400     Value *RetVal = I.getReturnValue();
3401     if (!RetVal) return;
3402     // Don't emit the epilogue for musttail call returns.
3403     if (isAMustTailRetVal(RetVal)) return;
3404     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
3405     if (CheckReturnValue) {
3406       insertShadowCheck(RetVal, &I);
3407       Value *Shadow = getCleanShadow(RetVal);
3408       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
3409     } else {
3410       Value *Shadow = getShadow(RetVal);
3411       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
3412       if (MS.TrackOrigins)
3413         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
3414     }
3415   }
3416 
3417   void visitPHINode(PHINode &I) {
3418     IRBuilder<> IRB(&I);
3419     if (!PropagateShadow) {
3420       setShadow(&I, getCleanShadow(&I));
3421       setOrigin(&I, getCleanOrigin());
3422       return;
3423     }
3424 
3425     ShadowPHINodes.push_back(&I);
3426     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
3427                                 "_msphi_s"));
3428     if (MS.TrackOrigins)
3429       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
3430                                   "_msphi_o"));
3431   }
3432 
3433   Value *getLocalVarDescription(AllocaInst &I) {
3434     SmallString<2048> StackDescriptionStorage;
3435     raw_svector_ostream StackDescription(StackDescriptionStorage);
3436     // We create a string with a description of the stack allocation and
3437     // pass it into __msan_set_alloca_origin.
3438     // It will be printed by the run-time if stack-originated UMR is found.
3439     // The first 4 bytes of the string are set to '----' and will be replaced
3440     // by __msan_va_arg_overflow_size_tls at the first call.
3441     StackDescription << "----" << I.getName() << "@" << F.getName();
3442     return createPrivateNonConstGlobalForString(*F.getParent(),
3443                                                 StackDescription.str());
3444   }
3445 
3446   void poisonAllocaUserspace(AllocaInst &I, IRBuilder<> &IRB, Value *Len) {
3447     if (PoisonStack && ClPoisonStackWithCall) {
3448       IRB.CreateCall(MS.MsanPoisonStackFn,
3449                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len});
3450     } else {
3451       Value *ShadowBase, *OriginBase;
3452       std::tie(ShadowBase, OriginBase) = getShadowOriginPtr(
3453           &I, IRB, IRB.getInt8Ty(), Align::None(), /*isStore*/ true);
3454 
3455       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
3456       IRB.CreateMemSet(ShadowBase, PoisonValue, Len,
3457                        MaybeAlign(I.getAlignment()));
3458     }
3459 
3460     if (PoisonStack && MS.TrackOrigins) {
3461       Value *Descr = getLocalVarDescription(I);
3462       IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
3463                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len,
3464                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
3465                       IRB.CreatePointerCast(&F, MS.IntptrTy)});
3466     }
3467   }
3468 
3469   void poisonAllocaKmsan(AllocaInst &I, IRBuilder<> &IRB, Value *Len) {
3470     Value *Descr = getLocalVarDescription(I);
3471     if (PoisonStack) {
3472       IRB.CreateCall(MS.MsanPoisonAllocaFn,
3473                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len,
3474                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy())});
3475     } else {
3476       IRB.CreateCall(MS.MsanUnpoisonAllocaFn,
3477                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len});
3478     }
3479   }
3480 
3481   void instrumentAlloca(AllocaInst &I, Instruction *InsPoint = nullptr) {
3482     if (!InsPoint)
3483       InsPoint = &I;
3484     IRBuilder<> IRB(InsPoint->getNextNode());
3485     const DataLayout &DL = F.getParent()->getDataLayout();
3486     uint64_t TypeSize = DL.getTypeAllocSize(I.getAllocatedType());
3487     Value *Len = ConstantInt::get(MS.IntptrTy, TypeSize);
3488     if (I.isArrayAllocation())
3489       Len = IRB.CreateMul(Len, I.getArraySize());
3490 
3491     if (MS.CompileKernel)
3492       poisonAllocaKmsan(I, IRB, Len);
3493     else
3494       poisonAllocaUserspace(I, IRB, Len);
3495   }
3496 
3497   void visitAllocaInst(AllocaInst &I) {
3498     setShadow(&I, getCleanShadow(&I));
3499     setOrigin(&I, getCleanOrigin());
3500     // We'll get to this alloca later unless it's poisoned at the corresponding
3501     // llvm.lifetime.start.
3502     AllocaSet.insert(&I);
3503   }
3504 
3505   void visitSelectInst(SelectInst& I) {
3506     IRBuilder<> IRB(&I);
3507     // a = select b, c, d
3508     Value *B = I.getCondition();
3509     Value *C = I.getTrueValue();
3510     Value *D = I.getFalseValue();
3511     Value *Sb = getShadow(B);
3512     Value *Sc = getShadow(C);
3513     Value *Sd = getShadow(D);
3514 
3515     // Result shadow if condition shadow is 0.
3516     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
3517     Value *Sa1;
3518     if (I.getType()->isAggregateType()) {
3519       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
3520       // an extra "select". This results in much more compact IR.
3521       // Sa = select Sb, poisoned, (select b, Sc, Sd)
3522       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
3523     } else {
3524       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
3525       // If Sb (condition is poisoned), look for bits in c and d that are equal
3526       // and both unpoisoned.
3527       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
3528 
3529       // Cast arguments to shadow-compatible type.
3530       C = CreateAppToShadowCast(IRB, C);
3531       D = CreateAppToShadowCast(IRB, D);
3532 
3533       // Result shadow if condition shadow is 1.
3534       Sa1 = IRB.CreateOr({IRB.CreateXor(C, D), Sc, Sd});
3535     }
3536     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
3537     setShadow(&I, Sa);
3538     if (MS.TrackOrigins) {
3539       // Origins are always i32, so any vector conditions must be flattened.
3540       // FIXME: consider tracking vector origins for app vectors?
3541       if (B->getType()->isVectorTy()) {
3542         Type *FlatTy = getShadowTyNoVec(B->getType());
3543         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
3544                                 ConstantInt::getNullValue(FlatTy));
3545         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
3546                                       ConstantInt::getNullValue(FlatTy));
3547       }
3548       // a = select b, c, d
3549       // Oa = Sb ? Ob : (b ? Oc : Od)
3550       setOrigin(
3551           &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
3552                                IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
3553                                                 getOrigin(I.getFalseValue()))));
3554     }
3555   }
3556 
3557   void visitLandingPadInst(LandingPadInst &I) {
3558     // Do nothing.
3559     // See https://github.com/google/sanitizers/issues/504
3560     setShadow(&I, getCleanShadow(&I));
3561     setOrigin(&I, getCleanOrigin());
3562   }
3563 
3564   void visitCatchSwitchInst(CatchSwitchInst &I) {
3565     setShadow(&I, getCleanShadow(&I));
3566     setOrigin(&I, getCleanOrigin());
3567   }
3568 
3569   void visitFuncletPadInst(FuncletPadInst &I) {
3570     setShadow(&I, getCleanShadow(&I));
3571     setOrigin(&I, getCleanOrigin());
3572   }
3573 
3574   void visitGetElementPtrInst(GetElementPtrInst &I) {
3575     handleShadowOr(I);
3576   }
3577 
3578   void visitExtractValueInst(ExtractValueInst &I) {
3579     IRBuilder<> IRB(&I);
3580     Value *Agg = I.getAggregateOperand();
3581     LLVM_DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
3582     Value *AggShadow = getShadow(Agg);
3583     LLVM_DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
3584     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
3585     LLVM_DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
3586     setShadow(&I, ResShadow);
3587     setOriginForNaryOp(I);
3588   }
3589 
3590   void visitInsertValueInst(InsertValueInst &I) {
3591     IRBuilder<> IRB(&I);
3592     LLVM_DEBUG(dbgs() << "InsertValue:  " << I << "\n");
3593     Value *AggShadow = getShadow(I.getAggregateOperand());
3594     Value *InsShadow = getShadow(I.getInsertedValueOperand());
3595     LLVM_DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
3596     LLVM_DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
3597     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
3598     LLVM_DEBUG(dbgs() << "   Res:        " << *Res << "\n");
3599     setShadow(&I, Res);
3600     setOriginForNaryOp(I);
3601   }
3602 
3603   void dumpInst(Instruction &I) {
3604     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
3605       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
3606     } else {
3607       errs() << "ZZZ " << I.getOpcodeName() << "\n";
3608     }
3609     errs() << "QQQ " << I << "\n";
3610   }
3611 
3612   void visitResumeInst(ResumeInst &I) {
3613     LLVM_DEBUG(dbgs() << "Resume: " << I << "\n");
3614     // Nothing to do here.
3615   }
3616 
3617   void visitCleanupReturnInst(CleanupReturnInst &CRI) {
3618     LLVM_DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
3619     // Nothing to do here.
3620   }
3621 
3622   void visitCatchReturnInst(CatchReturnInst &CRI) {
3623     LLVM_DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
3624     // Nothing to do here.
3625   }
3626 
3627   void instrumentAsmArgument(Value *Operand, Instruction &I, IRBuilder<> &IRB,
3628                              const DataLayout &DL, bool isOutput) {
3629     // For each assembly argument, we check its value for being initialized.
3630     // If the argument is a pointer, we assume it points to a single element
3631     // of the corresponding type (or to a 8-byte word, if the type is unsized).
3632     // Each such pointer is instrumented with a call to the runtime library.
3633     Type *OpType = Operand->getType();
3634     // Check the operand value itself.
3635     insertShadowCheck(Operand, &I);
3636     if (!OpType->isPointerTy() || !isOutput) {
3637       assert(!isOutput);
3638       return;
3639     }
3640     Type *ElType = OpType->getPointerElementType();
3641     if (!ElType->isSized())
3642       return;
3643     int Size = DL.getTypeStoreSize(ElType);
3644     Value *Ptr = IRB.CreatePointerCast(Operand, IRB.getInt8PtrTy());
3645     Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size);
3646     IRB.CreateCall(MS.MsanInstrumentAsmStoreFn, {Ptr, SizeVal});
3647   }
3648 
3649   /// Get the number of output arguments returned by pointers.
3650   int getNumOutputArgs(InlineAsm *IA, CallBase *CB) {
3651     int NumRetOutputs = 0;
3652     int NumOutputs = 0;
3653     Type *RetTy = cast<Value>(CB)->getType();
3654     if (!RetTy->isVoidTy()) {
3655       // Register outputs are returned via the CallInst return value.
3656       auto *ST = dyn_cast<StructType>(RetTy);
3657       if (ST)
3658         NumRetOutputs = ST->getNumElements();
3659       else
3660         NumRetOutputs = 1;
3661     }
3662     InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
3663     for (size_t i = 0, n = Constraints.size(); i < n; i++) {
3664       InlineAsm::ConstraintInfo Info = Constraints[i];
3665       switch (Info.Type) {
3666       case InlineAsm::isOutput:
3667         NumOutputs++;
3668         break;
3669       default:
3670         break;
3671       }
3672     }
3673     return NumOutputs - NumRetOutputs;
3674   }
3675 
3676   void visitAsmInstruction(Instruction &I) {
3677     // Conservative inline assembly handling: check for poisoned shadow of
3678     // asm() arguments, then unpoison the result and all the memory locations
3679     // pointed to by those arguments.
3680     // An inline asm() statement in C++ contains lists of input and output
3681     // arguments used by the assembly code. These are mapped to operands of the
3682     // CallInst as follows:
3683     //  - nR register outputs ("=r) are returned by value in a single structure
3684     //  (SSA value of the CallInst);
3685     //  - nO other outputs ("=m" and others) are returned by pointer as first
3686     // nO operands of the CallInst;
3687     //  - nI inputs ("r", "m" and others) are passed to CallInst as the
3688     // remaining nI operands.
3689     // The total number of asm() arguments in the source is nR+nO+nI, and the
3690     // corresponding CallInst has nO+nI+1 operands (the last operand is the
3691     // function to be called).
3692     const DataLayout &DL = F.getParent()->getDataLayout();
3693     CallBase *CB = cast<CallBase>(&I);
3694     IRBuilder<> IRB(&I);
3695     InlineAsm *IA = cast<InlineAsm>(CB->getCalledValue());
3696     int OutputArgs = getNumOutputArgs(IA, CB);
3697     // The last operand of a CallInst is the function itself.
3698     int NumOperands = CB->getNumOperands() - 1;
3699 
3700     // Check input arguments. Doing so before unpoisoning output arguments, so
3701     // that we won't overwrite uninit values before checking them.
3702     for (int i = OutputArgs; i < NumOperands; i++) {
3703       Value *Operand = CB->getOperand(i);
3704       instrumentAsmArgument(Operand, I, IRB, DL, /*isOutput*/ false);
3705     }
3706     // Unpoison output arguments. This must happen before the actual InlineAsm
3707     // call, so that the shadow for memory published in the asm() statement
3708     // remains valid.
3709     for (int i = 0; i < OutputArgs; i++) {
3710       Value *Operand = CB->getOperand(i);
3711       instrumentAsmArgument(Operand, I, IRB, DL, /*isOutput*/ true);
3712     }
3713 
3714     setShadow(&I, getCleanShadow(&I));
3715     setOrigin(&I, getCleanOrigin());
3716   }
3717 
3718   void visitInstruction(Instruction &I) {
3719     // Everything else: stop propagating and check for poisoned shadow.
3720     if (ClDumpStrictInstructions)
3721       dumpInst(I);
3722     LLVM_DEBUG(dbgs() << "DEFAULT: " << I << "\n");
3723     for (size_t i = 0, n = I.getNumOperands(); i < n; i++) {
3724       Value *Operand = I.getOperand(i);
3725       if (Operand->getType()->isSized())
3726         insertShadowCheck(Operand, &I);
3727     }
3728     setShadow(&I, getCleanShadow(&I));
3729     setOrigin(&I, getCleanOrigin());
3730   }
3731 };
3732 
3733 /// AMD64-specific implementation of VarArgHelper.
3734 struct VarArgAMD64Helper : public VarArgHelper {
3735   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
3736   // See a comment in visitCallSite for more details.
3737   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
3738   static const unsigned AMD64FpEndOffsetSSE = 176;
3739   // If SSE is disabled, fp_offset in va_list is zero.
3740   static const unsigned AMD64FpEndOffsetNoSSE = AMD64GpEndOffset;
3741 
3742   unsigned AMD64FpEndOffset;
3743   Function &F;
3744   MemorySanitizer &MS;
3745   MemorySanitizerVisitor &MSV;
3746   Value *VAArgTLSCopy = nullptr;
3747   Value *VAArgTLSOriginCopy = nullptr;
3748   Value *VAArgOverflowSize = nullptr;
3749 
3750   SmallVector<CallInst*, 16> VAStartInstrumentationList;
3751 
3752   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
3753 
3754   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
3755                     MemorySanitizerVisitor &MSV)
3756       : F(F), MS(MS), MSV(MSV) {
3757     AMD64FpEndOffset = AMD64FpEndOffsetSSE;
3758     for (const auto &Attr : F.getAttributes().getFnAttributes()) {
3759       if (Attr.isStringAttribute() &&
3760           (Attr.getKindAsString() == "target-features")) {
3761         if (Attr.getValueAsString().contains("-sse"))
3762           AMD64FpEndOffset = AMD64FpEndOffsetNoSSE;
3763         break;
3764       }
3765     }
3766   }
3767 
3768   ArgKind classifyArgument(Value* arg) {
3769     // A very rough approximation of X86_64 argument classification rules.
3770     Type *T = arg->getType();
3771     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
3772       return AK_FloatingPoint;
3773     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
3774       return AK_GeneralPurpose;
3775     if (T->isPointerTy())
3776       return AK_GeneralPurpose;
3777     return AK_Memory;
3778   }
3779 
3780   // For VarArg functions, store the argument shadow in an ABI-specific format
3781   // that corresponds to va_list layout.
3782   // We do this because Clang lowers va_arg in the frontend, and this pass
3783   // only sees the low level code that deals with va_list internals.
3784   // A much easier alternative (provided that Clang emits va_arg instructions)
3785   // would have been to associate each live instance of va_list with a copy of
3786   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
3787   // order.
3788   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
3789     unsigned GpOffset = 0;
3790     unsigned FpOffset = AMD64GpEndOffset;
3791     unsigned OverflowOffset = AMD64FpEndOffset;
3792     const DataLayout &DL = F.getParent()->getDataLayout();
3793     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
3794          ArgIt != End; ++ArgIt) {
3795       Value *A = *ArgIt;
3796       unsigned ArgNo = CS.getArgumentNo(ArgIt);
3797       bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
3798       bool IsByVal = CS.paramHasAttr(ArgNo, Attribute::ByVal);
3799       if (IsByVal) {
3800         // ByVal arguments always go to the overflow area.
3801         // Fixed arguments passed through the overflow area will be stepped
3802         // over by va_start, so don't count them towards the offset.
3803         if (IsFixed)
3804           continue;
3805         assert(A->getType()->isPointerTy());
3806         Type *RealTy = A->getType()->getPointerElementType();
3807         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
3808         Value *ShadowBase = getShadowPtrForVAArgument(
3809             RealTy, IRB, OverflowOffset, alignTo(ArgSize, 8));
3810         Value *OriginBase = nullptr;
3811         if (MS.TrackOrigins)
3812           OriginBase = getOriginPtrForVAArgument(RealTy, IRB, OverflowOffset);
3813         OverflowOffset += alignTo(ArgSize, 8);
3814         if (!ShadowBase)
3815           continue;
3816         Value *ShadowPtr, *OriginPtr;
3817         std::tie(ShadowPtr, OriginPtr) =
3818             MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), kShadowTLSAlignment,
3819                                    /*isStore*/ false);
3820 
3821         IRB.CreateMemCpy(ShadowBase, kShadowTLSAlignment, ShadowPtr,
3822                          kShadowTLSAlignment, ArgSize);
3823         if (MS.TrackOrigins)
3824           IRB.CreateMemCpy(OriginBase, kShadowTLSAlignment, OriginPtr,
3825                            kShadowTLSAlignment, ArgSize);
3826       } else {
3827         ArgKind AK = classifyArgument(A);
3828         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
3829           AK = AK_Memory;
3830         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
3831           AK = AK_Memory;
3832         Value *ShadowBase, *OriginBase = nullptr;
3833         switch (AK) {
3834           case AK_GeneralPurpose:
3835             ShadowBase =
3836                 getShadowPtrForVAArgument(A->getType(), IRB, GpOffset, 8);
3837             if (MS.TrackOrigins)
3838               OriginBase =
3839                   getOriginPtrForVAArgument(A->getType(), IRB, GpOffset);
3840             GpOffset += 8;
3841             break;
3842           case AK_FloatingPoint:
3843             ShadowBase =
3844                 getShadowPtrForVAArgument(A->getType(), IRB, FpOffset, 16);
3845             if (MS.TrackOrigins)
3846               OriginBase =
3847                   getOriginPtrForVAArgument(A->getType(), IRB, FpOffset);
3848             FpOffset += 16;
3849             break;
3850           case AK_Memory:
3851             if (IsFixed)
3852               continue;
3853             uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
3854             ShadowBase =
3855                 getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset, 8);
3856             if (MS.TrackOrigins)
3857               OriginBase =
3858                   getOriginPtrForVAArgument(A->getType(), IRB, OverflowOffset);
3859             OverflowOffset += alignTo(ArgSize, 8);
3860         }
3861         // Take fixed arguments into account for GpOffset and FpOffset,
3862         // but don't actually store shadows for them.
3863         // TODO(glider): don't call get*PtrForVAArgument() for them.
3864         if (IsFixed)
3865           continue;
3866         if (!ShadowBase)
3867           continue;
3868         Value *Shadow = MSV.getShadow(A);
3869         IRB.CreateAlignedStore(Shadow, ShadowBase, kShadowTLSAlignment);
3870         if (MS.TrackOrigins) {
3871           Value *Origin = MSV.getOrigin(A);
3872           unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
3873           MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize,
3874                           std::max(kShadowTLSAlignment, kMinOriginAlignment));
3875         }
3876       }
3877     }
3878     Constant *OverflowSize =
3879       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
3880     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
3881   }
3882 
3883   /// Compute the shadow address for a given va_arg.
3884   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3885                                    unsigned ArgOffset, unsigned ArgSize) {
3886     // Make sure we don't overflow __msan_va_arg_tls.
3887     if (ArgOffset + ArgSize > kParamTLSSize)
3888       return nullptr;
3889     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3890     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3891     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3892                               "_msarg_va_s");
3893   }
3894 
3895   /// Compute the origin address for a given va_arg.
3896   Value *getOriginPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, int ArgOffset) {
3897     Value *Base = IRB.CreatePointerCast(MS.VAArgOriginTLS, MS.IntptrTy);
3898     // getOriginPtrForVAArgument() is always called after
3899     // getShadowPtrForVAArgument(), so __msan_va_arg_origin_tls can never
3900     // overflow.
3901     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3902     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
3903                               "_msarg_va_o");
3904   }
3905 
3906   void unpoisonVAListTagForInst(IntrinsicInst &I) {
3907     IRBuilder<> IRB(&I);
3908     Value *VAListTag = I.getArgOperand(0);
3909     Value *ShadowPtr, *OriginPtr;
3910     const Align Alignment = Align(8);
3911     std::tie(ShadowPtr, OriginPtr) =
3912         MSV.getShadowOriginPtr(VAListTag, IRB, IRB.getInt8Ty(), Alignment,
3913                                /*isStore*/ true);
3914 
3915     // Unpoison the whole __va_list_tag.
3916     // FIXME: magic ABI constants.
3917     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3918                      /* size */ 24, Alignment, false);
3919     // We shouldn't need to zero out the origins, as they're only checked for
3920     // nonzero shadow.
3921   }
3922 
3923   void visitVAStartInst(VAStartInst &I) override {
3924     if (F.getCallingConv() == CallingConv::Win64)
3925       return;
3926     VAStartInstrumentationList.push_back(&I);
3927     unpoisonVAListTagForInst(I);
3928   }
3929 
3930   void visitVACopyInst(VACopyInst &I) override {
3931     if (F.getCallingConv() == CallingConv::Win64) return;
3932     unpoisonVAListTagForInst(I);
3933   }
3934 
3935   void finalizeInstrumentation() override {
3936     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
3937            "finalizeInstrumentation called twice");
3938     if (!VAStartInstrumentationList.empty()) {
3939       // If there is a va_start in this function, make a backup copy of
3940       // va_arg_tls somewhere in the function entry block.
3941       IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
3942       VAArgOverflowSize =
3943           IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
3944       Value *CopySize =
3945         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
3946                       VAArgOverflowSize);
3947       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3948       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
3949       if (MS.TrackOrigins) {
3950         VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3951         IRB.CreateMemCpy(VAArgTLSOriginCopy, Align(8), MS.VAArgOriginTLS,
3952                          Align(8), CopySize);
3953       }
3954     }
3955 
3956     // Instrument va_start.
3957     // Copy va_list shadow from the backup copy of the TLS contents.
3958     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3959       CallInst *OrigInst = VAStartInstrumentationList[i];
3960       IRBuilder<> IRB(OrigInst->getNextNode());
3961       Value *VAListTag = OrigInst->getArgOperand(0);
3962 
3963       Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C);
3964       Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr(
3965           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3966                         ConstantInt::get(MS.IntptrTy, 16)),
3967           PointerType::get(RegSaveAreaPtrTy, 0));
3968       Value *RegSaveAreaPtr =
3969           IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr);
3970       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
3971       const Align Alignment = Align(16);
3972       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
3973           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
3974                                  Alignment, /*isStore*/ true);
3975       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
3976                        AMD64FpEndOffset);
3977       if (MS.TrackOrigins)
3978         IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy,
3979                          Alignment, AMD64FpEndOffset);
3980       Type *OverflowArgAreaPtrTy = Type::getInt64PtrTy(*MS.C);
3981       Value *OverflowArgAreaPtrPtr = IRB.CreateIntToPtr(
3982           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3983                         ConstantInt::get(MS.IntptrTy, 8)),
3984           PointerType::get(OverflowArgAreaPtrTy, 0));
3985       Value *OverflowArgAreaPtr =
3986           IRB.CreateLoad(OverflowArgAreaPtrTy, OverflowArgAreaPtrPtr);
3987       Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr;
3988       std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) =
3989           MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(),
3990                                  Alignment, /*isStore*/ true);
3991       Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
3992                                              AMD64FpEndOffset);
3993       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment,
3994                        VAArgOverflowSize);
3995       if (MS.TrackOrigins) {
3996         SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy,
3997                                         AMD64FpEndOffset);
3998         IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment,
3999                          VAArgOverflowSize);
4000       }
4001     }
4002   }
4003 };
4004 
4005 /// MIPS64-specific implementation of VarArgHelper.
4006 struct VarArgMIPS64Helper : public VarArgHelper {
4007   Function &F;
4008   MemorySanitizer &MS;
4009   MemorySanitizerVisitor &MSV;
4010   Value *VAArgTLSCopy = nullptr;
4011   Value *VAArgSize = nullptr;
4012 
4013   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4014 
4015   VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
4016                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4017 
4018   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
4019     unsigned VAArgOffset = 0;
4020     const DataLayout &DL = F.getParent()->getDataLayout();
4021     for (CallSite::arg_iterator ArgIt = CS.arg_begin() +
4022          CS.getFunctionType()->getNumParams(), End = CS.arg_end();
4023          ArgIt != End; ++ArgIt) {
4024       Triple TargetTriple(F.getParent()->getTargetTriple());
4025       Value *A = *ArgIt;
4026       Value *Base;
4027       uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4028       if (TargetTriple.getArch() == Triple::mips64) {
4029         // Adjusting the shadow for argument with size < 8 to match the placement
4030         // of bits in big endian system
4031         if (ArgSize < 8)
4032           VAArgOffset += (8 - ArgSize);
4033       }
4034       Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset, ArgSize);
4035       VAArgOffset += ArgSize;
4036       VAArgOffset = alignTo(VAArgOffset, 8);
4037       if (!Base)
4038         continue;
4039       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4040     }
4041 
4042     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
4043     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
4044     // a new class member i.e. it is the total size of all VarArgs.
4045     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
4046   }
4047 
4048   /// Compute the shadow address for a given va_arg.
4049   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4050                                    unsigned ArgOffset, unsigned ArgSize) {
4051     // Make sure we don't overflow __msan_va_arg_tls.
4052     if (ArgOffset + ArgSize > kParamTLSSize)
4053       return nullptr;
4054     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4055     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4056     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4057                               "_msarg");
4058   }
4059 
4060   void visitVAStartInst(VAStartInst &I) override {
4061     IRBuilder<> IRB(&I);
4062     VAStartInstrumentationList.push_back(&I);
4063     Value *VAListTag = I.getArgOperand(0);
4064     Value *ShadowPtr, *OriginPtr;
4065     const Align Alignment = Align(8);
4066     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4067         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4068     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4069                      /* size */ 8, Alignment, false);
4070   }
4071 
4072   void visitVACopyInst(VACopyInst &I) override {
4073     IRBuilder<> IRB(&I);
4074     VAStartInstrumentationList.push_back(&I);
4075     Value *VAListTag = I.getArgOperand(0);
4076     Value *ShadowPtr, *OriginPtr;
4077     const Align Alignment = Align(8);
4078     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4079         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4080     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4081                      /* size */ 8, Alignment, false);
4082   }
4083 
4084   void finalizeInstrumentation() override {
4085     assert(!VAArgSize && !VAArgTLSCopy &&
4086            "finalizeInstrumentation called twice");
4087     IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4088     VAArgSize = IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4089     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
4090                                     VAArgSize);
4091 
4092     if (!VAStartInstrumentationList.empty()) {
4093       // If there is a va_start in this function, make a backup copy of
4094       // va_arg_tls somewhere in the function entry block.
4095       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4096       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4097     }
4098 
4099     // Instrument va_start.
4100     // Copy va_list shadow from the backup copy of the TLS contents.
4101     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4102       CallInst *OrigInst = VAStartInstrumentationList[i];
4103       IRBuilder<> IRB(OrigInst->getNextNode());
4104       Value *VAListTag = OrigInst->getArgOperand(0);
4105       Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4106       Value *RegSaveAreaPtrPtr =
4107           IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4108                              PointerType::get(RegSaveAreaPtrTy, 0));
4109       Value *RegSaveAreaPtr =
4110           IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr);
4111       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
4112       const Align Alignment = Align(8);
4113       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
4114           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4115                                  Alignment, /*isStore*/ true);
4116       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
4117                        CopySize);
4118     }
4119   }
4120 };
4121 
4122 /// AArch64-specific implementation of VarArgHelper.
4123 struct VarArgAArch64Helper : public VarArgHelper {
4124   static const unsigned kAArch64GrArgSize = 64;
4125   static const unsigned kAArch64VrArgSize = 128;
4126 
4127   static const unsigned AArch64GrBegOffset = 0;
4128   static const unsigned AArch64GrEndOffset = kAArch64GrArgSize;
4129   // Make VR space aligned to 16 bytes.
4130   static const unsigned AArch64VrBegOffset = AArch64GrEndOffset;
4131   static const unsigned AArch64VrEndOffset = AArch64VrBegOffset
4132                                              + kAArch64VrArgSize;
4133   static const unsigned AArch64VAEndOffset = AArch64VrEndOffset;
4134 
4135   Function &F;
4136   MemorySanitizer &MS;
4137   MemorySanitizerVisitor &MSV;
4138   Value *VAArgTLSCopy = nullptr;
4139   Value *VAArgOverflowSize = nullptr;
4140 
4141   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4142 
4143   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
4144 
4145   VarArgAArch64Helper(Function &F, MemorySanitizer &MS,
4146                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4147 
4148   ArgKind classifyArgument(Value* arg) {
4149     Type *T = arg->getType();
4150     if (T->isFPOrFPVectorTy())
4151       return AK_FloatingPoint;
4152     if ((T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
4153         || (T->isPointerTy()))
4154       return AK_GeneralPurpose;
4155     return AK_Memory;
4156   }
4157 
4158   // The instrumentation stores the argument shadow in a non ABI-specific
4159   // format because it does not know which argument is named (since Clang,
4160   // like x86_64 case, lowers the va_args in the frontend and this pass only
4161   // sees the low level code that deals with va_list internals).
4162   // The first seven GR registers are saved in the first 56 bytes of the
4163   // va_arg tls arra, followers by the first 8 FP/SIMD registers, and then
4164   // the remaining arguments.
4165   // Using constant offset within the va_arg TLS array allows fast copy
4166   // in the finalize instrumentation.
4167   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
4168     unsigned GrOffset = AArch64GrBegOffset;
4169     unsigned VrOffset = AArch64VrBegOffset;
4170     unsigned OverflowOffset = AArch64VAEndOffset;
4171 
4172     const DataLayout &DL = F.getParent()->getDataLayout();
4173     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
4174          ArgIt != End; ++ArgIt) {
4175       Value *A = *ArgIt;
4176       unsigned ArgNo = CS.getArgumentNo(ArgIt);
4177       bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
4178       ArgKind AK = classifyArgument(A);
4179       if (AK == AK_GeneralPurpose && GrOffset >= AArch64GrEndOffset)
4180         AK = AK_Memory;
4181       if (AK == AK_FloatingPoint && VrOffset >= AArch64VrEndOffset)
4182         AK = AK_Memory;
4183       Value *Base;
4184       switch (AK) {
4185         case AK_GeneralPurpose:
4186           Base = getShadowPtrForVAArgument(A->getType(), IRB, GrOffset, 8);
4187           GrOffset += 8;
4188           break;
4189         case AK_FloatingPoint:
4190           Base = getShadowPtrForVAArgument(A->getType(), IRB, VrOffset, 8);
4191           VrOffset += 16;
4192           break;
4193         case AK_Memory:
4194           // Don't count fixed arguments in the overflow area - va_start will
4195           // skip right over them.
4196           if (IsFixed)
4197             continue;
4198           uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4199           Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset,
4200                                            alignTo(ArgSize, 8));
4201           OverflowOffset += alignTo(ArgSize, 8);
4202           break;
4203       }
4204       // Count Gp/Vr fixed arguments to their respective offsets, but don't
4205       // bother to actually store a shadow.
4206       if (IsFixed)
4207         continue;
4208       if (!Base)
4209         continue;
4210       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4211     }
4212     Constant *OverflowSize =
4213       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AArch64VAEndOffset);
4214     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
4215   }
4216 
4217   /// Compute the shadow address for a given va_arg.
4218   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4219                                    unsigned ArgOffset, unsigned ArgSize) {
4220     // Make sure we don't overflow __msan_va_arg_tls.
4221     if (ArgOffset + ArgSize > kParamTLSSize)
4222       return nullptr;
4223     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4224     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4225     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4226                               "_msarg");
4227   }
4228 
4229   void visitVAStartInst(VAStartInst &I) override {
4230     IRBuilder<> IRB(&I);
4231     VAStartInstrumentationList.push_back(&I);
4232     Value *VAListTag = I.getArgOperand(0);
4233     Value *ShadowPtr, *OriginPtr;
4234     const Align Alignment = Align(8);
4235     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4236         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4237     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4238                      /* size */ 32, Alignment, false);
4239   }
4240 
4241   void visitVACopyInst(VACopyInst &I) override {
4242     IRBuilder<> IRB(&I);
4243     VAStartInstrumentationList.push_back(&I);
4244     Value *VAListTag = I.getArgOperand(0);
4245     Value *ShadowPtr, *OriginPtr;
4246     const Align Alignment = Align(8);
4247     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4248         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4249     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4250                      /* size */ 32, Alignment, false);
4251   }
4252 
4253   // Retrieve a va_list field of 'void*' size.
4254   Value* getVAField64(IRBuilder<> &IRB, Value *VAListTag, int offset) {
4255     Value *SaveAreaPtrPtr =
4256       IRB.CreateIntToPtr(
4257         IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4258                       ConstantInt::get(MS.IntptrTy, offset)),
4259         Type::getInt64PtrTy(*MS.C));
4260     return IRB.CreateLoad(Type::getInt64Ty(*MS.C), SaveAreaPtrPtr);
4261   }
4262 
4263   // Retrieve a va_list field of 'int' size.
4264   Value* getVAField32(IRBuilder<> &IRB, Value *VAListTag, int offset) {
4265     Value *SaveAreaPtr =
4266       IRB.CreateIntToPtr(
4267         IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4268                       ConstantInt::get(MS.IntptrTy, offset)),
4269         Type::getInt32PtrTy(*MS.C));
4270     Value *SaveArea32 = IRB.CreateLoad(IRB.getInt32Ty(), SaveAreaPtr);
4271     return IRB.CreateSExt(SaveArea32, MS.IntptrTy);
4272   }
4273 
4274   void finalizeInstrumentation() override {
4275     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
4276            "finalizeInstrumentation called twice");
4277     if (!VAStartInstrumentationList.empty()) {
4278       // If there is a va_start in this function, make a backup copy of
4279       // va_arg_tls somewhere in the function entry block.
4280       IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4281       VAArgOverflowSize =
4282           IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4283       Value *CopySize =
4284         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AArch64VAEndOffset),
4285                       VAArgOverflowSize);
4286       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4287       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4288     }
4289 
4290     Value *GrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64GrArgSize);
4291     Value *VrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64VrArgSize);
4292 
4293     // Instrument va_start, copy va_list shadow from the backup copy of
4294     // the TLS contents.
4295     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4296       CallInst *OrigInst = VAStartInstrumentationList[i];
4297       IRBuilder<> IRB(OrigInst->getNextNode());
4298 
4299       Value *VAListTag = OrigInst->getArgOperand(0);
4300 
4301       // The variadic ABI for AArch64 creates two areas to save the incoming
4302       // argument registers (one for 64-bit general register xn-x7 and another
4303       // for 128-bit FP/SIMD vn-v7).
4304       // We need then to propagate the shadow arguments on both regions
4305       // 'va::__gr_top + va::__gr_offs' and 'va::__vr_top + va::__vr_offs'.
4306       // The remaning arguments are saved on shadow for 'va::stack'.
4307       // One caveat is it requires only to propagate the non-named arguments,
4308       // however on the call site instrumentation 'all' the arguments are
4309       // saved. So to copy the shadow values from the va_arg TLS array
4310       // we need to adjust the offset for both GR and VR fields based on
4311       // the __{gr,vr}_offs value (since they are stores based on incoming
4312       // named arguments).
4313 
4314       // Read the stack pointer from the va_list.
4315       Value *StackSaveAreaPtr = getVAField64(IRB, VAListTag, 0);
4316 
4317       // Read both the __gr_top and __gr_off and add them up.
4318       Value *GrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 8);
4319       Value *GrOffSaveArea = getVAField32(IRB, VAListTag, 24);
4320 
4321       Value *GrRegSaveAreaPtr = IRB.CreateAdd(GrTopSaveAreaPtr, GrOffSaveArea);
4322 
4323       // Read both the __vr_top and __vr_off and add them up.
4324       Value *VrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 16);
4325       Value *VrOffSaveArea = getVAField32(IRB, VAListTag, 28);
4326 
4327       Value *VrRegSaveAreaPtr = IRB.CreateAdd(VrTopSaveAreaPtr, VrOffSaveArea);
4328 
4329       // It does not know how many named arguments is being used and, on the
4330       // callsite all the arguments were saved.  Since __gr_off is defined as
4331       // '0 - ((8 - named_gr) * 8)', the idea is to just propagate the variadic
4332       // argument by ignoring the bytes of shadow from named arguments.
4333       Value *GrRegSaveAreaShadowPtrOff =
4334         IRB.CreateAdd(GrArgSize, GrOffSaveArea);
4335 
4336       Value *GrRegSaveAreaShadowPtr =
4337           MSV.getShadowOriginPtr(GrRegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4338                                  Align(8), /*isStore*/ true)
4339               .first;
4340 
4341       Value *GrSrcPtr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4342                                               GrRegSaveAreaShadowPtrOff);
4343       Value *GrCopySize = IRB.CreateSub(GrArgSize, GrRegSaveAreaShadowPtrOff);
4344 
4345       IRB.CreateMemCpy(GrRegSaveAreaShadowPtr, Align(8), GrSrcPtr, Align(8),
4346                        GrCopySize);
4347 
4348       // Again, but for FP/SIMD values.
4349       Value *VrRegSaveAreaShadowPtrOff =
4350           IRB.CreateAdd(VrArgSize, VrOffSaveArea);
4351 
4352       Value *VrRegSaveAreaShadowPtr =
4353           MSV.getShadowOriginPtr(VrRegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4354                                  Align(8), /*isStore*/ true)
4355               .first;
4356 
4357       Value *VrSrcPtr = IRB.CreateInBoundsGEP(
4358         IRB.getInt8Ty(),
4359         IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4360                               IRB.getInt32(AArch64VrBegOffset)),
4361         VrRegSaveAreaShadowPtrOff);
4362       Value *VrCopySize = IRB.CreateSub(VrArgSize, VrRegSaveAreaShadowPtrOff);
4363 
4364       IRB.CreateMemCpy(VrRegSaveAreaShadowPtr, Align(8), VrSrcPtr, Align(8),
4365                        VrCopySize);
4366 
4367       // And finally for remaining arguments.
4368       Value *StackSaveAreaShadowPtr =
4369           MSV.getShadowOriginPtr(StackSaveAreaPtr, IRB, IRB.getInt8Ty(),
4370                                  Align(16), /*isStore*/ true)
4371               .first;
4372 
4373       Value *StackSrcPtr =
4374         IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4375                               IRB.getInt32(AArch64VAEndOffset));
4376 
4377       IRB.CreateMemCpy(StackSaveAreaShadowPtr, Align(16), StackSrcPtr,
4378                        Align(16), VAArgOverflowSize);
4379     }
4380   }
4381 };
4382 
4383 /// PowerPC64-specific implementation of VarArgHelper.
4384 struct VarArgPowerPC64Helper : public VarArgHelper {
4385   Function &F;
4386   MemorySanitizer &MS;
4387   MemorySanitizerVisitor &MSV;
4388   Value *VAArgTLSCopy = nullptr;
4389   Value *VAArgSize = nullptr;
4390 
4391   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4392 
4393   VarArgPowerPC64Helper(Function &F, MemorySanitizer &MS,
4394                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4395 
4396   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
4397     // For PowerPC, we need to deal with alignment of stack arguments -
4398     // they are mostly aligned to 8 bytes, but vectors and i128 arrays
4399     // are aligned to 16 bytes, byvals can be aligned to 8 or 16 bytes,
4400     // and QPX vectors are aligned to 32 bytes.  For that reason, we
4401     // compute current offset from stack pointer (which is always properly
4402     // aligned), and offset for the first vararg, then subtract them.
4403     unsigned VAArgBase;
4404     Triple TargetTriple(F.getParent()->getTargetTriple());
4405     // Parameter save area starts at 48 bytes from frame pointer for ABIv1,
4406     // and 32 bytes for ABIv2.  This is usually determined by target
4407     // endianness, but in theory could be overriden by function attribute.
4408     // For simplicity, we ignore it here (it'd only matter for QPX vectors).
4409     if (TargetTriple.getArch() == Triple::ppc64)
4410       VAArgBase = 48;
4411     else
4412       VAArgBase = 32;
4413     unsigned VAArgOffset = VAArgBase;
4414     const DataLayout &DL = F.getParent()->getDataLayout();
4415     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
4416          ArgIt != End; ++ArgIt) {
4417       Value *A = *ArgIt;
4418       unsigned ArgNo = CS.getArgumentNo(ArgIt);
4419       bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
4420       bool IsByVal = CS.paramHasAttr(ArgNo, Attribute::ByVal);
4421       if (IsByVal) {
4422         assert(A->getType()->isPointerTy());
4423         Type *RealTy = A->getType()->getPointerElementType();
4424         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
4425         uint64_t ArgAlign = CS.getParamAlignment(ArgNo);
4426         if (ArgAlign < 8)
4427           ArgAlign = 8;
4428         VAArgOffset = alignTo(VAArgOffset, ArgAlign);
4429         if (!IsFixed) {
4430           Value *Base = getShadowPtrForVAArgument(
4431               RealTy, IRB, VAArgOffset - VAArgBase, ArgSize);
4432           if (Base) {
4433             Value *AShadowPtr, *AOriginPtr;
4434             std::tie(AShadowPtr, AOriginPtr) =
4435                 MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(),
4436                                        kShadowTLSAlignment, /*isStore*/ false);
4437 
4438             IRB.CreateMemCpy(Base, kShadowTLSAlignment, AShadowPtr,
4439                              kShadowTLSAlignment, ArgSize);
4440           }
4441         }
4442         VAArgOffset += alignTo(ArgSize, 8);
4443       } else {
4444         Value *Base;
4445         uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4446         uint64_t ArgAlign = 8;
4447         if (A->getType()->isArrayTy()) {
4448           // Arrays are aligned to element size, except for long double
4449           // arrays, which are aligned to 8 bytes.
4450           Type *ElementTy = A->getType()->getArrayElementType();
4451           if (!ElementTy->isPPC_FP128Ty())
4452             ArgAlign = DL.getTypeAllocSize(ElementTy);
4453         } else if (A->getType()->isVectorTy()) {
4454           // Vectors are naturally aligned.
4455           ArgAlign = DL.getTypeAllocSize(A->getType());
4456         }
4457         if (ArgAlign < 8)
4458           ArgAlign = 8;
4459         VAArgOffset = alignTo(VAArgOffset, ArgAlign);
4460         if (DL.isBigEndian()) {
4461           // Adjusting the shadow for argument with size < 8 to match the placement
4462           // of bits in big endian system
4463           if (ArgSize < 8)
4464             VAArgOffset += (8 - ArgSize);
4465         }
4466         if (!IsFixed) {
4467           Base = getShadowPtrForVAArgument(A->getType(), IRB,
4468                                            VAArgOffset - VAArgBase, ArgSize);
4469           if (Base)
4470             IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4471         }
4472         VAArgOffset += ArgSize;
4473         VAArgOffset = alignTo(VAArgOffset, 8);
4474       }
4475       if (IsFixed)
4476         VAArgBase = VAArgOffset;
4477     }
4478 
4479     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(),
4480                                                 VAArgOffset - VAArgBase);
4481     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
4482     // a new class member i.e. it is the total size of all VarArgs.
4483     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
4484   }
4485 
4486   /// Compute the shadow address for a given va_arg.
4487   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4488                                    unsigned ArgOffset, unsigned ArgSize) {
4489     // Make sure we don't overflow __msan_va_arg_tls.
4490     if (ArgOffset + ArgSize > kParamTLSSize)
4491       return nullptr;
4492     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4493     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4494     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4495                               "_msarg");
4496   }
4497 
4498   void visitVAStartInst(VAStartInst &I) override {
4499     IRBuilder<> IRB(&I);
4500     VAStartInstrumentationList.push_back(&I);
4501     Value *VAListTag = I.getArgOperand(0);
4502     Value *ShadowPtr, *OriginPtr;
4503     const Align Alignment = Align(8);
4504     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4505         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4506     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4507                      /* size */ 8, Alignment, false);
4508   }
4509 
4510   void visitVACopyInst(VACopyInst &I) override {
4511     IRBuilder<> IRB(&I);
4512     Value *VAListTag = I.getArgOperand(0);
4513     Value *ShadowPtr, *OriginPtr;
4514     const Align Alignment = Align(8);
4515     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4516         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4517     // Unpoison the whole __va_list_tag.
4518     // FIXME: magic ABI constants.
4519     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4520                      /* size */ 8, Alignment, false);
4521   }
4522 
4523   void finalizeInstrumentation() override {
4524     assert(!VAArgSize && !VAArgTLSCopy &&
4525            "finalizeInstrumentation called twice");
4526     IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4527     VAArgSize = IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4528     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
4529                                     VAArgSize);
4530 
4531     if (!VAStartInstrumentationList.empty()) {
4532       // If there is a va_start in this function, make a backup copy of
4533       // va_arg_tls somewhere in the function entry block.
4534       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4535       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4536     }
4537 
4538     // Instrument va_start.
4539     // Copy va_list shadow from the backup copy of the TLS contents.
4540     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4541       CallInst *OrigInst = VAStartInstrumentationList[i];
4542       IRBuilder<> IRB(OrigInst->getNextNode());
4543       Value *VAListTag = OrigInst->getArgOperand(0);
4544       Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4545       Value *RegSaveAreaPtrPtr =
4546           IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4547                              PointerType::get(RegSaveAreaPtrTy, 0));
4548       Value *RegSaveAreaPtr =
4549           IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr);
4550       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
4551       const Align Alignment = Align(8);
4552       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
4553           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4554                                  Alignment, /*isStore*/ true);
4555       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
4556                        CopySize);
4557     }
4558   }
4559 };
4560 
4561 /// A no-op implementation of VarArgHelper.
4562 struct VarArgNoOpHelper : public VarArgHelper {
4563   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
4564                    MemorySanitizerVisitor &MSV) {}
4565 
4566   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
4567 
4568   void visitVAStartInst(VAStartInst &I) override {}
4569 
4570   void visitVACopyInst(VACopyInst &I) override {}
4571 
4572   void finalizeInstrumentation() override {}
4573 };
4574 
4575 } // end anonymous namespace
4576 
4577 static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
4578                                         MemorySanitizerVisitor &Visitor) {
4579   // VarArg handling is only implemented on AMD64. False positives are possible
4580   // on other platforms.
4581   Triple TargetTriple(Func.getParent()->getTargetTriple());
4582   if (TargetTriple.getArch() == Triple::x86_64)
4583     return new VarArgAMD64Helper(Func, Msan, Visitor);
4584   else if (TargetTriple.isMIPS64())
4585     return new VarArgMIPS64Helper(Func, Msan, Visitor);
4586   else if (TargetTriple.getArch() == Triple::aarch64)
4587     return new VarArgAArch64Helper(Func, Msan, Visitor);
4588   else if (TargetTriple.getArch() == Triple::ppc64 ||
4589            TargetTriple.getArch() == Triple::ppc64le)
4590     return new VarArgPowerPC64Helper(Func, Msan, Visitor);
4591   else
4592     return new VarArgNoOpHelper(Func, Msan, Visitor);
4593 }
4594 
4595 bool MemorySanitizer::sanitizeFunction(Function &F, TargetLibraryInfo &TLI) {
4596   if (!CompileKernel && F.getName() == kMsanModuleCtorName)
4597     return false;
4598 
4599   MemorySanitizerVisitor Visitor(F, *this, TLI);
4600 
4601   // Clear out readonly/readnone attributes.
4602   AttrBuilder B;
4603   B.addAttribute(Attribute::ReadOnly)
4604       .addAttribute(Attribute::ReadNone)
4605       .addAttribute(Attribute::WriteOnly)
4606       .addAttribute(Attribute::ArgMemOnly)
4607       .addAttribute(Attribute::Speculatable);
4608   F.removeAttributes(AttributeList::FunctionIndex, B);
4609 
4610   return Visitor.runOnFunction();
4611 }
4612