1 //===- MemorySanitizer.cpp - detector of uninitialized reads --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This file is a part of MemorySanitizer, a detector of uninitialized
11 /// reads.
12 ///
13 /// The algorithm of the tool is similar to Memcheck
14 /// (http://goo.gl/QKbem). We associate a few shadow bits with every
15 /// byte of the application memory, poison the shadow of the malloc-ed
16 /// or alloca-ed memory, load the shadow bits on every memory read,
17 /// propagate the shadow bits through some of the arithmetic
18 /// instruction (including MOV), store the shadow bits on every memory
19 /// write, report a bug on some other instructions (e.g. JMP) if the
20 /// associated shadow is poisoned.
21 ///
22 /// But there are differences too. The first and the major one:
23 /// compiler instrumentation instead of binary instrumentation. This
24 /// gives us much better register allocation, possible compiler
25 /// optimizations and a fast start-up. But this brings the major issue
26 /// as well: msan needs to see all program events, including system
27 /// calls and reads/writes in system libraries, so we either need to
28 /// compile *everything* with msan or use a binary translation
29 /// component (e.g. DynamoRIO) to instrument pre-built libraries.
30 /// Another difference from Memcheck is that we use 8 shadow bits per
31 /// byte of application memory and use a direct shadow mapping. This
32 /// greatly simplifies the instrumentation code and avoids races on
33 /// shadow updates (Memcheck is single-threaded so races are not a
34 /// concern there. Memcheck uses 2 shadow bits per byte with a slow
35 /// path storage that uses 8 bits per byte).
36 ///
37 /// The default value of shadow is 0, which means "clean" (not poisoned).
38 ///
39 /// Every module initializer should call __msan_init to ensure that the
40 /// shadow memory is ready. On error, __msan_warning is called. Since
41 /// parameters and return values may be passed via registers, we have a
42 /// specialized thread-local shadow for return values
43 /// (__msan_retval_tls) and parameters (__msan_param_tls).
44 ///
45 ///                           Origin tracking.
46 ///
47 /// MemorySanitizer can track origins (allocation points) of all uninitialized
48 /// values. This behavior is controlled with a flag (msan-track-origins) and is
49 /// disabled by default.
50 ///
51 /// Origins are 4-byte values created and interpreted by the runtime library.
52 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
53 /// of application memory. Propagation of origins is basically a bunch of
54 /// "select" instructions that pick the origin of a dirty argument, if an
55 /// instruction has one.
56 ///
57 /// Every 4 aligned, consecutive bytes of application memory have one origin
58 /// value associated with them. If these bytes contain uninitialized data
59 /// coming from 2 different allocations, the last store wins. Because of this,
60 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
61 /// practice.
62 ///
63 /// Origins are meaningless for fully initialized values, so MemorySanitizer
64 /// avoids storing origin to memory when a fully initialized value is stored.
65 /// This way it avoids needless overwriting origin of the 4-byte region on
66 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
67 ///
68 ///                            Atomic handling.
69 ///
70 /// Ideally, every atomic store of application value should update the
71 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
72 /// of two disjoint locations can not be done without severe slowdown.
73 ///
74 /// Therefore, we implement an approximation that may err on the safe side.
75 /// In this implementation, every atomically accessed location in the program
76 /// may only change from (partially) uninitialized to fully initialized, but
77 /// not the other way around. We load the shadow _after_ the application load,
78 /// and we store the shadow _before_ the app store. Also, we always store clean
79 /// shadow (if the application store is atomic). This way, if the store-load
80 /// pair constitutes a happens-before arc, shadow store and load are correctly
81 /// ordered such that the load will get either the value that was stored, or
82 /// some later value (which is always clean).
83 ///
84 /// This does not work very well with Compare-And-Swap (CAS) and
85 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
86 /// must store the new shadow before the app operation, and load the shadow
87 /// after the app operation. Computers don't work this way. Current
88 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
89 /// value. It implements the store part as a simple atomic store by storing a
90 /// clean shadow.
91 ///
92 ///                      Instrumenting inline assembly.
93 ///
94 /// For inline assembly code LLVM has little idea about which memory locations
95 /// become initialized depending on the arguments. It can be possible to figure
96 /// out which arguments are meant to point to inputs and outputs, but the
97 /// actual semantics can be only visible at runtime. In the Linux kernel it's
98 /// also possible that the arguments only indicate the offset for a base taken
99 /// from a segment register, so it's dangerous to treat any asm() arguments as
100 /// pointers. We take a conservative approach generating calls to
101 ///   __msan_instrument_asm_store(ptr, size)
102 /// , which defer the memory unpoisoning to the runtime library.
103 /// The latter can perform more complex address checks to figure out whether
104 /// it's safe to touch the shadow memory.
105 /// Like with atomic operations, we call __msan_instrument_asm_store() before
106 /// the assembly call, so that changes to the shadow memory will be seen by
107 /// other threads together with main memory initialization.
108 ///
109 ///                  KernelMemorySanitizer (KMSAN) implementation.
110 ///
111 /// The major differences between KMSAN and MSan instrumentation are:
112 ///  - KMSAN always tracks the origins and implies msan-keep-going=true;
113 ///  - KMSAN allocates shadow and origin memory for each page separately, so
114 ///    there are no explicit accesses to shadow and origin in the
115 ///    instrumentation.
116 ///    Shadow and origin values for a particular X-byte memory location
117 ///    (X=1,2,4,8) are accessed through pointers obtained via the
118 ///      __msan_metadata_ptr_for_load_X(ptr)
119 ///      __msan_metadata_ptr_for_store_X(ptr)
120 ///    functions. The corresponding functions check that the X-byte accesses
121 ///    are possible and returns the pointers to shadow and origin memory.
122 ///    Arbitrary sized accesses are handled with:
123 ///      __msan_metadata_ptr_for_load_n(ptr, size)
124 ///      __msan_metadata_ptr_for_store_n(ptr, size);
125 ///  - TLS variables are stored in a single per-task struct. A call to a
126 ///    function __msan_get_context_state() returning a pointer to that struct
127 ///    is inserted into every instrumented function before the entry block;
128 ///  - __msan_warning() takes a 32-bit origin parameter;
129 ///  - local variables are poisoned with __msan_poison_alloca() upon function
130 ///    entry and unpoisoned with __msan_unpoison_alloca() before leaving the
131 ///    function;
132 ///  - the pass doesn't declare any global variables or add global constructors
133 ///    to the translation unit.
134 ///
135 /// Also, KMSAN currently ignores uninitialized memory passed into inline asm
136 /// calls, making sure we're on the safe side wrt. possible false positives.
137 ///
138 ///  KernelMemorySanitizer only supports X86_64 at the moment.
139 ///
140 //===----------------------------------------------------------------------===//
141 
142 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
143 #include "llvm/ADT/APInt.h"
144 #include "llvm/ADT/ArrayRef.h"
145 #include "llvm/ADT/DepthFirstIterator.h"
146 #include "llvm/ADT/SmallSet.h"
147 #include "llvm/ADT/SmallString.h"
148 #include "llvm/ADT/SmallVector.h"
149 #include "llvm/ADT/StringExtras.h"
150 #include "llvm/ADT/StringRef.h"
151 #include "llvm/ADT/Triple.h"
152 #include "llvm/Analysis/TargetLibraryInfo.h"
153 #include "llvm/IR/Argument.h"
154 #include "llvm/IR/Attributes.h"
155 #include "llvm/IR/BasicBlock.h"
156 #include "llvm/IR/CallSite.h"
157 #include "llvm/IR/CallingConv.h"
158 #include "llvm/IR/Constant.h"
159 #include "llvm/IR/Constants.h"
160 #include "llvm/IR/DataLayout.h"
161 #include "llvm/IR/DerivedTypes.h"
162 #include "llvm/IR/Function.h"
163 #include "llvm/IR/GlobalValue.h"
164 #include "llvm/IR/GlobalVariable.h"
165 #include "llvm/IR/IRBuilder.h"
166 #include "llvm/IR/InlineAsm.h"
167 #include "llvm/IR/InstVisitor.h"
168 #include "llvm/IR/InstrTypes.h"
169 #include "llvm/IR/Instruction.h"
170 #include "llvm/IR/Instructions.h"
171 #include "llvm/IR/IntrinsicInst.h"
172 #include "llvm/IR/Intrinsics.h"
173 #include "llvm/IR/IntrinsicsX86.h"
174 #include "llvm/IR/LLVMContext.h"
175 #include "llvm/IR/MDBuilder.h"
176 #include "llvm/IR/Module.h"
177 #include "llvm/IR/Type.h"
178 #include "llvm/IR/Value.h"
179 #include "llvm/IR/ValueMap.h"
180 #include "llvm/InitializePasses.h"
181 #include "llvm/Pass.h"
182 #include "llvm/Support/AtomicOrdering.h"
183 #include "llvm/Support/Casting.h"
184 #include "llvm/Support/CommandLine.h"
185 #include "llvm/Support/Compiler.h"
186 #include "llvm/Support/Debug.h"
187 #include "llvm/Support/ErrorHandling.h"
188 #include "llvm/Support/MathExtras.h"
189 #include "llvm/Support/raw_ostream.h"
190 #include "llvm/Transforms/Instrumentation.h"
191 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
192 #include "llvm/Transforms/Utils/Local.h"
193 #include "llvm/Transforms/Utils/ModuleUtils.h"
194 #include <algorithm>
195 #include <cassert>
196 #include <cstddef>
197 #include <cstdint>
198 #include <memory>
199 #include <string>
200 #include <tuple>
201 
202 using namespace llvm;
203 
204 #define DEBUG_TYPE "msan"
205 
206 static const unsigned kOriginSize = 4;
207 static const Align kMinOriginAlignment = Align(4);
208 static const Align kShadowTLSAlignment = Align(8);
209 
210 // These constants must be kept in sync with the ones in msan.h.
211 static const unsigned kParamTLSSize = 800;
212 static const unsigned kRetvalTLSSize = 800;
213 
214 // Accesses sizes are powers of two: 1, 2, 4, 8.
215 static const size_t kNumberOfAccessSizes = 4;
216 
217 /// Track origins of uninitialized values.
218 ///
219 /// Adds a section to MemorySanitizer report that points to the allocation
220 /// (stack or heap) the uninitialized bits came from originally.
221 static cl::opt<int> ClTrackOrigins("msan-track-origins",
222        cl::desc("Track origins (allocation sites) of poisoned memory"),
223        cl::Hidden, cl::init(0));
224 
225 static cl::opt<bool> ClKeepGoing("msan-keep-going",
226        cl::desc("keep going after reporting a UMR"),
227        cl::Hidden, cl::init(false));
228 
229 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
230        cl::desc("poison uninitialized stack variables"),
231        cl::Hidden, cl::init(true));
232 
233 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
234        cl::desc("poison uninitialized stack variables with a call"),
235        cl::Hidden, cl::init(false));
236 
237 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
238        cl::desc("poison uninitialized stack variables with the given pattern"),
239        cl::Hidden, cl::init(0xff));
240 
241 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
242        cl::desc("poison undef temps"),
243        cl::Hidden, cl::init(true));
244 
245 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
246        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
247        cl::Hidden, cl::init(true));
248 
249 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
250        cl::desc("exact handling of relational integer ICmp"),
251        cl::Hidden, cl::init(false));
252 
253 static cl::opt<bool> ClHandleLifetimeIntrinsics(
254     "msan-handle-lifetime-intrinsics",
255     cl::desc(
256         "when possible, poison scoped variables at the beginning of the scope "
257         "(slower, but more precise)"),
258     cl::Hidden, cl::init(true));
259 
260 // When compiling the Linux kernel, we sometimes see false positives related to
261 // MSan being unable to understand that inline assembly calls may initialize
262 // local variables.
263 // This flag makes the compiler conservatively unpoison every memory location
264 // passed into an assembly call. Note that this may cause false positives.
265 // Because it's impossible to figure out the array sizes, we can only unpoison
266 // the first sizeof(type) bytes for each type* pointer.
267 // The instrumentation is only enabled in KMSAN builds, and only if
268 // -msan-handle-asm-conservative is on. This is done because we may want to
269 // quickly disable assembly instrumentation when it breaks.
270 static cl::opt<bool> ClHandleAsmConservative(
271     "msan-handle-asm-conservative",
272     cl::desc("conservative handling of inline assembly"), cl::Hidden,
273     cl::init(true));
274 
275 // This flag controls whether we check the shadow of the address
276 // operand of load or store. Such bugs are very rare, since load from
277 // a garbage address typically results in SEGV, but still happen
278 // (e.g. only lower bits of address are garbage, or the access happens
279 // early at program startup where malloc-ed memory is more likely to
280 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
281 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
282        cl::desc("report accesses through a pointer which has poisoned shadow"),
283        cl::Hidden, cl::init(true));
284 
285 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
286        cl::desc("print out instructions with default strict semantics"),
287        cl::Hidden, cl::init(false));
288 
289 static cl::opt<int> ClInstrumentationWithCallThreshold(
290     "msan-instrumentation-with-call-threshold",
291     cl::desc(
292         "If the function being instrumented requires more than "
293         "this number of checks and origin stores, use callbacks instead of "
294         "inline checks (-1 means never use callbacks)."),
295     cl::Hidden, cl::init(3500));
296 
297 static cl::opt<bool>
298     ClEnableKmsan("msan-kernel",
299                   cl::desc("Enable KernelMemorySanitizer instrumentation"),
300                   cl::Hidden, cl::init(false));
301 
302 // This is an experiment to enable handling of cases where shadow is a non-zero
303 // compile-time constant. For some unexplainable reason they were silently
304 // ignored in the instrumentation.
305 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
306        cl::desc("Insert checks for constant shadow values"),
307        cl::Hidden, cl::init(false));
308 
309 // This is off by default because of a bug in gold:
310 // https://sourceware.org/bugzilla/show_bug.cgi?id=19002
311 static cl::opt<bool> ClWithComdat("msan-with-comdat",
312        cl::desc("Place MSan constructors in comdat sections"),
313        cl::Hidden, cl::init(false));
314 
315 // These options allow to specify custom memory map parameters
316 // See MemoryMapParams for details.
317 static cl::opt<uint64_t> ClAndMask("msan-and-mask",
318                                    cl::desc("Define custom MSan AndMask"),
319                                    cl::Hidden, cl::init(0));
320 
321 static cl::opt<uint64_t> ClXorMask("msan-xor-mask",
322                                    cl::desc("Define custom MSan XorMask"),
323                                    cl::Hidden, cl::init(0));
324 
325 static cl::opt<uint64_t> ClShadowBase("msan-shadow-base",
326                                       cl::desc("Define custom MSan ShadowBase"),
327                                       cl::Hidden, cl::init(0));
328 
329 static cl::opt<uint64_t> ClOriginBase("msan-origin-base",
330                                       cl::desc("Define custom MSan OriginBase"),
331                                       cl::Hidden, cl::init(0));
332 
333 static const char *const kMsanModuleCtorName = "msan.module_ctor";
334 static const char *const kMsanInitName = "__msan_init";
335 
336 namespace {
337 
338 // Memory map parameters used in application-to-shadow address calculation.
339 // Offset = (Addr & ~AndMask) ^ XorMask
340 // Shadow = ShadowBase + Offset
341 // Origin = OriginBase + Offset
342 struct MemoryMapParams {
343   uint64_t AndMask;
344   uint64_t XorMask;
345   uint64_t ShadowBase;
346   uint64_t OriginBase;
347 };
348 
349 struct PlatformMemoryMapParams {
350   const MemoryMapParams *bits32;
351   const MemoryMapParams *bits64;
352 };
353 
354 } // end anonymous namespace
355 
356 // i386 Linux
357 static const MemoryMapParams Linux_I386_MemoryMapParams = {
358   0x000080000000,  // AndMask
359   0,               // XorMask (not used)
360   0,               // ShadowBase (not used)
361   0x000040000000,  // OriginBase
362 };
363 
364 // x86_64 Linux
365 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
366 #ifdef MSAN_LINUX_X86_64_OLD_MAPPING
367   0x400000000000,  // AndMask
368   0,               // XorMask (not used)
369   0,               // ShadowBase (not used)
370   0x200000000000,  // OriginBase
371 #else
372   0,               // AndMask (not used)
373   0x500000000000,  // XorMask
374   0,               // ShadowBase (not used)
375   0x100000000000,  // OriginBase
376 #endif
377 };
378 
379 // mips64 Linux
380 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
381   0,               // AndMask (not used)
382   0x008000000000,  // XorMask
383   0,               // ShadowBase (not used)
384   0x002000000000,  // OriginBase
385 };
386 
387 // ppc64 Linux
388 static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
389   0xE00000000000,  // AndMask
390   0x100000000000,  // XorMask
391   0x080000000000,  // ShadowBase
392   0x1C0000000000,  // OriginBase
393 };
394 
395 // aarch64 Linux
396 static const MemoryMapParams Linux_AArch64_MemoryMapParams = {
397   0,               // AndMask (not used)
398   0x06000000000,   // XorMask
399   0,               // ShadowBase (not used)
400   0x01000000000,   // OriginBase
401 };
402 
403 // i386 FreeBSD
404 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
405   0x000180000000,  // AndMask
406   0x000040000000,  // XorMask
407   0x000020000000,  // ShadowBase
408   0x000700000000,  // OriginBase
409 };
410 
411 // x86_64 FreeBSD
412 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
413   0xc00000000000,  // AndMask
414   0x200000000000,  // XorMask
415   0x100000000000,  // ShadowBase
416   0x380000000000,  // OriginBase
417 };
418 
419 // x86_64 NetBSD
420 static const MemoryMapParams NetBSD_X86_64_MemoryMapParams = {
421   0,               // AndMask
422   0x500000000000,  // XorMask
423   0,               // ShadowBase
424   0x100000000000,  // OriginBase
425 };
426 
427 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
428   &Linux_I386_MemoryMapParams,
429   &Linux_X86_64_MemoryMapParams,
430 };
431 
432 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
433   nullptr,
434   &Linux_MIPS64_MemoryMapParams,
435 };
436 
437 static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
438   nullptr,
439   &Linux_PowerPC64_MemoryMapParams,
440 };
441 
442 static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = {
443   nullptr,
444   &Linux_AArch64_MemoryMapParams,
445 };
446 
447 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
448   &FreeBSD_I386_MemoryMapParams,
449   &FreeBSD_X86_64_MemoryMapParams,
450 };
451 
452 static const PlatformMemoryMapParams NetBSD_X86_MemoryMapParams = {
453   nullptr,
454   &NetBSD_X86_64_MemoryMapParams,
455 };
456 
457 namespace {
458 
459 /// Instrument functions of a module to detect uninitialized reads.
460 ///
461 /// Instantiating MemorySanitizer inserts the msan runtime library API function
462 /// declarations into the module if they don't exist already. Instantiating
463 /// ensures the __msan_init function is in the list of global constructors for
464 /// the module.
465 class MemorySanitizer {
466 public:
467   MemorySanitizer(Module &M, MemorySanitizerOptions Options)
468       : CompileKernel(Options.Kernel), TrackOrigins(Options.TrackOrigins),
469         Recover(Options.Recover) {
470     initializeModule(M);
471   }
472 
473   // MSan cannot be moved or copied because of MapParams.
474   MemorySanitizer(MemorySanitizer &&) = delete;
475   MemorySanitizer &operator=(MemorySanitizer &&) = delete;
476   MemorySanitizer(const MemorySanitizer &) = delete;
477   MemorySanitizer &operator=(const MemorySanitizer &) = delete;
478 
479   bool sanitizeFunction(Function &F, TargetLibraryInfo &TLI);
480 
481 private:
482   friend struct MemorySanitizerVisitor;
483   friend struct VarArgAMD64Helper;
484   friend struct VarArgMIPS64Helper;
485   friend struct VarArgAArch64Helper;
486   friend struct VarArgPowerPC64Helper;
487 
488   void initializeModule(Module &M);
489   void initializeCallbacks(Module &M);
490   void createKernelApi(Module &M);
491   void createUserspaceApi(Module &M);
492 
493   /// True if we're compiling the Linux kernel.
494   bool CompileKernel;
495   /// Track origins (allocation points) of uninitialized values.
496   int TrackOrigins;
497   bool Recover;
498 
499   LLVMContext *C;
500   Type *IntptrTy;
501   Type *OriginTy;
502 
503   // XxxTLS variables represent the per-thread state in MSan and per-task state
504   // in KMSAN.
505   // For the userspace these point to thread-local globals. In the kernel land
506   // they point to the members of a per-task struct obtained via a call to
507   // __msan_get_context_state().
508 
509   /// Thread-local shadow storage for function parameters.
510   Value *ParamTLS;
511 
512   /// Thread-local origin storage for function parameters.
513   Value *ParamOriginTLS;
514 
515   /// Thread-local shadow storage for function return value.
516   Value *RetvalTLS;
517 
518   /// Thread-local origin storage for function return value.
519   Value *RetvalOriginTLS;
520 
521   /// Thread-local shadow storage for in-register va_arg function
522   /// parameters (x86_64-specific).
523   Value *VAArgTLS;
524 
525   /// Thread-local shadow storage for in-register va_arg function
526   /// parameters (x86_64-specific).
527   Value *VAArgOriginTLS;
528 
529   /// Thread-local shadow storage for va_arg overflow area
530   /// (x86_64-specific).
531   Value *VAArgOverflowSizeTLS;
532 
533   /// Thread-local space used to pass origin value to the UMR reporting
534   /// function.
535   Value *OriginTLS;
536 
537   /// Are the instrumentation callbacks set up?
538   bool CallbacksInitialized = false;
539 
540   /// The run-time callback to print a warning.
541   FunctionCallee WarningFn;
542 
543   // These arrays are indexed by log2(AccessSize).
544   FunctionCallee MaybeWarningFn[kNumberOfAccessSizes];
545   FunctionCallee MaybeStoreOriginFn[kNumberOfAccessSizes];
546 
547   /// Run-time helper that generates a new origin value for a stack
548   /// allocation.
549   FunctionCallee MsanSetAllocaOrigin4Fn;
550 
551   /// Run-time helper that poisons stack on function entry.
552   FunctionCallee MsanPoisonStackFn;
553 
554   /// Run-time helper that records a store (or any event) of an
555   /// uninitialized value and returns an updated origin id encoding this info.
556   FunctionCallee MsanChainOriginFn;
557 
558   /// MSan runtime replacements for memmove, memcpy and memset.
559   FunctionCallee MemmoveFn, MemcpyFn, MemsetFn;
560 
561   /// KMSAN callback for task-local function argument shadow.
562   StructType *MsanContextStateTy;
563   FunctionCallee MsanGetContextStateFn;
564 
565   /// Functions for poisoning/unpoisoning local variables
566   FunctionCallee MsanPoisonAllocaFn, MsanUnpoisonAllocaFn;
567 
568   /// Each of the MsanMetadataPtrXxx functions returns a pair of shadow/origin
569   /// pointers.
570   FunctionCallee MsanMetadataPtrForLoadN, MsanMetadataPtrForStoreN;
571   FunctionCallee MsanMetadataPtrForLoad_1_8[4];
572   FunctionCallee MsanMetadataPtrForStore_1_8[4];
573   FunctionCallee MsanInstrumentAsmStoreFn;
574 
575   /// Helper to choose between different MsanMetadataPtrXxx().
576   FunctionCallee getKmsanShadowOriginAccessFn(bool isStore, int size);
577 
578   /// Memory map parameters used in application-to-shadow calculation.
579   const MemoryMapParams *MapParams;
580 
581   /// Custom memory map parameters used when -msan-shadow-base or
582   // -msan-origin-base is provided.
583   MemoryMapParams CustomMapParams;
584 
585   MDNode *ColdCallWeights;
586 
587   /// Branch weights for origin store.
588   MDNode *OriginStoreWeights;
589 
590   /// An empty volatile inline asm that prevents callback merge.
591   InlineAsm *EmptyAsm;
592 };
593 
594 void insertModuleCtor(Module &M) {
595   getOrCreateSanitizerCtorAndInitFunctions(
596       M, kMsanModuleCtorName, kMsanInitName,
597       /*InitArgTypes=*/{},
598       /*InitArgs=*/{},
599       // This callback is invoked when the functions are created the first
600       // time. Hook them into the global ctors list in that case:
601       [&](Function *Ctor, FunctionCallee) {
602         if (!ClWithComdat) {
603           appendToGlobalCtors(M, Ctor, 0);
604           return;
605         }
606         Comdat *MsanCtorComdat = M.getOrInsertComdat(kMsanModuleCtorName);
607         Ctor->setComdat(MsanCtorComdat);
608         appendToGlobalCtors(M, Ctor, 0, Ctor);
609       });
610 }
611 
612 /// A legacy function pass for msan instrumentation.
613 ///
614 /// Instruments functions to detect uninitialized reads.
615 struct MemorySanitizerLegacyPass : public FunctionPass {
616   // Pass identification, replacement for typeid.
617   static char ID;
618 
619   MemorySanitizerLegacyPass(MemorySanitizerOptions Options = {})
620       : FunctionPass(ID), Options(Options) {}
621   StringRef getPassName() const override { return "MemorySanitizerLegacyPass"; }
622 
623   void getAnalysisUsage(AnalysisUsage &AU) const override {
624     AU.addRequired<TargetLibraryInfoWrapperPass>();
625   }
626 
627   bool runOnFunction(Function &F) override {
628     return MSan->sanitizeFunction(
629         F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F));
630   }
631   bool doInitialization(Module &M) override;
632 
633   Optional<MemorySanitizer> MSan;
634   MemorySanitizerOptions Options;
635 };
636 
637 template <class T> T getOptOrDefault(const cl::opt<T> &Opt, T Default) {
638   return (Opt.getNumOccurrences() > 0) ? Opt : Default;
639 }
640 
641 } // end anonymous namespace
642 
643 MemorySanitizerOptions::MemorySanitizerOptions(int TO, bool R, bool K)
644     : Kernel(getOptOrDefault(ClEnableKmsan, K)),
645       TrackOrigins(getOptOrDefault(ClTrackOrigins, Kernel ? 2 : TO)),
646       Recover(getOptOrDefault(ClKeepGoing, Kernel || R)) {}
647 
648 PreservedAnalyses MemorySanitizerPass::run(Function &F,
649                                            FunctionAnalysisManager &FAM) {
650   MemorySanitizer Msan(*F.getParent(), Options);
651   if (Msan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F)))
652     return PreservedAnalyses::none();
653   return PreservedAnalyses::all();
654 }
655 
656 PreservedAnalyses MemorySanitizerPass::run(Module &M,
657                                            ModuleAnalysisManager &AM) {
658   if (Options.Kernel)
659     return PreservedAnalyses::all();
660   insertModuleCtor(M);
661   return PreservedAnalyses::none();
662 }
663 
664 char MemorySanitizerLegacyPass::ID = 0;
665 
666 INITIALIZE_PASS_BEGIN(MemorySanitizerLegacyPass, "msan",
667                       "MemorySanitizer: detects uninitialized reads.", false,
668                       false)
669 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
670 INITIALIZE_PASS_END(MemorySanitizerLegacyPass, "msan",
671                     "MemorySanitizer: detects uninitialized reads.", false,
672                     false)
673 
674 FunctionPass *
675 llvm::createMemorySanitizerLegacyPassPass(MemorySanitizerOptions Options) {
676   return new MemorySanitizerLegacyPass(Options);
677 }
678 
679 /// Create a non-const global initialized with the given string.
680 ///
681 /// Creates a writable global for Str so that we can pass it to the
682 /// run-time lib. Runtime uses first 4 bytes of the string to store the
683 /// frame ID, so the string needs to be mutable.
684 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
685                                                             StringRef Str) {
686   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
687   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
688                             GlobalValue::PrivateLinkage, StrConst, "");
689 }
690 
691 /// Create KMSAN API callbacks.
692 void MemorySanitizer::createKernelApi(Module &M) {
693   IRBuilder<> IRB(*C);
694 
695   // These will be initialized in insertKmsanPrologue().
696   RetvalTLS = nullptr;
697   RetvalOriginTLS = nullptr;
698   ParamTLS = nullptr;
699   ParamOriginTLS = nullptr;
700   VAArgTLS = nullptr;
701   VAArgOriginTLS = nullptr;
702   VAArgOverflowSizeTLS = nullptr;
703   // OriginTLS is unused in the kernel.
704   OriginTLS = nullptr;
705 
706   // __msan_warning() in the kernel takes an origin.
707   WarningFn = M.getOrInsertFunction("__msan_warning", IRB.getVoidTy(),
708                                     IRB.getInt32Ty());
709   // Requests the per-task context state (kmsan_context_state*) from the
710   // runtime library.
711   MsanContextStateTy = StructType::get(
712       ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8),
713       ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8),
714       ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8),
715       ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), /* va_arg_origin */
716       IRB.getInt64Ty(), ArrayType::get(OriginTy, kParamTLSSize / 4), OriginTy,
717       OriginTy);
718   MsanGetContextStateFn = M.getOrInsertFunction(
719       "__msan_get_context_state", PointerType::get(MsanContextStateTy, 0));
720 
721   Type *RetTy = StructType::get(PointerType::get(IRB.getInt8Ty(), 0),
722                                 PointerType::get(IRB.getInt32Ty(), 0));
723 
724   for (int ind = 0, size = 1; ind < 4; ind++, size <<= 1) {
725     std::string name_load =
726         "__msan_metadata_ptr_for_load_" + std::to_string(size);
727     std::string name_store =
728         "__msan_metadata_ptr_for_store_" + std::to_string(size);
729     MsanMetadataPtrForLoad_1_8[ind] = M.getOrInsertFunction(
730         name_load, RetTy, PointerType::get(IRB.getInt8Ty(), 0));
731     MsanMetadataPtrForStore_1_8[ind] = M.getOrInsertFunction(
732         name_store, RetTy, PointerType::get(IRB.getInt8Ty(), 0));
733   }
734 
735   MsanMetadataPtrForLoadN = M.getOrInsertFunction(
736       "__msan_metadata_ptr_for_load_n", RetTy,
737       PointerType::get(IRB.getInt8Ty(), 0), IRB.getInt64Ty());
738   MsanMetadataPtrForStoreN = M.getOrInsertFunction(
739       "__msan_metadata_ptr_for_store_n", RetTy,
740       PointerType::get(IRB.getInt8Ty(), 0), IRB.getInt64Ty());
741 
742   // Functions for poisoning and unpoisoning memory.
743   MsanPoisonAllocaFn =
744       M.getOrInsertFunction("__msan_poison_alloca", IRB.getVoidTy(),
745                             IRB.getInt8PtrTy(), IntptrTy, IRB.getInt8PtrTy());
746   MsanUnpoisonAllocaFn = M.getOrInsertFunction(
747       "__msan_unpoison_alloca", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy);
748 }
749 
750 static Constant *getOrInsertGlobal(Module &M, StringRef Name, Type *Ty) {
751   return M.getOrInsertGlobal(Name, Ty, [&] {
752     return new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
753                               nullptr, Name, nullptr,
754                               GlobalVariable::InitialExecTLSModel);
755   });
756 }
757 
758 /// Insert declarations for userspace-specific functions and globals.
759 void MemorySanitizer::createUserspaceApi(Module &M) {
760   IRBuilder<> IRB(*C);
761   // Create the callback.
762   // FIXME: this function should have "Cold" calling conv,
763   // which is not yet implemented.
764   StringRef WarningFnName = Recover ? "__msan_warning"
765                                     : "__msan_warning_noreturn";
766   WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy());
767 
768   // Create the global TLS variables.
769   RetvalTLS =
770       getOrInsertGlobal(M, "__msan_retval_tls",
771                         ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8));
772 
773   RetvalOriginTLS = getOrInsertGlobal(M, "__msan_retval_origin_tls", OriginTy);
774 
775   ParamTLS =
776       getOrInsertGlobal(M, "__msan_param_tls",
777                         ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8));
778 
779   ParamOriginTLS =
780       getOrInsertGlobal(M, "__msan_param_origin_tls",
781                         ArrayType::get(OriginTy, kParamTLSSize / 4));
782 
783   VAArgTLS =
784       getOrInsertGlobal(M, "__msan_va_arg_tls",
785                         ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8));
786 
787   VAArgOriginTLS =
788       getOrInsertGlobal(M, "__msan_va_arg_origin_tls",
789                         ArrayType::get(OriginTy, kParamTLSSize / 4));
790 
791   VAArgOverflowSizeTLS =
792       getOrInsertGlobal(M, "__msan_va_arg_overflow_size_tls", IRB.getInt64Ty());
793   OriginTLS = getOrInsertGlobal(M, "__msan_origin_tls", IRB.getInt32Ty());
794 
795   for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
796        AccessSizeIndex++) {
797     unsigned AccessSize = 1 << AccessSizeIndex;
798     std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
799     MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
800         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
801         IRB.getInt32Ty());
802 
803     FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
804     MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
805         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
806         IRB.getInt8PtrTy(), IRB.getInt32Ty());
807   }
808 
809   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
810     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
811     IRB.getInt8PtrTy(), IntptrTy);
812   MsanPoisonStackFn =
813       M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
814                             IRB.getInt8PtrTy(), IntptrTy);
815 }
816 
817 /// Insert extern declaration of runtime-provided functions and globals.
818 void MemorySanitizer::initializeCallbacks(Module &M) {
819   // Only do this once.
820   if (CallbacksInitialized)
821     return;
822 
823   IRBuilder<> IRB(*C);
824   // Initialize callbacks that are common for kernel and userspace
825   // instrumentation.
826   MsanChainOriginFn = M.getOrInsertFunction(
827     "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty());
828   MemmoveFn = M.getOrInsertFunction(
829     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
830     IRB.getInt8PtrTy(), IntptrTy);
831   MemcpyFn = M.getOrInsertFunction(
832     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
833     IntptrTy);
834   MemsetFn = M.getOrInsertFunction(
835     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
836     IntptrTy);
837   // We insert an empty inline asm after __msan_report* to avoid callback merge.
838   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
839                             StringRef(""), StringRef(""),
840                             /*hasSideEffects=*/true);
841 
842   MsanInstrumentAsmStoreFn =
843       M.getOrInsertFunction("__msan_instrument_asm_store", IRB.getVoidTy(),
844                             PointerType::get(IRB.getInt8Ty(), 0), IntptrTy);
845 
846   if (CompileKernel) {
847     createKernelApi(M);
848   } else {
849     createUserspaceApi(M);
850   }
851   CallbacksInitialized = true;
852 }
853 
854 FunctionCallee MemorySanitizer::getKmsanShadowOriginAccessFn(bool isStore,
855                                                              int size) {
856   FunctionCallee *Fns =
857       isStore ? MsanMetadataPtrForStore_1_8 : MsanMetadataPtrForLoad_1_8;
858   switch (size) {
859   case 1:
860     return Fns[0];
861   case 2:
862     return Fns[1];
863   case 4:
864     return Fns[2];
865   case 8:
866     return Fns[3];
867   default:
868     return nullptr;
869   }
870 }
871 
872 /// Module-level initialization.
873 ///
874 /// inserts a call to __msan_init to the module's constructor list.
875 void MemorySanitizer::initializeModule(Module &M) {
876   auto &DL = M.getDataLayout();
877 
878   bool ShadowPassed = ClShadowBase.getNumOccurrences() > 0;
879   bool OriginPassed = ClOriginBase.getNumOccurrences() > 0;
880   // Check the overrides first
881   if (ShadowPassed || OriginPassed) {
882     CustomMapParams.AndMask = ClAndMask;
883     CustomMapParams.XorMask = ClXorMask;
884     CustomMapParams.ShadowBase = ClShadowBase;
885     CustomMapParams.OriginBase = ClOriginBase;
886     MapParams = &CustomMapParams;
887   } else {
888     Triple TargetTriple(M.getTargetTriple());
889     switch (TargetTriple.getOS()) {
890       case Triple::FreeBSD:
891         switch (TargetTriple.getArch()) {
892           case Triple::x86_64:
893             MapParams = FreeBSD_X86_MemoryMapParams.bits64;
894             break;
895           case Triple::x86:
896             MapParams = FreeBSD_X86_MemoryMapParams.bits32;
897             break;
898           default:
899             report_fatal_error("unsupported architecture");
900         }
901         break;
902       case Triple::NetBSD:
903         switch (TargetTriple.getArch()) {
904           case Triple::x86_64:
905             MapParams = NetBSD_X86_MemoryMapParams.bits64;
906             break;
907           default:
908             report_fatal_error("unsupported architecture");
909         }
910         break;
911       case Triple::Linux:
912         switch (TargetTriple.getArch()) {
913           case Triple::x86_64:
914             MapParams = Linux_X86_MemoryMapParams.bits64;
915             break;
916           case Triple::x86:
917             MapParams = Linux_X86_MemoryMapParams.bits32;
918             break;
919           case Triple::mips64:
920           case Triple::mips64el:
921             MapParams = Linux_MIPS_MemoryMapParams.bits64;
922             break;
923           case Triple::ppc64:
924           case Triple::ppc64le:
925             MapParams = Linux_PowerPC_MemoryMapParams.bits64;
926             break;
927           case Triple::aarch64:
928           case Triple::aarch64_be:
929             MapParams = Linux_ARM_MemoryMapParams.bits64;
930             break;
931           default:
932             report_fatal_error("unsupported architecture");
933         }
934         break;
935       default:
936         report_fatal_error("unsupported operating system");
937     }
938   }
939 
940   C = &(M.getContext());
941   IRBuilder<> IRB(*C);
942   IntptrTy = IRB.getIntPtrTy(DL);
943   OriginTy = IRB.getInt32Ty();
944 
945   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
946   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
947 
948   if (!CompileKernel) {
949     if (TrackOrigins)
950       M.getOrInsertGlobal("__msan_track_origins", IRB.getInt32Ty(), [&] {
951         return new GlobalVariable(
952             M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
953             IRB.getInt32(TrackOrigins), "__msan_track_origins");
954       });
955 
956     if (Recover)
957       M.getOrInsertGlobal("__msan_keep_going", IRB.getInt32Ty(), [&] {
958         return new GlobalVariable(M, IRB.getInt32Ty(), true,
959                                   GlobalValue::WeakODRLinkage,
960                                   IRB.getInt32(Recover), "__msan_keep_going");
961       });
962 }
963 }
964 
965 bool MemorySanitizerLegacyPass::doInitialization(Module &M) {
966   if (!Options.Kernel)
967     insertModuleCtor(M);
968   MSan.emplace(M, Options);
969   return true;
970 }
971 
972 namespace {
973 
974 /// A helper class that handles instrumentation of VarArg
975 /// functions on a particular platform.
976 ///
977 /// Implementations are expected to insert the instrumentation
978 /// necessary to propagate argument shadow through VarArg function
979 /// calls. Visit* methods are called during an InstVisitor pass over
980 /// the function, and should avoid creating new basic blocks. A new
981 /// instance of this class is created for each instrumented function.
982 struct VarArgHelper {
983   virtual ~VarArgHelper() = default;
984 
985   /// Visit a CallSite.
986   virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
987 
988   /// Visit a va_start call.
989   virtual void visitVAStartInst(VAStartInst &I) = 0;
990 
991   /// Visit a va_copy call.
992   virtual void visitVACopyInst(VACopyInst &I) = 0;
993 
994   /// Finalize function instrumentation.
995   ///
996   /// This method is called after visiting all interesting (see above)
997   /// instructions in a function.
998   virtual void finalizeInstrumentation() = 0;
999 };
1000 
1001 struct MemorySanitizerVisitor;
1002 
1003 } // end anonymous namespace
1004 
1005 static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1006                                         MemorySanitizerVisitor &Visitor);
1007 
1008 static unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
1009   if (TypeSize <= 8) return 0;
1010   return Log2_32_Ceil((TypeSize + 7) / 8);
1011 }
1012 
1013 namespace {
1014 
1015 /// This class does all the work for a given function. Store and Load
1016 /// instructions store and load corresponding shadow and origin
1017 /// values. Most instructions propagate shadow from arguments to their
1018 /// return values. Certain instructions (most importantly, BranchInst)
1019 /// test their argument shadow and print reports (with a runtime call) if it's
1020 /// non-zero.
1021 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
1022   Function &F;
1023   MemorySanitizer &MS;
1024   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
1025   ValueMap<Value*, Value*> ShadowMap, OriginMap;
1026   std::unique_ptr<VarArgHelper> VAHelper;
1027   const TargetLibraryInfo *TLI;
1028   BasicBlock *ActualFnStart;
1029 
1030   // The following flags disable parts of MSan instrumentation based on
1031   // blacklist contents and command-line options.
1032   bool InsertChecks;
1033   bool PropagateShadow;
1034   bool PoisonStack;
1035   bool PoisonUndef;
1036   bool CheckReturnValue;
1037 
1038   struct ShadowOriginAndInsertPoint {
1039     Value *Shadow;
1040     Value *Origin;
1041     Instruction *OrigIns;
1042 
1043     ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
1044       : Shadow(S), Origin(O), OrigIns(I) {}
1045   };
1046   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
1047   bool InstrumentLifetimeStart = ClHandleLifetimeIntrinsics;
1048   SmallSet<AllocaInst *, 16> AllocaSet;
1049   SmallVector<std::pair<IntrinsicInst *, AllocaInst *>, 16> LifetimeStartList;
1050   SmallVector<StoreInst *, 16> StoreList;
1051 
1052   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS,
1053                          const TargetLibraryInfo &TLI)
1054       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)), TLI(&TLI) {
1055     bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
1056     InsertChecks = SanitizeFunction;
1057     PropagateShadow = SanitizeFunction;
1058     PoisonStack = SanitizeFunction && ClPoisonStack;
1059     PoisonUndef = SanitizeFunction && ClPoisonUndef;
1060     // FIXME: Consider using SpecialCaseList to specify a list of functions that
1061     // must always return fully initialized values. For now, we hardcode "main".
1062     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
1063 
1064     MS.initializeCallbacks(*F.getParent());
1065     if (MS.CompileKernel)
1066       ActualFnStart = insertKmsanPrologue(F);
1067     else
1068       ActualFnStart = &F.getEntryBlock();
1069 
1070     LLVM_DEBUG(if (!InsertChecks) dbgs()
1071                << "MemorySanitizer is not inserting checks into '"
1072                << F.getName() << "'\n");
1073   }
1074 
1075   Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
1076     if (MS.TrackOrigins <= 1) return V;
1077     return IRB.CreateCall(MS.MsanChainOriginFn, V);
1078   }
1079 
1080   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
1081     const DataLayout &DL = F.getParent()->getDataLayout();
1082     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
1083     if (IntptrSize == kOriginSize) return Origin;
1084     assert(IntptrSize == kOriginSize * 2);
1085     Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
1086     return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
1087   }
1088 
1089   /// Fill memory range with the given origin value.
1090   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
1091                    unsigned Size, Align Alignment) {
1092     const DataLayout &DL = F.getParent()->getDataLayout();
1093     const Align IntptrAlignment = Align(DL.getABITypeAlignment(MS.IntptrTy));
1094     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
1095     assert(IntptrAlignment >= kMinOriginAlignment);
1096     assert(IntptrSize >= kOriginSize);
1097 
1098     unsigned Ofs = 0;
1099     Align CurrentAlignment = Alignment;
1100     if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
1101       Value *IntptrOrigin = originToIntptr(IRB, Origin);
1102       Value *IntptrOriginPtr =
1103           IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
1104       for (unsigned i = 0; i < Size / IntptrSize; ++i) {
1105         Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
1106                        : IntptrOriginPtr;
1107         IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
1108         Ofs += IntptrSize / kOriginSize;
1109         CurrentAlignment = IntptrAlignment;
1110       }
1111     }
1112 
1113     for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
1114       Value *GEP =
1115           i ? IRB.CreateConstGEP1_32(MS.OriginTy, OriginPtr, i) : OriginPtr;
1116       IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
1117       CurrentAlignment = kMinOriginAlignment;
1118     }
1119   }
1120 
1121   void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
1122                    Value *OriginPtr, Align Alignment, bool AsCall) {
1123     const DataLayout &DL = F.getParent()->getDataLayout();
1124     const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1125     unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
1126     if (Shadow->getType()->isAggregateType()) {
1127       paintOrigin(IRB, updateOrigin(Origin, IRB), OriginPtr, StoreSize,
1128                   OriginAlignment);
1129     } else {
1130       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
1131       if (auto *ConstantShadow = dyn_cast<Constant>(ConvertedShadow)) {
1132         if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
1133           paintOrigin(IRB, updateOrigin(Origin, IRB), OriginPtr, StoreSize,
1134                       OriginAlignment);
1135         return;
1136       }
1137 
1138       unsigned TypeSizeInBits =
1139           DL.getTypeSizeInBits(ConvertedShadow->getType());
1140       unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
1141       if (AsCall && SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) {
1142         FunctionCallee Fn = MS.MaybeStoreOriginFn[SizeIndex];
1143         Value *ConvertedShadow2 = IRB.CreateZExt(
1144             ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
1145         IRB.CreateCall(Fn, {ConvertedShadow2,
1146                             IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
1147                             Origin});
1148       } else {
1149         Value *Cmp = IRB.CreateICmpNE(
1150             ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
1151         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
1152             Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
1153         IRBuilder<> IRBNew(CheckTerm);
1154         paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), OriginPtr, StoreSize,
1155                     OriginAlignment);
1156       }
1157     }
1158   }
1159 
1160   void materializeStores(bool InstrumentWithCalls) {
1161     for (StoreInst *SI : StoreList) {
1162       IRBuilder<> IRB(SI);
1163       Value *Val = SI->getValueOperand();
1164       Value *Addr = SI->getPointerOperand();
1165       Value *Shadow = SI->isAtomic() ? getCleanShadow(Val) : getShadow(Val);
1166       Value *ShadowPtr, *OriginPtr;
1167       Type *ShadowTy = Shadow->getType();
1168       const Align Alignment = assumeAligned(SI->getAlignment());
1169       const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1170       std::tie(ShadowPtr, OriginPtr) =
1171           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ true);
1172 
1173       StoreInst *NewSI = IRB.CreateAlignedStore(Shadow, ShadowPtr, Alignment);
1174       LLVM_DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
1175       (void)NewSI;
1176 
1177       if (SI->isAtomic())
1178         SI->setOrdering(addReleaseOrdering(SI->getOrdering()));
1179 
1180       if (MS.TrackOrigins && !SI->isAtomic())
1181         storeOrigin(IRB, Addr, Shadow, getOrigin(Val), OriginPtr,
1182                     OriginAlignment, InstrumentWithCalls);
1183     }
1184   }
1185 
1186   /// Helper function to insert a warning at IRB's current insert point.
1187   void insertWarningFn(IRBuilder<> &IRB, Value *Origin) {
1188     if (!Origin)
1189       Origin = (Value *)IRB.getInt32(0);
1190     if (MS.CompileKernel) {
1191       IRB.CreateCall(MS.WarningFn, Origin);
1192     } else {
1193       if (MS.TrackOrigins) {
1194         IRB.CreateStore(Origin, MS.OriginTLS);
1195       }
1196       IRB.CreateCall(MS.WarningFn, {});
1197     }
1198     IRB.CreateCall(MS.EmptyAsm, {});
1199     // FIXME: Insert UnreachableInst if !MS.Recover?
1200     // This may invalidate some of the following checks and needs to be done
1201     // at the very end.
1202   }
1203 
1204   void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
1205                            bool AsCall) {
1206     IRBuilder<> IRB(OrigIns);
1207     LLVM_DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
1208     Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
1209     LLVM_DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
1210 
1211     if (auto *ConstantShadow = dyn_cast<Constant>(ConvertedShadow)) {
1212       if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
1213         insertWarningFn(IRB, Origin);
1214       }
1215       return;
1216     }
1217 
1218     const DataLayout &DL = OrigIns->getModule()->getDataLayout();
1219 
1220     unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
1221     unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
1222     if (AsCall && SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) {
1223       FunctionCallee Fn = MS.MaybeWarningFn[SizeIndex];
1224       Value *ConvertedShadow2 =
1225           IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
1226       IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
1227                                                 ? Origin
1228                                                 : (Value *)IRB.getInt32(0)});
1229     } else {
1230       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
1231                                     getCleanShadow(ConvertedShadow), "_mscmp");
1232       Instruction *CheckTerm = SplitBlockAndInsertIfThen(
1233           Cmp, OrigIns,
1234           /* Unreachable */ !MS.Recover, MS.ColdCallWeights);
1235 
1236       IRB.SetInsertPoint(CheckTerm);
1237       insertWarningFn(IRB, Origin);
1238       LLVM_DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
1239     }
1240   }
1241 
1242   void materializeChecks(bool InstrumentWithCalls) {
1243     for (const auto &ShadowData : InstrumentationList) {
1244       Instruction *OrigIns = ShadowData.OrigIns;
1245       Value *Shadow = ShadowData.Shadow;
1246       Value *Origin = ShadowData.Origin;
1247       materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
1248     }
1249     LLVM_DEBUG(dbgs() << "DONE:\n" << F);
1250   }
1251 
1252   BasicBlock *insertKmsanPrologue(Function &F) {
1253     BasicBlock *ret =
1254         SplitBlock(&F.getEntryBlock(), F.getEntryBlock().getFirstNonPHI());
1255     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1256     Value *ContextState = IRB.CreateCall(MS.MsanGetContextStateFn, {});
1257     Constant *Zero = IRB.getInt32(0);
1258     MS.ParamTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1259                                 {Zero, IRB.getInt32(0)}, "param_shadow");
1260     MS.RetvalTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1261                                  {Zero, IRB.getInt32(1)}, "retval_shadow");
1262     MS.VAArgTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1263                                 {Zero, IRB.getInt32(2)}, "va_arg_shadow");
1264     MS.VAArgOriginTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1265                                       {Zero, IRB.getInt32(3)}, "va_arg_origin");
1266     MS.VAArgOverflowSizeTLS =
1267         IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1268                       {Zero, IRB.getInt32(4)}, "va_arg_overflow_size");
1269     MS.ParamOriginTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1270                                       {Zero, IRB.getInt32(5)}, "param_origin");
1271     MS.RetvalOriginTLS =
1272         IRB.CreateGEP(MS.MsanContextStateTy, ContextState,
1273                       {Zero, IRB.getInt32(6)}, "retval_origin");
1274     return ret;
1275   }
1276 
1277   /// Add MemorySanitizer instrumentation to a function.
1278   bool runOnFunction() {
1279     // In the presence of unreachable blocks, we may see Phi nodes with
1280     // incoming nodes from such blocks. Since InstVisitor skips unreachable
1281     // blocks, such nodes will not have any shadow value associated with them.
1282     // It's easier to remove unreachable blocks than deal with missing shadow.
1283     removeUnreachableBlocks(F);
1284 
1285     // Iterate all BBs in depth-first order and create shadow instructions
1286     // for all instructions (where applicable).
1287     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
1288     for (BasicBlock *BB : depth_first(ActualFnStart))
1289       visit(*BB);
1290 
1291     // Finalize PHI nodes.
1292     for (PHINode *PN : ShadowPHINodes) {
1293       PHINode *PNS = cast<PHINode>(getShadow(PN));
1294       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
1295       size_t NumValues = PN->getNumIncomingValues();
1296       for (size_t v = 0; v < NumValues; v++) {
1297         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
1298         if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
1299       }
1300     }
1301 
1302     VAHelper->finalizeInstrumentation();
1303 
1304     // Poison llvm.lifetime.start intrinsics, if we haven't fallen back to
1305     // instrumenting only allocas.
1306     if (InstrumentLifetimeStart) {
1307       for (auto Item : LifetimeStartList) {
1308         instrumentAlloca(*Item.second, Item.first);
1309         AllocaSet.erase(Item.second);
1310       }
1311     }
1312     // Poison the allocas for which we didn't instrument the corresponding
1313     // lifetime intrinsics.
1314     for (AllocaInst *AI : AllocaSet)
1315       instrumentAlloca(*AI);
1316 
1317     bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
1318                                InstrumentationList.size() + StoreList.size() >
1319                                    (unsigned)ClInstrumentationWithCallThreshold;
1320 
1321     // Insert shadow value checks.
1322     materializeChecks(InstrumentWithCalls);
1323 
1324     // Delayed instrumentation of StoreInst.
1325     // This may not add new address checks.
1326     materializeStores(InstrumentWithCalls);
1327 
1328     return true;
1329   }
1330 
1331   /// Compute the shadow type that corresponds to a given Value.
1332   Type *getShadowTy(Value *V) {
1333     return getShadowTy(V->getType());
1334   }
1335 
1336   /// Compute the shadow type that corresponds to a given Type.
1337   Type *getShadowTy(Type *OrigTy) {
1338     if (!OrigTy->isSized()) {
1339       return nullptr;
1340     }
1341     // For integer type, shadow is the same as the original type.
1342     // This may return weird-sized types like i1.
1343     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
1344       return IT;
1345     const DataLayout &DL = F.getParent()->getDataLayout();
1346     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
1347       uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
1348       return VectorType::get(IntegerType::get(*MS.C, EltSize),
1349                              VT->getNumElements());
1350     }
1351     if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
1352       return ArrayType::get(getShadowTy(AT->getElementType()),
1353                             AT->getNumElements());
1354     }
1355     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
1356       SmallVector<Type*, 4> Elements;
1357       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1358         Elements.push_back(getShadowTy(ST->getElementType(i)));
1359       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
1360       LLVM_DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
1361       return Res;
1362     }
1363     uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
1364     return IntegerType::get(*MS.C, TypeSize);
1365   }
1366 
1367   /// Flatten a vector type.
1368   Type *getShadowTyNoVec(Type *ty) {
1369     if (VectorType *vt = dyn_cast<VectorType>(ty))
1370       return IntegerType::get(*MS.C, vt->getBitWidth());
1371     return ty;
1372   }
1373 
1374   /// Convert a shadow value to it's flattened variant.
1375   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
1376     Type *Ty = V->getType();
1377     Type *NoVecTy = getShadowTyNoVec(Ty);
1378     if (Ty == NoVecTy) return V;
1379     return IRB.CreateBitCast(V, NoVecTy);
1380   }
1381 
1382   /// Compute the integer shadow offset that corresponds to a given
1383   /// application address.
1384   ///
1385   /// Offset = (Addr & ~AndMask) ^ XorMask
1386   Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
1387     Value *OffsetLong = IRB.CreatePointerCast(Addr, MS.IntptrTy);
1388 
1389     uint64_t AndMask = MS.MapParams->AndMask;
1390     if (AndMask)
1391       OffsetLong =
1392           IRB.CreateAnd(OffsetLong, ConstantInt::get(MS.IntptrTy, ~AndMask));
1393 
1394     uint64_t XorMask = MS.MapParams->XorMask;
1395     if (XorMask)
1396       OffsetLong =
1397           IRB.CreateXor(OffsetLong, ConstantInt::get(MS.IntptrTy, XorMask));
1398     return OffsetLong;
1399   }
1400 
1401   /// Compute the shadow and origin addresses corresponding to a given
1402   /// application address.
1403   ///
1404   /// Shadow = ShadowBase + Offset
1405   /// Origin = (OriginBase + Offset) & ~3ULL
1406   std::pair<Value *, Value *>
1407   getShadowOriginPtrUserspace(Value *Addr, IRBuilder<> &IRB, Type *ShadowTy,
1408                               MaybeAlign Alignment) {
1409     Value *ShadowOffset = getShadowPtrOffset(Addr, IRB);
1410     Value *ShadowLong = ShadowOffset;
1411     uint64_t ShadowBase = MS.MapParams->ShadowBase;
1412     if (ShadowBase != 0) {
1413       ShadowLong =
1414         IRB.CreateAdd(ShadowLong,
1415                       ConstantInt::get(MS.IntptrTy, ShadowBase));
1416     }
1417     Value *ShadowPtr =
1418         IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
1419     Value *OriginPtr = nullptr;
1420     if (MS.TrackOrigins) {
1421       Value *OriginLong = ShadowOffset;
1422       uint64_t OriginBase = MS.MapParams->OriginBase;
1423       if (OriginBase != 0)
1424         OriginLong = IRB.CreateAdd(OriginLong,
1425                                    ConstantInt::get(MS.IntptrTy, OriginBase));
1426       if (!Alignment || *Alignment < kMinOriginAlignment) {
1427         uint64_t Mask = kMinOriginAlignment.value() - 1;
1428         OriginLong =
1429             IRB.CreateAnd(OriginLong, ConstantInt::get(MS.IntptrTy, ~Mask));
1430       }
1431       OriginPtr =
1432           IRB.CreateIntToPtr(OriginLong, PointerType::get(MS.OriginTy, 0));
1433     }
1434     return std::make_pair(ShadowPtr, OriginPtr);
1435   }
1436 
1437   std::pair<Value *, Value *> getShadowOriginPtrKernel(Value *Addr,
1438                                                        IRBuilder<> &IRB,
1439                                                        Type *ShadowTy,
1440                                                        bool isStore) {
1441     Value *ShadowOriginPtrs;
1442     const DataLayout &DL = F.getParent()->getDataLayout();
1443     int Size = DL.getTypeStoreSize(ShadowTy);
1444 
1445     FunctionCallee Getter = MS.getKmsanShadowOriginAccessFn(isStore, Size);
1446     Value *AddrCast =
1447         IRB.CreatePointerCast(Addr, PointerType::get(IRB.getInt8Ty(), 0));
1448     if (Getter) {
1449       ShadowOriginPtrs = IRB.CreateCall(Getter, AddrCast);
1450     } else {
1451       Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size);
1452       ShadowOriginPtrs = IRB.CreateCall(isStore ? MS.MsanMetadataPtrForStoreN
1453                                                 : MS.MsanMetadataPtrForLoadN,
1454                                         {AddrCast, SizeVal});
1455     }
1456     Value *ShadowPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 0);
1457     ShadowPtr = IRB.CreatePointerCast(ShadowPtr, PointerType::get(ShadowTy, 0));
1458     Value *OriginPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 1);
1459 
1460     return std::make_pair(ShadowPtr, OriginPtr);
1461   }
1462 
1463   std::pair<Value *, Value *> getShadowOriginPtr(Value *Addr, IRBuilder<> &IRB,
1464                                                  Type *ShadowTy,
1465                                                  MaybeAlign Alignment,
1466                                                  bool isStore) {
1467     if (MS.CompileKernel)
1468       return getShadowOriginPtrKernel(Addr, IRB, ShadowTy, isStore);
1469     return getShadowOriginPtrUserspace(Addr, IRB, ShadowTy, Alignment);
1470   }
1471 
1472   /// Compute the shadow address for a given function argument.
1473   ///
1474   /// Shadow = ParamTLS+ArgOffset.
1475   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
1476                                  int ArgOffset) {
1477     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
1478     if (ArgOffset)
1479       Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1480     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
1481                               "_msarg");
1482   }
1483 
1484   /// Compute the origin address for a given function argument.
1485   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
1486                                  int ArgOffset) {
1487     if (!MS.TrackOrigins)
1488       return nullptr;
1489     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
1490     if (ArgOffset)
1491       Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1492     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
1493                               "_msarg_o");
1494   }
1495 
1496   /// Compute the shadow address for a retval.
1497   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
1498     return IRB.CreatePointerCast(MS.RetvalTLS,
1499                                  PointerType::get(getShadowTy(A), 0),
1500                                  "_msret");
1501   }
1502 
1503   /// Compute the origin address for a retval.
1504   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
1505     // We keep a single origin for the entire retval. Might be too optimistic.
1506     return MS.RetvalOriginTLS;
1507   }
1508 
1509   /// Set SV to be the shadow value for V.
1510   void setShadow(Value *V, Value *SV) {
1511     assert(!ShadowMap.count(V) && "Values may only have one shadow");
1512     ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
1513   }
1514 
1515   /// Set Origin to be the origin value for V.
1516   void setOrigin(Value *V, Value *Origin) {
1517     if (!MS.TrackOrigins) return;
1518     assert(!OriginMap.count(V) && "Values may only have one origin");
1519     LLVM_DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
1520     OriginMap[V] = Origin;
1521   }
1522 
1523   Constant *getCleanShadow(Type *OrigTy) {
1524     Type *ShadowTy = getShadowTy(OrigTy);
1525     if (!ShadowTy)
1526       return nullptr;
1527     return Constant::getNullValue(ShadowTy);
1528   }
1529 
1530   /// Create a clean shadow value for a given value.
1531   ///
1532   /// Clean shadow (all zeroes) means all bits of the value are defined
1533   /// (initialized).
1534   Constant *getCleanShadow(Value *V) {
1535     return getCleanShadow(V->getType());
1536   }
1537 
1538   /// Create a dirty shadow of a given shadow type.
1539   Constant *getPoisonedShadow(Type *ShadowTy) {
1540     assert(ShadowTy);
1541     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
1542       return Constant::getAllOnesValue(ShadowTy);
1543     if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
1544       SmallVector<Constant *, 4> Vals(AT->getNumElements(),
1545                                       getPoisonedShadow(AT->getElementType()));
1546       return ConstantArray::get(AT, Vals);
1547     }
1548     if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
1549       SmallVector<Constant *, 4> Vals;
1550       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1551         Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1552       return ConstantStruct::get(ST, Vals);
1553     }
1554     llvm_unreachable("Unexpected shadow type");
1555   }
1556 
1557   /// Create a dirty shadow for a given value.
1558   Constant *getPoisonedShadow(Value *V) {
1559     Type *ShadowTy = getShadowTy(V);
1560     if (!ShadowTy)
1561       return nullptr;
1562     return getPoisonedShadow(ShadowTy);
1563   }
1564 
1565   /// Create a clean (zero) origin.
1566   Value *getCleanOrigin() {
1567     return Constant::getNullValue(MS.OriginTy);
1568   }
1569 
1570   /// Get the shadow value for a given Value.
1571   ///
1572   /// This function either returns the value set earlier with setShadow,
1573   /// or extracts if from ParamTLS (for function arguments).
1574   Value *getShadow(Value *V) {
1575     if (!PropagateShadow) return getCleanShadow(V);
1576     if (Instruction *I = dyn_cast<Instruction>(V)) {
1577       if (I->getMetadata("nosanitize"))
1578         return getCleanShadow(V);
1579       // For instructions the shadow is already stored in the map.
1580       Value *Shadow = ShadowMap[V];
1581       if (!Shadow) {
1582         LLVM_DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
1583         (void)I;
1584         assert(Shadow && "No shadow for a value");
1585       }
1586       return Shadow;
1587     }
1588     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
1589       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
1590       LLVM_DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
1591       (void)U;
1592       return AllOnes;
1593     }
1594     if (Argument *A = dyn_cast<Argument>(V)) {
1595       // For arguments we compute the shadow on demand and store it in the map.
1596       Value **ShadowPtr = &ShadowMap[V];
1597       if (*ShadowPtr)
1598         return *ShadowPtr;
1599       Function *F = A->getParent();
1600       IRBuilder<> EntryIRB(ActualFnStart->getFirstNonPHI());
1601       unsigned ArgOffset = 0;
1602       const DataLayout &DL = F->getParent()->getDataLayout();
1603       for (auto &FArg : F->args()) {
1604         if (!FArg.getType()->isSized()) {
1605           LLVM_DEBUG(dbgs() << "Arg is not sized\n");
1606           continue;
1607         }
1608         unsigned Size =
1609             FArg.hasByValAttr()
1610                 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
1611                 : DL.getTypeAllocSize(FArg.getType());
1612         if (A == &FArg) {
1613           bool Overflow = ArgOffset + Size > kParamTLSSize;
1614           Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1615           if (FArg.hasByValAttr()) {
1616             // ByVal pointer itself has clean shadow. We copy the actual
1617             // argument shadow to the underlying memory.
1618             // Figure out maximal valid memcpy alignment.
1619             const Align ArgAlign = DL.getValueOrABITypeAlignment(
1620                 MaybeAlign(FArg.getParamAlignment()),
1621                 A->getType()->getPointerElementType());
1622             Value *CpShadowPtr =
1623                 getShadowOriginPtr(V, EntryIRB, EntryIRB.getInt8Ty(), ArgAlign,
1624                                    /*isStore*/ true)
1625                     .first;
1626             // TODO(glider): need to copy origins.
1627             if (Overflow) {
1628               // ParamTLS overflow.
1629               EntryIRB.CreateMemSet(
1630                   CpShadowPtr, Constant::getNullValue(EntryIRB.getInt8Ty()),
1631                   Size, ArgAlign);
1632             } else {
1633               const Align CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1634               Value *Cpy = EntryIRB.CreateMemCpy(CpShadowPtr, CopyAlign, Base,
1635                                                  CopyAlign, Size);
1636               LLVM_DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
1637               (void)Cpy;
1638             }
1639             *ShadowPtr = getCleanShadow(V);
1640           } else {
1641             if (Overflow) {
1642               // ParamTLS overflow.
1643               *ShadowPtr = getCleanShadow(V);
1644             } else {
1645               *ShadowPtr = EntryIRB.CreateAlignedLoad(getShadowTy(&FArg), Base,
1646                                                       kShadowTLSAlignment);
1647             }
1648           }
1649           LLVM_DEBUG(dbgs()
1650                      << "  ARG:    " << FArg << " ==> " << **ShadowPtr << "\n");
1651           if (MS.TrackOrigins && !Overflow) {
1652             Value *OriginPtr =
1653                 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
1654             setOrigin(A, EntryIRB.CreateLoad(MS.OriginTy, OriginPtr));
1655           } else {
1656             setOrigin(A, getCleanOrigin());
1657           }
1658         }
1659         ArgOffset += alignTo(Size, kShadowTLSAlignment);
1660       }
1661       assert(*ShadowPtr && "Could not find shadow for an argument");
1662       return *ShadowPtr;
1663     }
1664     // For everything else the shadow is zero.
1665     return getCleanShadow(V);
1666   }
1667 
1668   /// Get the shadow for i-th argument of the instruction I.
1669   Value *getShadow(Instruction *I, int i) {
1670     return getShadow(I->getOperand(i));
1671   }
1672 
1673   /// Get the origin for a value.
1674   Value *getOrigin(Value *V) {
1675     if (!MS.TrackOrigins) return nullptr;
1676     if (!PropagateShadow) return getCleanOrigin();
1677     if (isa<Constant>(V)) return getCleanOrigin();
1678     assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1679            "Unexpected value type in getOrigin()");
1680     if (Instruction *I = dyn_cast<Instruction>(V)) {
1681       if (I->getMetadata("nosanitize"))
1682         return getCleanOrigin();
1683     }
1684     Value *Origin = OriginMap[V];
1685     assert(Origin && "Missing origin");
1686     return Origin;
1687   }
1688 
1689   /// Get the origin for i-th argument of the instruction I.
1690   Value *getOrigin(Instruction *I, int i) {
1691     return getOrigin(I->getOperand(i));
1692   }
1693 
1694   /// Remember the place where a shadow check should be inserted.
1695   ///
1696   /// This location will be later instrumented with a check that will print a
1697   /// UMR warning in runtime if the shadow value is not 0.
1698   void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1699     assert(Shadow);
1700     if (!InsertChecks) return;
1701 #ifndef NDEBUG
1702     Type *ShadowTy = Shadow->getType();
1703     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1704            "Can only insert checks for integer and vector shadow types");
1705 #endif
1706     InstrumentationList.push_back(
1707         ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1708   }
1709 
1710   /// Remember the place where a shadow check should be inserted.
1711   ///
1712   /// This location will be later instrumented with a check that will print a
1713   /// UMR warning in runtime if the value is not fully defined.
1714   void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1715     assert(Val);
1716     Value *Shadow, *Origin;
1717     if (ClCheckConstantShadow) {
1718       Shadow = getShadow(Val);
1719       if (!Shadow) return;
1720       Origin = getOrigin(Val);
1721     } else {
1722       Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1723       if (!Shadow) return;
1724       Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1725     }
1726     insertShadowCheck(Shadow, Origin, OrigIns);
1727   }
1728 
1729   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1730     switch (a) {
1731       case AtomicOrdering::NotAtomic:
1732         return AtomicOrdering::NotAtomic;
1733       case AtomicOrdering::Unordered:
1734       case AtomicOrdering::Monotonic:
1735       case AtomicOrdering::Release:
1736         return AtomicOrdering::Release;
1737       case AtomicOrdering::Acquire:
1738       case AtomicOrdering::AcquireRelease:
1739         return AtomicOrdering::AcquireRelease;
1740       case AtomicOrdering::SequentiallyConsistent:
1741         return AtomicOrdering::SequentiallyConsistent;
1742     }
1743     llvm_unreachable("Unknown ordering");
1744   }
1745 
1746   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1747     switch (a) {
1748       case AtomicOrdering::NotAtomic:
1749         return AtomicOrdering::NotAtomic;
1750       case AtomicOrdering::Unordered:
1751       case AtomicOrdering::Monotonic:
1752       case AtomicOrdering::Acquire:
1753         return AtomicOrdering::Acquire;
1754       case AtomicOrdering::Release:
1755       case AtomicOrdering::AcquireRelease:
1756         return AtomicOrdering::AcquireRelease;
1757       case AtomicOrdering::SequentiallyConsistent:
1758         return AtomicOrdering::SequentiallyConsistent;
1759     }
1760     llvm_unreachable("Unknown ordering");
1761   }
1762 
1763   // ------------------- Visitors.
1764   using InstVisitor<MemorySanitizerVisitor>::visit;
1765   void visit(Instruction &I) {
1766     if (!I.getMetadata("nosanitize"))
1767       InstVisitor<MemorySanitizerVisitor>::visit(I);
1768   }
1769 
1770   /// Instrument LoadInst
1771   ///
1772   /// Loads the corresponding shadow and (optionally) origin.
1773   /// Optionally, checks that the load address is fully defined.
1774   void visitLoadInst(LoadInst &I) {
1775     assert(I.getType()->isSized() && "Load type must have size");
1776     assert(!I.getMetadata("nosanitize"));
1777     IRBuilder<> IRB(I.getNextNode());
1778     Type *ShadowTy = getShadowTy(&I);
1779     Value *Addr = I.getPointerOperand();
1780     Value *ShadowPtr = nullptr, *OriginPtr = nullptr;
1781     const Align Alignment = assumeAligned(I.getAlignment());
1782     if (PropagateShadow) {
1783       std::tie(ShadowPtr, OriginPtr) =
1784           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
1785       setShadow(&I,
1786                 IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Alignment, "_msld"));
1787     } else {
1788       setShadow(&I, getCleanShadow(&I));
1789     }
1790 
1791     if (ClCheckAccessAddress)
1792       insertShadowCheck(I.getPointerOperand(), &I);
1793 
1794     if (I.isAtomic())
1795       I.setOrdering(addAcquireOrdering(I.getOrdering()));
1796 
1797     if (MS.TrackOrigins) {
1798       if (PropagateShadow) {
1799         const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1800         setOrigin(
1801             &I, IRB.CreateAlignedLoad(MS.OriginTy, OriginPtr, OriginAlignment));
1802       } else {
1803         setOrigin(&I, getCleanOrigin());
1804       }
1805     }
1806   }
1807 
1808   /// Instrument StoreInst
1809   ///
1810   /// Stores the corresponding shadow and (optionally) origin.
1811   /// Optionally, checks that the store address is fully defined.
1812   void visitStoreInst(StoreInst &I) {
1813     StoreList.push_back(&I);
1814     if (ClCheckAccessAddress)
1815       insertShadowCheck(I.getPointerOperand(), &I);
1816   }
1817 
1818   void handleCASOrRMW(Instruction &I) {
1819     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1820 
1821     IRBuilder<> IRB(&I);
1822     Value *Addr = I.getOperand(0);
1823     Value *ShadowPtr = getShadowOriginPtr(Addr, IRB, I.getType(), Align(1),
1824                                           /*isStore*/ true)
1825                            .first;
1826 
1827     if (ClCheckAccessAddress)
1828       insertShadowCheck(Addr, &I);
1829 
1830     // Only test the conditional argument of cmpxchg instruction.
1831     // The other argument can potentially be uninitialized, but we can not
1832     // detect this situation reliably without possible false positives.
1833     if (isa<AtomicCmpXchgInst>(I))
1834       insertShadowCheck(I.getOperand(1), &I);
1835 
1836     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1837 
1838     setShadow(&I, getCleanShadow(&I));
1839     setOrigin(&I, getCleanOrigin());
1840   }
1841 
1842   void visitAtomicRMWInst(AtomicRMWInst &I) {
1843     handleCASOrRMW(I);
1844     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1845   }
1846 
1847   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1848     handleCASOrRMW(I);
1849     I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1850   }
1851 
1852   // Vector manipulation.
1853   void visitExtractElementInst(ExtractElementInst &I) {
1854     insertShadowCheck(I.getOperand(1), &I);
1855     IRBuilder<> IRB(&I);
1856     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1857               "_msprop"));
1858     setOrigin(&I, getOrigin(&I, 0));
1859   }
1860 
1861   void visitInsertElementInst(InsertElementInst &I) {
1862     insertShadowCheck(I.getOperand(2), &I);
1863     IRBuilder<> IRB(&I);
1864     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1865               I.getOperand(2), "_msprop"));
1866     setOriginForNaryOp(I);
1867   }
1868 
1869   void visitShuffleVectorInst(ShuffleVectorInst &I) {
1870     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(1), /*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(1);
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 instrumentation 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 intrinsic.
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 intrinsic.
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 intrinsic.
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-differences 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(1), /*isStore*/ true).first;
2872 
2873     IRB.CreateStore(getCleanShadow(Ty),
2874                     IRB.CreatePointerCast(ShadowPtr, Ty->getPointerTo()));
2875 
2876     if (ClCheckAccessAddress)
2877       insertShadowCheck(Addr, &I);
2878   }
2879 
2880   void handleLdmxcsr(IntrinsicInst &I) {
2881     if (!InsertChecks) return;
2882 
2883     IRBuilder<> IRB(&I);
2884     Value *Addr = I.getArgOperand(0);
2885     Type *Ty = IRB.getInt32Ty();
2886     const Align Alignment = Align(1);
2887     Value *ShadowPtr, *OriginPtr;
2888     std::tie(ShadowPtr, OriginPtr) =
2889         getShadowOriginPtr(Addr, IRB, Ty, Alignment, /*isStore*/ false);
2890 
2891     if (ClCheckAccessAddress)
2892       insertShadowCheck(Addr, &I);
2893 
2894     Value *Shadow = IRB.CreateAlignedLoad(Ty, ShadowPtr, Alignment, "_ldmxcsr");
2895     Value *Origin = MS.TrackOrigins ? IRB.CreateLoad(MS.OriginTy, OriginPtr)
2896                                     : getCleanOrigin();
2897     insertShadowCheck(Shadow, Origin, &I);
2898   }
2899 
2900   void handleMaskedStore(IntrinsicInst &I) {
2901     IRBuilder<> IRB(&I);
2902     Value *V = I.getArgOperand(0);
2903     Value *Addr = I.getArgOperand(1);
2904     const Align Alignment(
2905         cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
2906     Value *Mask = I.getArgOperand(3);
2907     Value *Shadow = getShadow(V);
2908 
2909     Value *ShadowPtr;
2910     Value *OriginPtr;
2911     std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr(
2912         Addr, IRB, Shadow->getType(), Alignment, /*isStore*/ true);
2913 
2914     if (ClCheckAccessAddress) {
2915       insertShadowCheck(Addr, &I);
2916       // Uninitialized mask is kind of like uninitialized address, but not as
2917       // scary.
2918       insertShadowCheck(Mask, &I);
2919     }
2920 
2921     IRB.CreateMaskedStore(Shadow, ShadowPtr, Alignment, Mask);
2922 
2923     if (MS.TrackOrigins) {
2924       auto &DL = F.getParent()->getDataLayout();
2925       paintOrigin(IRB, getOrigin(V), OriginPtr,
2926                   DL.getTypeStoreSize(Shadow->getType()),
2927                   std::max(Alignment, kMinOriginAlignment));
2928     }
2929   }
2930 
2931   bool handleMaskedLoad(IntrinsicInst &I) {
2932     IRBuilder<> IRB(&I);
2933     Value *Addr = I.getArgOperand(0);
2934     const Align Alignment(
2935         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
2936     Value *Mask = I.getArgOperand(2);
2937     Value *PassThru = I.getArgOperand(3);
2938 
2939     Type *ShadowTy = getShadowTy(&I);
2940     Value *ShadowPtr, *OriginPtr;
2941     if (PropagateShadow) {
2942       std::tie(ShadowPtr, OriginPtr) =
2943           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
2944       setShadow(&I, IRB.CreateMaskedLoad(ShadowPtr, Alignment, Mask,
2945                                          getShadow(PassThru), "_msmaskedld"));
2946     } else {
2947       setShadow(&I, getCleanShadow(&I));
2948     }
2949 
2950     if (ClCheckAccessAddress) {
2951       insertShadowCheck(Addr, &I);
2952       insertShadowCheck(Mask, &I);
2953     }
2954 
2955     if (MS.TrackOrigins) {
2956       if (PropagateShadow) {
2957         // Choose between PassThru's and the loaded value's origins.
2958         Value *MaskedPassThruShadow = IRB.CreateAnd(
2959             getShadow(PassThru), IRB.CreateSExt(IRB.CreateNeg(Mask), ShadowTy));
2960 
2961         Value *Acc = IRB.CreateExtractElement(
2962             MaskedPassThruShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2963         for (int i = 1, N = PassThru->getType()->getVectorNumElements(); i < N;
2964              ++i) {
2965           Value *More = IRB.CreateExtractElement(
2966               MaskedPassThruShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2967           Acc = IRB.CreateOr(Acc, More);
2968         }
2969 
2970         Value *Origin = IRB.CreateSelect(
2971             IRB.CreateICmpNE(Acc, Constant::getNullValue(Acc->getType())),
2972             getOrigin(PassThru), IRB.CreateLoad(MS.OriginTy, OriginPtr));
2973 
2974         setOrigin(&I, Origin);
2975       } else {
2976         setOrigin(&I, getCleanOrigin());
2977       }
2978     }
2979     return true;
2980   }
2981 
2982   // Instrument BMI / BMI2 intrinsics.
2983   // All of these intrinsics are Z = I(X, Y)
2984   // where the types of all operands and the result match, and are either i32 or i64.
2985   // The following instrumentation happens to work for all of them:
2986   //   Sz = I(Sx, Y) | (sext (Sy != 0))
2987   void handleBmiIntrinsic(IntrinsicInst &I) {
2988     IRBuilder<> IRB(&I);
2989     Type *ShadowTy = getShadowTy(&I);
2990 
2991     // If any bit of the mask operand is poisoned, then the whole thing is.
2992     Value *SMask = getShadow(&I, 1);
2993     SMask = IRB.CreateSExt(IRB.CreateICmpNE(SMask, getCleanShadow(ShadowTy)),
2994                            ShadowTy);
2995     // Apply the same intrinsic to the shadow of the first operand.
2996     Value *S = IRB.CreateCall(I.getCalledFunction(),
2997                               {getShadow(&I, 0), I.getOperand(1)});
2998     S = IRB.CreateOr(SMask, S);
2999     setShadow(&I, S);
3000     setOriginForNaryOp(I);
3001   }
3002 
3003   Constant *getPclmulMask(IRBuilder<> &IRB, unsigned Width, bool OddElements) {
3004     SmallVector<Constant *, 8> Mask;
3005     for (unsigned X = OddElements ? 1 : 0; X < Width; X += 2) {
3006       Constant *C = ConstantInt::get(IRB.getInt32Ty(), X);
3007       Mask.push_back(C);
3008       Mask.push_back(C);
3009     }
3010     return ConstantVector::get(Mask);
3011   }
3012 
3013   // Instrument pclmul intrinsics.
3014   // These intrinsics operate either on odd or on even elements of the input
3015   // vectors, depending on the constant in the 3rd argument, ignoring the rest.
3016   // Replace the unused elements with copies of the used ones, ex:
3017   //   (0, 1, 2, 3) -> (0, 0, 2, 2) (even case)
3018   // or
3019   //   (0, 1, 2, 3) -> (1, 1, 3, 3) (odd case)
3020   // and then apply the usual shadow combining logic.
3021   void handlePclmulIntrinsic(IntrinsicInst &I) {
3022     IRBuilder<> IRB(&I);
3023     Type *ShadowTy = getShadowTy(&I);
3024     unsigned Width = I.getArgOperand(0)->getType()->getVectorNumElements();
3025     assert(isa<ConstantInt>(I.getArgOperand(2)) &&
3026            "pclmul 3rd operand must be a constant");
3027     unsigned Imm = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3028     Value *Shuf0 =
3029         IRB.CreateShuffleVector(getShadow(&I, 0), UndefValue::get(ShadowTy),
3030                                 getPclmulMask(IRB, Width, Imm & 0x01));
3031     Value *Shuf1 =
3032         IRB.CreateShuffleVector(getShadow(&I, 1), UndefValue::get(ShadowTy),
3033                                 getPclmulMask(IRB, Width, Imm & 0x10));
3034     ShadowAndOriginCombiner SOC(this, IRB);
3035     SOC.Add(Shuf0, getOrigin(&I, 0));
3036     SOC.Add(Shuf1, getOrigin(&I, 1));
3037     SOC.Done(&I);
3038   }
3039 
3040   void visitIntrinsicInst(IntrinsicInst &I) {
3041     switch (I.getIntrinsicID()) {
3042     case Intrinsic::lifetime_start:
3043       handleLifetimeStart(I);
3044       break;
3045     case Intrinsic::launder_invariant_group:
3046     case Intrinsic::strip_invariant_group:
3047       handleInvariantGroup(I);
3048       break;
3049     case Intrinsic::bswap:
3050       handleBswap(I);
3051       break;
3052     case Intrinsic::masked_store:
3053       handleMaskedStore(I);
3054       break;
3055     case Intrinsic::masked_load:
3056       handleMaskedLoad(I);
3057       break;
3058     case Intrinsic::x86_sse_stmxcsr:
3059       handleStmxcsr(I);
3060       break;
3061     case Intrinsic::x86_sse_ldmxcsr:
3062       handleLdmxcsr(I);
3063       break;
3064     case Intrinsic::x86_avx512_vcvtsd2usi64:
3065     case Intrinsic::x86_avx512_vcvtsd2usi32:
3066     case Intrinsic::x86_avx512_vcvtss2usi64:
3067     case Intrinsic::x86_avx512_vcvtss2usi32:
3068     case Intrinsic::x86_avx512_cvttss2usi64:
3069     case Intrinsic::x86_avx512_cvttss2usi:
3070     case Intrinsic::x86_avx512_cvttsd2usi64:
3071     case Intrinsic::x86_avx512_cvttsd2usi:
3072     case Intrinsic::x86_avx512_cvtusi2ss:
3073     case Intrinsic::x86_avx512_cvtusi642sd:
3074     case Intrinsic::x86_avx512_cvtusi642ss:
3075     case Intrinsic::x86_sse2_cvtsd2si64:
3076     case Intrinsic::x86_sse2_cvtsd2si:
3077     case Intrinsic::x86_sse2_cvtsd2ss:
3078     case Intrinsic::x86_sse2_cvttsd2si64:
3079     case Intrinsic::x86_sse2_cvttsd2si:
3080     case Intrinsic::x86_sse_cvtss2si64:
3081     case Intrinsic::x86_sse_cvtss2si:
3082     case Intrinsic::x86_sse_cvttss2si64:
3083     case Intrinsic::x86_sse_cvttss2si:
3084       handleVectorConvertIntrinsic(I, 1);
3085       break;
3086     case Intrinsic::x86_sse_cvtps2pi:
3087     case Intrinsic::x86_sse_cvttps2pi:
3088       handleVectorConvertIntrinsic(I, 2);
3089       break;
3090 
3091     case Intrinsic::x86_avx512_psll_w_512:
3092     case Intrinsic::x86_avx512_psll_d_512:
3093     case Intrinsic::x86_avx512_psll_q_512:
3094     case Intrinsic::x86_avx512_pslli_w_512:
3095     case Intrinsic::x86_avx512_pslli_d_512:
3096     case Intrinsic::x86_avx512_pslli_q_512:
3097     case Intrinsic::x86_avx512_psrl_w_512:
3098     case Intrinsic::x86_avx512_psrl_d_512:
3099     case Intrinsic::x86_avx512_psrl_q_512:
3100     case Intrinsic::x86_avx512_psra_w_512:
3101     case Intrinsic::x86_avx512_psra_d_512:
3102     case Intrinsic::x86_avx512_psra_q_512:
3103     case Intrinsic::x86_avx512_psrli_w_512:
3104     case Intrinsic::x86_avx512_psrli_d_512:
3105     case Intrinsic::x86_avx512_psrli_q_512:
3106     case Intrinsic::x86_avx512_psrai_w_512:
3107     case Intrinsic::x86_avx512_psrai_d_512:
3108     case Intrinsic::x86_avx512_psrai_q_512:
3109     case Intrinsic::x86_avx512_psra_q_256:
3110     case Intrinsic::x86_avx512_psra_q_128:
3111     case Intrinsic::x86_avx512_psrai_q_256:
3112     case Intrinsic::x86_avx512_psrai_q_128:
3113     case Intrinsic::x86_avx2_psll_w:
3114     case Intrinsic::x86_avx2_psll_d:
3115     case Intrinsic::x86_avx2_psll_q:
3116     case Intrinsic::x86_avx2_pslli_w:
3117     case Intrinsic::x86_avx2_pslli_d:
3118     case Intrinsic::x86_avx2_pslli_q:
3119     case Intrinsic::x86_avx2_psrl_w:
3120     case Intrinsic::x86_avx2_psrl_d:
3121     case Intrinsic::x86_avx2_psrl_q:
3122     case Intrinsic::x86_avx2_psra_w:
3123     case Intrinsic::x86_avx2_psra_d:
3124     case Intrinsic::x86_avx2_psrli_w:
3125     case Intrinsic::x86_avx2_psrli_d:
3126     case Intrinsic::x86_avx2_psrli_q:
3127     case Intrinsic::x86_avx2_psrai_w:
3128     case Intrinsic::x86_avx2_psrai_d:
3129     case Intrinsic::x86_sse2_psll_w:
3130     case Intrinsic::x86_sse2_psll_d:
3131     case Intrinsic::x86_sse2_psll_q:
3132     case Intrinsic::x86_sse2_pslli_w:
3133     case Intrinsic::x86_sse2_pslli_d:
3134     case Intrinsic::x86_sse2_pslli_q:
3135     case Intrinsic::x86_sse2_psrl_w:
3136     case Intrinsic::x86_sse2_psrl_d:
3137     case Intrinsic::x86_sse2_psrl_q:
3138     case Intrinsic::x86_sse2_psra_w:
3139     case Intrinsic::x86_sse2_psra_d:
3140     case Intrinsic::x86_sse2_psrli_w:
3141     case Intrinsic::x86_sse2_psrli_d:
3142     case Intrinsic::x86_sse2_psrli_q:
3143     case Intrinsic::x86_sse2_psrai_w:
3144     case Intrinsic::x86_sse2_psrai_d:
3145     case Intrinsic::x86_mmx_psll_w:
3146     case Intrinsic::x86_mmx_psll_d:
3147     case Intrinsic::x86_mmx_psll_q:
3148     case Intrinsic::x86_mmx_pslli_w:
3149     case Intrinsic::x86_mmx_pslli_d:
3150     case Intrinsic::x86_mmx_pslli_q:
3151     case Intrinsic::x86_mmx_psrl_w:
3152     case Intrinsic::x86_mmx_psrl_d:
3153     case Intrinsic::x86_mmx_psrl_q:
3154     case Intrinsic::x86_mmx_psra_w:
3155     case Intrinsic::x86_mmx_psra_d:
3156     case Intrinsic::x86_mmx_psrli_w:
3157     case Intrinsic::x86_mmx_psrli_d:
3158     case Intrinsic::x86_mmx_psrli_q:
3159     case Intrinsic::x86_mmx_psrai_w:
3160     case Intrinsic::x86_mmx_psrai_d:
3161       handleVectorShiftIntrinsic(I, /* Variable */ false);
3162       break;
3163     case Intrinsic::x86_avx2_psllv_d:
3164     case Intrinsic::x86_avx2_psllv_d_256:
3165     case Intrinsic::x86_avx512_psllv_d_512:
3166     case Intrinsic::x86_avx2_psllv_q:
3167     case Intrinsic::x86_avx2_psllv_q_256:
3168     case Intrinsic::x86_avx512_psllv_q_512:
3169     case Intrinsic::x86_avx2_psrlv_d:
3170     case Intrinsic::x86_avx2_psrlv_d_256:
3171     case Intrinsic::x86_avx512_psrlv_d_512:
3172     case Intrinsic::x86_avx2_psrlv_q:
3173     case Intrinsic::x86_avx2_psrlv_q_256:
3174     case Intrinsic::x86_avx512_psrlv_q_512:
3175     case Intrinsic::x86_avx2_psrav_d:
3176     case Intrinsic::x86_avx2_psrav_d_256:
3177     case Intrinsic::x86_avx512_psrav_d_512:
3178     case Intrinsic::x86_avx512_psrav_q_128:
3179     case Intrinsic::x86_avx512_psrav_q_256:
3180     case Intrinsic::x86_avx512_psrav_q_512:
3181       handleVectorShiftIntrinsic(I, /* Variable */ true);
3182       break;
3183 
3184     case Intrinsic::x86_sse2_packsswb_128:
3185     case Intrinsic::x86_sse2_packssdw_128:
3186     case Intrinsic::x86_sse2_packuswb_128:
3187     case Intrinsic::x86_sse41_packusdw:
3188     case Intrinsic::x86_avx2_packsswb:
3189     case Intrinsic::x86_avx2_packssdw:
3190     case Intrinsic::x86_avx2_packuswb:
3191     case Intrinsic::x86_avx2_packusdw:
3192       handleVectorPackIntrinsic(I);
3193       break;
3194 
3195     case Intrinsic::x86_mmx_packsswb:
3196     case Intrinsic::x86_mmx_packuswb:
3197       handleVectorPackIntrinsic(I, 16);
3198       break;
3199 
3200     case Intrinsic::x86_mmx_packssdw:
3201       handleVectorPackIntrinsic(I, 32);
3202       break;
3203 
3204     case Intrinsic::x86_mmx_psad_bw:
3205     case Intrinsic::x86_sse2_psad_bw:
3206     case Intrinsic::x86_avx2_psad_bw:
3207       handleVectorSadIntrinsic(I);
3208       break;
3209 
3210     case Intrinsic::x86_sse2_pmadd_wd:
3211     case Intrinsic::x86_avx2_pmadd_wd:
3212     case Intrinsic::x86_ssse3_pmadd_ub_sw_128:
3213     case Intrinsic::x86_avx2_pmadd_ub_sw:
3214       handleVectorPmaddIntrinsic(I);
3215       break;
3216 
3217     case Intrinsic::x86_ssse3_pmadd_ub_sw:
3218       handleVectorPmaddIntrinsic(I, 8);
3219       break;
3220 
3221     case Intrinsic::x86_mmx_pmadd_wd:
3222       handleVectorPmaddIntrinsic(I, 16);
3223       break;
3224 
3225     case Intrinsic::x86_sse_cmp_ss:
3226     case Intrinsic::x86_sse2_cmp_sd:
3227     case Intrinsic::x86_sse_comieq_ss:
3228     case Intrinsic::x86_sse_comilt_ss:
3229     case Intrinsic::x86_sse_comile_ss:
3230     case Intrinsic::x86_sse_comigt_ss:
3231     case Intrinsic::x86_sse_comige_ss:
3232     case Intrinsic::x86_sse_comineq_ss:
3233     case Intrinsic::x86_sse_ucomieq_ss:
3234     case Intrinsic::x86_sse_ucomilt_ss:
3235     case Intrinsic::x86_sse_ucomile_ss:
3236     case Intrinsic::x86_sse_ucomigt_ss:
3237     case Intrinsic::x86_sse_ucomige_ss:
3238     case Intrinsic::x86_sse_ucomineq_ss:
3239     case Intrinsic::x86_sse2_comieq_sd:
3240     case Intrinsic::x86_sse2_comilt_sd:
3241     case Intrinsic::x86_sse2_comile_sd:
3242     case Intrinsic::x86_sse2_comigt_sd:
3243     case Intrinsic::x86_sse2_comige_sd:
3244     case Intrinsic::x86_sse2_comineq_sd:
3245     case Intrinsic::x86_sse2_ucomieq_sd:
3246     case Intrinsic::x86_sse2_ucomilt_sd:
3247     case Intrinsic::x86_sse2_ucomile_sd:
3248     case Intrinsic::x86_sse2_ucomigt_sd:
3249     case Intrinsic::x86_sse2_ucomige_sd:
3250     case Intrinsic::x86_sse2_ucomineq_sd:
3251       handleVectorCompareScalarIntrinsic(I);
3252       break;
3253 
3254     case Intrinsic::x86_sse_cmp_ps:
3255     case Intrinsic::x86_sse2_cmp_pd:
3256       // FIXME: For x86_avx_cmp_pd_256 and x86_avx_cmp_ps_256 this function
3257       // generates reasonably looking IR that fails in the backend with "Do not
3258       // know how to split the result of this operator!".
3259       handleVectorComparePackedIntrinsic(I);
3260       break;
3261 
3262     case Intrinsic::x86_bmi_bextr_32:
3263     case Intrinsic::x86_bmi_bextr_64:
3264     case Intrinsic::x86_bmi_bzhi_32:
3265     case Intrinsic::x86_bmi_bzhi_64:
3266     case Intrinsic::x86_bmi_pdep_32:
3267     case Intrinsic::x86_bmi_pdep_64:
3268     case Intrinsic::x86_bmi_pext_32:
3269     case Intrinsic::x86_bmi_pext_64:
3270       handleBmiIntrinsic(I);
3271       break;
3272 
3273     case Intrinsic::x86_pclmulqdq:
3274     case Intrinsic::x86_pclmulqdq_256:
3275     case Intrinsic::x86_pclmulqdq_512:
3276       handlePclmulIntrinsic(I);
3277       break;
3278 
3279     case Intrinsic::is_constant:
3280       // The result of llvm.is.constant() is always defined.
3281       setShadow(&I, getCleanShadow(&I));
3282       setOrigin(&I, getCleanOrigin());
3283       break;
3284 
3285     default:
3286       if (!handleUnknownIntrinsic(I))
3287         visitInstruction(I);
3288       break;
3289     }
3290   }
3291 
3292   void visitCallSite(CallSite CS) {
3293     Instruction &I = *CS.getInstruction();
3294     assert(!I.getMetadata("nosanitize"));
3295     assert((CS.isCall() || CS.isInvoke() || CS.isCallBr()) &&
3296            "Unknown type of CallSite");
3297     if (CS.isCallBr() || (CS.isCall() && cast<CallInst>(&I)->isInlineAsm())) {
3298       // For inline asm (either a call to asm function, or callbr instruction),
3299       // do the usual thing: check argument shadow and mark all outputs as
3300       // clean. Note that any side effects of the inline asm that are not
3301       // immediately visible in its constraints are not handled.
3302       if (ClHandleAsmConservative && MS.CompileKernel)
3303         visitAsmInstruction(I);
3304       else
3305         visitInstruction(I);
3306       return;
3307     }
3308     if (CS.isCall()) {
3309       CallInst *Call = cast<CallInst>(&I);
3310       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
3311 
3312       // We are going to insert code that relies on the fact that the callee
3313       // will become a non-readonly function after it is instrumented by us. To
3314       // prevent this code from being optimized out, mark that function
3315       // non-readonly in advance.
3316       if (Function *Func = Call->getCalledFunction()) {
3317         // Clear out readonly/readnone attributes.
3318         AttrBuilder B;
3319         B.addAttribute(Attribute::ReadOnly)
3320             .addAttribute(Attribute::ReadNone)
3321             .addAttribute(Attribute::WriteOnly)
3322             .addAttribute(Attribute::ArgMemOnly)
3323             .addAttribute(Attribute::Speculatable);
3324         Func->removeAttributes(AttributeList::FunctionIndex, B);
3325       }
3326 
3327       maybeMarkSanitizerLibraryCallNoBuiltin(Call, TLI);
3328     }
3329     IRBuilder<> IRB(&I);
3330 
3331     unsigned ArgOffset = 0;
3332     LLVM_DEBUG(dbgs() << "  CallSite: " << I << "\n");
3333     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
3334          ArgIt != End; ++ArgIt) {
3335       Value *A = *ArgIt;
3336       unsigned i = ArgIt - CS.arg_begin();
3337       if (!A->getType()->isSized()) {
3338         LLVM_DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
3339         continue;
3340       }
3341       unsigned Size = 0;
3342       Value *Store = nullptr;
3343       // Compute the Shadow for arg even if it is ByVal, because
3344       // in that case getShadow() will copy the actual arg shadow to
3345       // __msan_param_tls.
3346       Value *ArgShadow = getShadow(A);
3347       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
3348       LLVM_DEBUG(dbgs() << "  Arg#" << i << ": " << *A
3349                         << " Shadow: " << *ArgShadow << "\n");
3350       bool ArgIsInitialized = false;
3351       const DataLayout &DL = F.getParent()->getDataLayout();
3352       if (CS.paramHasAttr(i, Attribute::ByVal)) {
3353         assert(A->getType()->isPointerTy() &&
3354                "ByVal argument is not a pointer!");
3355         Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
3356         if (ArgOffset + Size > kParamTLSSize) break;
3357         const MaybeAlign ParamAlignment(CS.getParamAlignment(i));
3358         MaybeAlign Alignment = llvm::None;
3359         if (ParamAlignment)
3360           Alignment = std::min(*ParamAlignment, kShadowTLSAlignment);
3361         Value *AShadowPtr =
3362             getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), Alignment,
3363                                /*isStore*/ false)
3364                 .first;
3365 
3366         Store = IRB.CreateMemCpy(ArgShadowBase, Alignment, AShadowPtr,
3367                                  Alignment, Size);
3368         // TODO(glider): need to copy origins.
3369       } else {
3370         Size = DL.getTypeAllocSize(A->getType());
3371         if (ArgOffset + Size > kParamTLSSize) break;
3372         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
3373                                        kShadowTLSAlignment);
3374         Constant *Cst = dyn_cast<Constant>(ArgShadow);
3375         if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
3376       }
3377       if (MS.TrackOrigins && !ArgIsInitialized)
3378         IRB.CreateStore(getOrigin(A),
3379                         getOriginPtrForArgument(A, IRB, ArgOffset));
3380       (void)Store;
3381       assert(Size != 0 && Store != nullptr);
3382       LLVM_DEBUG(dbgs() << "  Param:" << *Store << "\n");
3383       ArgOffset += alignTo(Size, 8);
3384     }
3385     LLVM_DEBUG(dbgs() << "  done with call args\n");
3386 
3387     FunctionType *FT = CS.getFunctionType();
3388     if (FT->isVarArg()) {
3389       VAHelper->visitCallSite(CS, IRB);
3390     }
3391 
3392     // Now, get the shadow for the RetVal.
3393     if (!I.getType()->isSized()) return;
3394     // Don't emit the epilogue for musttail call returns.
3395     if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
3396     IRBuilder<> IRBBefore(&I);
3397     // Until we have full dynamic coverage, make sure the retval shadow is 0.
3398     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
3399     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
3400     BasicBlock::iterator NextInsn;
3401     if (CS.isCall()) {
3402       NextInsn = ++I.getIterator();
3403       assert(NextInsn != I.getParent()->end());
3404     } else {
3405       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
3406       if (!NormalDest->getSinglePredecessor()) {
3407         // FIXME: this case is tricky, so we are just conservative here.
3408         // Perhaps we need to split the edge between this BB and NormalDest,
3409         // but a naive attempt to use SplitEdge leads to a crash.
3410         setShadow(&I, getCleanShadow(&I));
3411         setOrigin(&I, getCleanOrigin());
3412         return;
3413       }
3414       // FIXME: NextInsn is likely in a basic block that has not been visited yet.
3415       // Anything inserted there will be instrumented by MSan later!
3416       NextInsn = NormalDest->getFirstInsertionPt();
3417       assert(NextInsn != NormalDest->end() &&
3418              "Could not find insertion point for retval shadow load");
3419     }
3420     IRBuilder<> IRBAfter(&*NextInsn);
3421     Value *RetvalShadow = IRBAfter.CreateAlignedLoad(
3422         getShadowTy(&I), getShadowPtrForRetval(&I, IRBAfter),
3423         kShadowTLSAlignment, "_msret");
3424     setShadow(&I, RetvalShadow);
3425     if (MS.TrackOrigins)
3426       setOrigin(&I, IRBAfter.CreateLoad(MS.OriginTy,
3427                                         getOriginPtrForRetval(IRBAfter)));
3428   }
3429 
3430   bool isAMustTailRetVal(Value *RetVal) {
3431     if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
3432       RetVal = I->getOperand(0);
3433     }
3434     if (auto *I = dyn_cast<CallInst>(RetVal)) {
3435       return I->isMustTailCall();
3436     }
3437     return false;
3438   }
3439 
3440   void visitReturnInst(ReturnInst &I) {
3441     IRBuilder<> IRB(&I);
3442     Value *RetVal = I.getReturnValue();
3443     if (!RetVal) return;
3444     // Don't emit the epilogue for musttail call returns.
3445     if (isAMustTailRetVal(RetVal)) return;
3446     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
3447     if (CheckReturnValue) {
3448       insertShadowCheck(RetVal, &I);
3449       Value *Shadow = getCleanShadow(RetVal);
3450       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
3451     } else {
3452       Value *Shadow = getShadow(RetVal);
3453       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
3454       if (MS.TrackOrigins)
3455         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
3456     }
3457   }
3458 
3459   void visitPHINode(PHINode &I) {
3460     IRBuilder<> IRB(&I);
3461     if (!PropagateShadow) {
3462       setShadow(&I, getCleanShadow(&I));
3463       setOrigin(&I, getCleanOrigin());
3464       return;
3465     }
3466 
3467     ShadowPHINodes.push_back(&I);
3468     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
3469                                 "_msphi_s"));
3470     if (MS.TrackOrigins)
3471       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
3472                                   "_msphi_o"));
3473   }
3474 
3475   Value *getLocalVarDescription(AllocaInst &I) {
3476     SmallString<2048> StackDescriptionStorage;
3477     raw_svector_ostream StackDescription(StackDescriptionStorage);
3478     // We create a string with a description of the stack allocation and
3479     // pass it into __msan_set_alloca_origin.
3480     // It will be printed by the run-time if stack-originated UMR is found.
3481     // The first 4 bytes of the string are set to '----' and will be replaced
3482     // by __msan_va_arg_overflow_size_tls at the first call.
3483     StackDescription << "----" << I.getName() << "@" << F.getName();
3484     return createPrivateNonConstGlobalForString(*F.getParent(),
3485                                                 StackDescription.str());
3486   }
3487 
3488   void poisonAllocaUserspace(AllocaInst &I, IRBuilder<> &IRB, Value *Len) {
3489     if (PoisonStack && ClPoisonStackWithCall) {
3490       IRB.CreateCall(MS.MsanPoisonStackFn,
3491                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len});
3492     } else {
3493       Value *ShadowBase, *OriginBase;
3494       std::tie(ShadowBase, OriginBase) = getShadowOriginPtr(
3495           &I, IRB, IRB.getInt8Ty(), Align(1), /*isStore*/ true);
3496 
3497       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
3498       IRB.CreateMemSet(ShadowBase, PoisonValue, Len,
3499                        MaybeAlign(I.getAlignment()));
3500     }
3501 
3502     if (PoisonStack && MS.TrackOrigins) {
3503       Value *Descr = getLocalVarDescription(I);
3504       IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
3505                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len,
3506                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
3507                       IRB.CreatePointerCast(&F, MS.IntptrTy)});
3508     }
3509   }
3510 
3511   void poisonAllocaKmsan(AllocaInst &I, IRBuilder<> &IRB, Value *Len) {
3512     Value *Descr = getLocalVarDescription(I);
3513     if (PoisonStack) {
3514       IRB.CreateCall(MS.MsanPoisonAllocaFn,
3515                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len,
3516                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy())});
3517     } else {
3518       IRB.CreateCall(MS.MsanUnpoisonAllocaFn,
3519                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len});
3520     }
3521   }
3522 
3523   void instrumentAlloca(AllocaInst &I, Instruction *InsPoint = nullptr) {
3524     if (!InsPoint)
3525       InsPoint = &I;
3526     IRBuilder<> IRB(InsPoint->getNextNode());
3527     const DataLayout &DL = F.getParent()->getDataLayout();
3528     uint64_t TypeSize = DL.getTypeAllocSize(I.getAllocatedType());
3529     Value *Len = ConstantInt::get(MS.IntptrTy, TypeSize);
3530     if (I.isArrayAllocation())
3531       Len = IRB.CreateMul(Len, I.getArraySize());
3532 
3533     if (MS.CompileKernel)
3534       poisonAllocaKmsan(I, IRB, Len);
3535     else
3536       poisonAllocaUserspace(I, IRB, Len);
3537   }
3538 
3539   void visitAllocaInst(AllocaInst &I) {
3540     setShadow(&I, getCleanShadow(&I));
3541     setOrigin(&I, getCleanOrigin());
3542     // We'll get to this alloca later unless it's poisoned at the corresponding
3543     // llvm.lifetime.start.
3544     AllocaSet.insert(&I);
3545   }
3546 
3547   void visitSelectInst(SelectInst& I) {
3548     IRBuilder<> IRB(&I);
3549     // a = select b, c, d
3550     Value *B = I.getCondition();
3551     Value *C = I.getTrueValue();
3552     Value *D = I.getFalseValue();
3553     Value *Sb = getShadow(B);
3554     Value *Sc = getShadow(C);
3555     Value *Sd = getShadow(D);
3556 
3557     // Result shadow if condition shadow is 0.
3558     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
3559     Value *Sa1;
3560     if (I.getType()->isAggregateType()) {
3561       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
3562       // an extra "select". This results in much more compact IR.
3563       // Sa = select Sb, poisoned, (select b, Sc, Sd)
3564       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
3565     } else {
3566       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
3567       // If Sb (condition is poisoned), look for bits in c and d that are equal
3568       // and both unpoisoned.
3569       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
3570 
3571       // Cast arguments to shadow-compatible type.
3572       C = CreateAppToShadowCast(IRB, C);
3573       D = CreateAppToShadowCast(IRB, D);
3574 
3575       // Result shadow if condition shadow is 1.
3576       Sa1 = IRB.CreateOr({IRB.CreateXor(C, D), Sc, Sd});
3577     }
3578     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
3579     setShadow(&I, Sa);
3580     if (MS.TrackOrigins) {
3581       // Origins are always i32, so any vector conditions must be flattened.
3582       // FIXME: consider tracking vector origins for app vectors?
3583       if (B->getType()->isVectorTy()) {
3584         Type *FlatTy = getShadowTyNoVec(B->getType());
3585         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
3586                                 ConstantInt::getNullValue(FlatTy));
3587         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
3588                                       ConstantInt::getNullValue(FlatTy));
3589       }
3590       // a = select b, c, d
3591       // Oa = Sb ? Ob : (b ? Oc : Od)
3592       setOrigin(
3593           &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
3594                                IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
3595                                                 getOrigin(I.getFalseValue()))));
3596     }
3597   }
3598 
3599   void visitLandingPadInst(LandingPadInst &I) {
3600     // Do nothing.
3601     // See https://github.com/google/sanitizers/issues/504
3602     setShadow(&I, getCleanShadow(&I));
3603     setOrigin(&I, getCleanOrigin());
3604   }
3605 
3606   void visitCatchSwitchInst(CatchSwitchInst &I) {
3607     setShadow(&I, getCleanShadow(&I));
3608     setOrigin(&I, getCleanOrigin());
3609   }
3610 
3611   void visitFuncletPadInst(FuncletPadInst &I) {
3612     setShadow(&I, getCleanShadow(&I));
3613     setOrigin(&I, getCleanOrigin());
3614   }
3615 
3616   void visitGetElementPtrInst(GetElementPtrInst &I) {
3617     handleShadowOr(I);
3618   }
3619 
3620   void visitExtractValueInst(ExtractValueInst &I) {
3621     IRBuilder<> IRB(&I);
3622     Value *Agg = I.getAggregateOperand();
3623     LLVM_DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
3624     Value *AggShadow = getShadow(Agg);
3625     LLVM_DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
3626     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
3627     LLVM_DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
3628     setShadow(&I, ResShadow);
3629     setOriginForNaryOp(I);
3630   }
3631 
3632   void visitInsertValueInst(InsertValueInst &I) {
3633     IRBuilder<> IRB(&I);
3634     LLVM_DEBUG(dbgs() << "InsertValue:  " << I << "\n");
3635     Value *AggShadow = getShadow(I.getAggregateOperand());
3636     Value *InsShadow = getShadow(I.getInsertedValueOperand());
3637     LLVM_DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
3638     LLVM_DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
3639     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
3640     LLVM_DEBUG(dbgs() << "   Res:        " << *Res << "\n");
3641     setShadow(&I, Res);
3642     setOriginForNaryOp(I);
3643   }
3644 
3645   void dumpInst(Instruction &I) {
3646     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
3647       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
3648     } else {
3649       errs() << "ZZZ " << I.getOpcodeName() << "\n";
3650     }
3651     errs() << "QQQ " << I << "\n";
3652   }
3653 
3654   void visitResumeInst(ResumeInst &I) {
3655     LLVM_DEBUG(dbgs() << "Resume: " << I << "\n");
3656     // Nothing to do here.
3657   }
3658 
3659   void visitCleanupReturnInst(CleanupReturnInst &CRI) {
3660     LLVM_DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
3661     // Nothing to do here.
3662   }
3663 
3664   void visitCatchReturnInst(CatchReturnInst &CRI) {
3665     LLVM_DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
3666     // Nothing to do here.
3667   }
3668 
3669   void instrumentAsmArgument(Value *Operand, Instruction &I, IRBuilder<> &IRB,
3670                              const DataLayout &DL, bool isOutput) {
3671     // For each assembly argument, we check its value for being initialized.
3672     // If the argument is a pointer, we assume it points to a single element
3673     // of the corresponding type (or to a 8-byte word, if the type is unsized).
3674     // Each such pointer is instrumented with a call to the runtime library.
3675     Type *OpType = Operand->getType();
3676     // Check the operand value itself.
3677     insertShadowCheck(Operand, &I);
3678     if (!OpType->isPointerTy() || !isOutput) {
3679       assert(!isOutput);
3680       return;
3681     }
3682     Type *ElType = OpType->getPointerElementType();
3683     if (!ElType->isSized())
3684       return;
3685     int Size = DL.getTypeStoreSize(ElType);
3686     Value *Ptr = IRB.CreatePointerCast(Operand, IRB.getInt8PtrTy());
3687     Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size);
3688     IRB.CreateCall(MS.MsanInstrumentAsmStoreFn, {Ptr, SizeVal});
3689   }
3690 
3691   /// Get the number of output arguments returned by pointers.
3692   int getNumOutputArgs(InlineAsm *IA, CallBase *CB) {
3693     int NumRetOutputs = 0;
3694     int NumOutputs = 0;
3695     Type *RetTy = cast<Value>(CB)->getType();
3696     if (!RetTy->isVoidTy()) {
3697       // Register outputs are returned via the CallInst return value.
3698       auto *ST = dyn_cast<StructType>(RetTy);
3699       if (ST)
3700         NumRetOutputs = ST->getNumElements();
3701       else
3702         NumRetOutputs = 1;
3703     }
3704     InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
3705     for (size_t i = 0, n = Constraints.size(); i < n; i++) {
3706       InlineAsm::ConstraintInfo Info = Constraints[i];
3707       switch (Info.Type) {
3708       case InlineAsm::isOutput:
3709         NumOutputs++;
3710         break;
3711       default:
3712         break;
3713       }
3714     }
3715     return NumOutputs - NumRetOutputs;
3716   }
3717 
3718   void visitAsmInstruction(Instruction &I) {
3719     // Conservative inline assembly handling: check for poisoned shadow of
3720     // asm() arguments, then unpoison the result and all the memory locations
3721     // pointed to by those arguments.
3722     // An inline asm() statement in C++ contains lists of input and output
3723     // arguments used by the assembly code. These are mapped to operands of the
3724     // CallInst as follows:
3725     //  - nR register outputs ("=r) are returned by value in a single structure
3726     //  (SSA value of the CallInst);
3727     //  - nO other outputs ("=m" and others) are returned by pointer as first
3728     // nO operands of the CallInst;
3729     //  - nI inputs ("r", "m" and others) are passed to CallInst as the
3730     // remaining nI operands.
3731     // The total number of asm() arguments in the source is nR+nO+nI, and the
3732     // corresponding CallInst has nO+nI+1 operands (the last operand is the
3733     // function to be called).
3734     const DataLayout &DL = F.getParent()->getDataLayout();
3735     CallBase *CB = cast<CallBase>(&I);
3736     IRBuilder<> IRB(&I);
3737     InlineAsm *IA = cast<InlineAsm>(CB->getCalledValue());
3738     int OutputArgs = getNumOutputArgs(IA, CB);
3739     // The last operand of a CallInst is the function itself.
3740     int NumOperands = CB->getNumOperands() - 1;
3741 
3742     // Check input arguments. Doing so before unpoisoning output arguments, so
3743     // that we won't overwrite uninit values before checking them.
3744     for (int i = OutputArgs; i < NumOperands; i++) {
3745       Value *Operand = CB->getOperand(i);
3746       instrumentAsmArgument(Operand, I, IRB, DL, /*isOutput*/ false);
3747     }
3748     // Unpoison output arguments. This must happen before the actual InlineAsm
3749     // call, so that the shadow for memory published in the asm() statement
3750     // remains valid.
3751     for (int i = 0; i < OutputArgs; i++) {
3752       Value *Operand = CB->getOperand(i);
3753       instrumentAsmArgument(Operand, I, IRB, DL, /*isOutput*/ true);
3754     }
3755 
3756     setShadow(&I, getCleanShadow(&I));
3757     setOrigin(&I, getCleanOrigin());
3758   }
3759 
3760   void visitInstruction(Instruction &I) {
3761     // Everything else: stop propagating and check for poisoned shadow.
3762     if (ClDumpStrictInstructions)
3763       dumpInst(I);
3764     LLVM_DEBUG(dbgs() << "DEFAULT: " << I << "\n");
3765     for (size_t i = 0, n = I.getNumOperands(); i < n; i++) {
3766       Value *Operand = I.getOperand(i);
3767       if (Operand->getType()->isSized())
3768         insertShadowCheck(Operand, &I);
3769     }
3770     setShadow(&I, getCleanShadow(&I));
3771     setOrigin(&I, getCleanOrigin());
3772   }
3773 };
3774 
3775 /// AMD64-specific implementation of VarArgHelper.
3776 struct VarArgAMD64Helper : public VarArgHelper {
3777   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
3778   // See a comment in visitCallSite for more details.
3779   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
3780   static const unsigned AMD64FpEndOffsetSSE = 176;
3781   // If SSE is disabled, fp_offset in va_list is zero.
3782   static const unsigned AMD64FpEndOffsetNoSSE = AMD64GpEndOffset;
3783 
3784   unsigned AMD64FpEndOffset;
3785   Function &F;
3786   MemorySanitizer &MS;
3787   MemorySanitizerVisitor &MSV;
3788   Value *VAArgTLSCopy = nullptr;
3789   Value *VAArgTLSOriginCopy = nullptr;
3790   Value *VAArgOverflowSize = nullptr;
3791 
3792   SmallVector<CallInst*, 16> VAStartInstrumentationList;
3793 
3794   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
3795 
3796   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
3797                     MemorySanitizerVisitor &MSV)
3798       : F(F), MS(MS), MSV(MSV) {
3799     AMD64FpEndOffset = AMD64FpEndOffsetSSE;
3800     for (const auto &Attr : F.getAttributes().getFnAttributes()) {
3801       if (Attr.isStringAttribute() &&
3802           (Attr.getKindAsString() == "target-features")) {
3803         if (Attr.getValueAsString().contains("-sse"))
3804           AMD64FpEndOffset = AMD64FpEndOffsetNoSSE;
3805         break;
3806       }
3807     }
3808   }
3809 
3810   ArgKind classifyArgument(Value* arg) {
3811     // A very rough approximation of X86_64 argument classification rules.
3812     Type *T = arg->getType();
3813     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
3814       return AK_FloatingPoint;
3815     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
3816       return AK_GeneralPurpose;
3817     if (T->isPointerTy())
3818       return AK_GeneralPurpose;
3819     return AK_Memory;
3820   }
3821 
3822   // For VarArg functions, store the argument shadow in an ABI-specific format
3823   // that corresponds to va_list layout.
3824   // We do this because Clang lowers va_arg in the frontend, and this pass
3825   // only sees the low level code that deals with va_list internals.
3826   // A much easier alternative (provided that Clang emits va_arg instructions)
3827   // would have been to associate each live instance of va_list with a copy of
3828   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
3829   // order.
3830   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
3831     unsigned GpOffset = 0;
3832     unsigned FpOffset = AMD64GpEndOffset;
3833     unsigned OverflowOffset = AMD64FpEndOffset;
3834     const DataLayout &DL = F.getParent()->getDataLayout();
3835     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
3836          ArgIt != End; ++ArgIt) {
3837       Value *A = *ArgIt;
3838       unsigned ArgNo = CS.getArgumentNo(ArgIt);
3839       bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
3840       bool IsByVal = CS.paramHasAttr(ArgNo, Attribute::ByVal);
3841       if (IsByVal) {
3842         // ByVal arguments always go to the overflow area.
3843         // Fixed arguments passed through the overflow area will be stepped
3844         // over by va_start, so don't count them towards the offset.
3845         if (IsFixed)
3846           continue;
3847         assert(A->getType()->isPointerTy());
3848         Type *RealTy = A->getType()->getPointerElementType();
3849         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
3850         Value *ShadowBase = getShadowPtrForVAArgument(
3851             RealTy, IRB, OverflowOffset, alignTo(ArgSize, 8));
3852         Value *OriginBase = nullptr;
3853         if (MS.TrackOrigins)
3854           OriginBase = getOriginPtrForVAArgument(RealTy, IRB, OverflowOffset);
3855         OverflowOffset += alignTo(ArgSize, 8);
3856         if (!ShadowBase)
3857           continue;
3858         Value *ShadowPtr, *OriginPtr;
3859         std::tie(ShadowPtr, OriginPtr) =
3860             MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), kShadowTLSAlignment,
3861                                    /*isStore*/ false);
3862 
3863         IRB.CreateMemCpy(ShadowBase, kShadowTLSAlignment, ShadowPtr,
3864                          kShadowTLSAlignment, ArgSize);
3865         if (MS.TrackOrigins)
3866           IRB.CreateMemCpy(OriginBase, kShadowTLSAlignment, OriginPtr,
3867                            kShadowTLSAlignment, ArgSize);
3868       } else {
3869         ArgKind AK = classifyArgument(A);
3870         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
3871           AK = AK_Memory;
3872         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
3873           AK = AK_Memory;
3874         Value *ShadowBase, *OriginBase = nullptr;
3875         switch (AK) {
3876           case AK_GeneralPurpose:
3877             ShadowBase =
3878                 getShadowPtrForVAArgument(A->getType(), IRB, GpOffset, 8);
3879             if (MS.TrackOrigins)
3880               OriginBase =
3881                   getOriginPtrForVAArgument(A->getType(), IRB, GpOffset);
3882             GpOffset += 8;
3883             break;
3884           case AK_FloatingPoint:
3885             ShadowBase =
3886                 getShadowPtrForVAArgument(A->getType(), IRB, FpOffset, 16);
3887             if (MS.TrackOrigins)
3888               OriginBase =
3889                   getOriginPtrForVAArgument(A->getType(), IRB, FpOffset);
3890             FpOffset += 16;
3891             break;
3892           case AK_Memory:
3893             if (IsFixed)
3894               continue;
3895             uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
3896             ShadowBase =
3897                 getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset, 8);
3898             if (MS.TrackOrigins)
3899               OriginBase =
3900                   getOriginPtrForVAArgument(A->getType(), IRB, OverflowOffset);
3901             OverflowOffset += alignTo(ArgSize, 8);
3902         }
3903         // Take fixed arguments into account for GpOffset and FpOffset,
3904         // but don't actually store shadows for them.
3905         // TODO(glider): don't call get*PtrForVAArgument() for them.
3906         if (IsFixed)
3907           continue;
3908         if (!ShadowBase)
3909           continue;
3910         Value *Shadow = MSV.getShadow(A);
3911         IRB.CreateAlignedStore(Shadow, ShadowBase, kShadowTLSAlignment);
3912         if (MS.TrackOrigins) {
3913           Value *Origin = MSV.getOrigin(A);
3914           unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
3915           MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize,
3916                           std::max(kShadowTLSAlignment, kMinOriginAlignment));
3917         }
3918       }
3919     }
3920     Constant *OverflowSize =
3921       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
3922     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
3923   }
3924 
3925   /// Compute the shadow address for a given va_arg.
3926   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3927                                    unsigned ArgOffset, unsigned ArgSize) {
3928     // Make sure we don't overflow __msan_va_arg_tls.
3929     if (ArgOffset + ArgSize > kParamTLSSize)
3930       return nullptr;
3931     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3932     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3933     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3934                               "_msarg_va_s");
3935   }
3936 
3937   /// Compute the origin address for a given va_arg.
3938   Value *getOriginPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, int ArgOffset) {
3939     Value *Base = IRB.CreatePointerCast(MS.VAArgOriginTLS, MS.IntptrTy);
3940     // getOriginPtrForVAArgument() is always called after
3941     // getShadowPtrForVAArgument(), so __msan_va_arg_origin_tls can never
3942     // overflow.
3943     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3944     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
3945                               "_msarg_va_o");
3946   }
3947 
3948   void unpoisonVAListTagForInst(IntrinsicInst &I) {
3949     IRBuilder<> IRB(&I);
3950     Value *VAListTag = I.getArgOperand(0);
3951     Value *ShadowPtr, *OriginPtr;
3952     const Align Alignment = Align(8);
3953     std::tie(ShadowPtr, OriginPtr) =
3954         MSV.getShadowOriginPtr(VAListTag, IRB, IRB.getInt8Ty(), Alignment,
3955                                /*isStore*/ true);
3956 
3957     // Unpoison the whole __va_list_tag.
3958     // FIXME: magic ABI constants.
3959     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3960                      /* size */ 24, Alignment, false);
3961     // We shouldn't need to zero out the origins, as they're only checked for
3962     // nonzero shadow.
3963   }
3964 
3965   void visitVAStartInst(VAStartInst &I) override {
3966     if (F.getCallingConv() == CallingConv::Win64)
3967       return;
3968     VAStartInstrumentationList.push_back(&I);
3969     unpoisonVAListTagForInst(I);
3970   }
3971 
3972   void visitVACopyInst(VACopyInst &I) override {
3973     if (F.getCallingConv() == CallingConv::Win64) return;
3974     unpoisonVAListTagForInst(I);
3975   }
3976 
3977   void finalizeInstrumentation() override {
3978     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
3979            "finalizeInstrumentation called twice");
3980     if (!VAStartInstrumentationList.empty()) {
3981       // If there is a va_start in this function, make a backup copy of
3982       // va_arg_tls somewhere in the function entry block.
3983       IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
3984       VAArgOverflowSize =
3985           IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
3986       Value *CopySize =
3987         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
3988                       VAArgOverflowSize);
3989       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3990       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
3991       if (MS.TrackOrigins) {
3992         VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3993         IRB.CreateMemCpy(VAArgTLSOriginCopy, Align(8), MS.VAArgOriginTLS,
3994                          Align(8), CopySize);
3995       }
3996     }
3997 
3998     // Instrument va_start.
3999     // Copy va_list shadow from the backup copy of the TLS contents.
4000     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4001       CallInst *OrigInst = VAStartInstrumentationList[i];
4002       IRBuilder<> IRB(OrigInst->getNextNode());
4003       Value *VAListTag = OrigInst->getArgOperand(0);
4004 
4005       Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4006       Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr(
4007           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4008                         ConstantInt::get(MS.IntptrTy, 16)),
4009           PointerType::get(RegSaveAreaPtrTy, 0));
4010       Value *RegSaveAreaPtr =
4011           IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr);
4012       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
4013       const Align Alignment = Align(16);
4014       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
4015           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4016                                  Alignment, /*isStore*/ true);
4017       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
4018                        AMD64FpEndOffset);
4019       if (MS.TrackOrigins)
4020         IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy,
4021                          Alignment, AMD64FpEndOffset);
4022       Type *OverflowArgAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4023       Value *OverflowArgAreaPtrPtr = IRB.CreateIntToPtr(
4024           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4025                         ConstantInt::get(MS.IntptrTy, 8)),
4026           PointerType::get(OverflowArgAreaPtrTy, 0));
4027       Value *OverflowArgAreaPtr =
4028           IRB.CreateLoad(OverflowArgAreaPtrTy, OverflowArgAreaPtrPtr);
4029       Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr;
4030       std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) =
4031           MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(),
4032                                  Alignment, /*isStore*/ true);
4033       Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
4034                                              AMD64FpEndOffset);
4035       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment,
4036                        VAArgOverflowSize);
4037       if (MS.TrackOrigins) {
4038         SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy,
4039                                         AMD64FpEndOffset);
4040         IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment,
4041                          VAArgOverflowSize);
4042       }
4043     }
4044   }
4045 };
4046 
4047 /// MIPS64-specific implementation of VarArgHelper.
4048 struct VarArgMIPS64Helper : public VarArgHelper {
4049   Function &F;
4050   MemorySanitizer &MS;
4051   MemorySanitizerVisitor &MSV;
4052   Value *VAArgTLSCopy = nullptr;
4053   Value *VAArgSize = nullptr;
4054 
4055   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4056 
4057   VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
4058                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4059 
4060   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
4061     unsigned VAArgOffset = 0;
4062     const DataLayout &DL = F.getParent()->getDataLayout();
4063     for (CallSite::arg_iterator ArgIt = CS.arg_begin() +
4064          CS.getFunctionType()->getNumParams(), End = CS.arg_end();
4065          ArgIt != End; ++ArgIt) {
4066       Triple TargetTriple(F.getParent()->getTargetTriple());
4067       Value *A = *ArgIt;
4068       Value *Base;
4069       uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4070       if (TargetTriple.getArch() == Triple::mips64) {
4071         // Adjusting the shadow for argument with size < 8 to match the placement
4072         // of bits in big endian system
4073         if (ArgSize < 8)
4074           VAArgOffset += (8 - ArgSize);
4075       }
4076       Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset, ArgSize);
4077       VAArgOffset += ArgSize;
4078       VAArgOffset = alignTo(VAArgOffset, 8);
4079       if (!Base)
4080         continue;
4081       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4082     }
4083 
4084     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
4085     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
4086     // a new class member i.e. it is the total size of all VarArgs.
4087     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
4088   }
4089 
4090   /// Compute the shadow address for a given va_arg.
4091   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4092                                    unsigned ArgOffset, unsigned ArgSize) {
4093     // Make sure we don't overflow __msan_va_arg_tls.
4094     if (ArgOffset + ArgSize > kParamTLSSize)
4095       return nullptr;
4096     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4097     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4098     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4099                               "_msarg");
4100   }
4101 
4102   void visitVAStartInst(VAStartInst &I) override {
4103     IRBuilder<> IRB(&I);
4104     VAStartInstrumentationList.push_back(&I);
4105     Value *VAListTag = I.getArgOperand(0);
4106     Value *ShadowPtr, *OriginPtr;
4107     const Align Alignment = Align(8);
4108     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4109         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4110     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4111                      /* size */ 8, Alignment, false);
4112   }
4113 
4114   void visitVACopyInst(VACopyInst &I) override {
4115     IRBuilder<> IRB(&I);
4116     VAStartInstrumentationList.push_back(&I);
4117     Value *VAListTag = I.getArgOperand(0);
4118     Value *ShadowPtr, *OriginPtr;
4119     const Align Alignment = Align(8);
4120     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4121         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4122     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4123                      /* size */ 8, Alignment, false);
4124   }
4125 
4126   void finalizeInstrumentation() override {
4127     assert(!VAArgSize && !VAArgTLSCopy &&
4128            "finalizeInstrumentation called twice");
4129     IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4130     VAArgSize = IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4131     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
4132                                     VAArgSize);
4133 
4134     if (!VAStartInstrumentationList.empty()) {
4135       // If there is a va_start in this function, make a backup copy of
4136       // va_arg_tls somewhere in the function entry block.
4137       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4138       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4139     }
4140 
4141     // Instrument va_start.
4142     // Copy va_list shadow from the backup copy of the TLS contents.
4143     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4144       CallInst *OrigInst = VAStartInstrumentationList[i];
4145       IRBuilder<> IRB(OrigInst->getNextNode());
4146       Value *VAListTag = OrigInst->getArgOperand(0);
4147       Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4148       Value *RegSaveAreaPtrPtr =
4149           IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4150                              PointerType::get(RegSaveAreaPtrTy, 0));
4151       Value *RegSaveAreaPtr =
4152           IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr);
4153       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
4154       const Align Alignment = Align(8);
4155       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
4156           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4157                                  Alignment, /*isStore*/ true);
4158       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
4159                        CopySize);
4160     }
4161   }
4162 };
4163 
4164 /// AArch64-specific implementation of VarArgHelper.
4165 struct VarArgAArch64Helper : public VarArgHelper {
4166   static const unsigned kAArch64GrArgSize = 64;
4167   static const unsigned kAArch64VrArgSize = 128;
4168 
4169   static const unsigned AArch64GrBegOffset = 0;
4170   static const unsigned AArch64GrEndOffset = kAArch64GrArgSize;
4171   // Make VR space aligned to 16 bytes.
4172   static const unsigned AArch64VrBegOffset = AArch64GrEndOffset;
4173   static const unsigned AArch64VrEndOffset = AArch64VrBegOffset
4174                                              + kAArch64VrArgSize;
4175   static const unsigned AArch64VAEndOffset = AArch64VrEndOffset;
4176 
4177   Function &F;
4178   MemorySanitizer &MS;
4179   MemorySanitizerVisitor &MSV;
4180   Value *VAArgTLSCopy = nullptr;
4181   Value *VAArgOverflowSize = nullptr;
4182 
4183   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4184 
4185   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
4186 
4187   VarArgAArch64Helper(Function &F, MemorySanitizer &MS,
4188                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4189 
4190   ArgKind classifyArgument(Value* arg) {
4191     Type *T = arg->getType();
4192     if (T->isFPOrFPVectorTy())
4193       return AK_FloatingPoint;
4194     if ((T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
4195         || (T->isPointerTy()))
4196       return AK_GeneralPurpose;
4197     return AK_Memory;
4198   }
4199 
4200   // The instrumentation stores the argument shadow in a non ABI-specific
4201   // format because it does not know which argument is named (since Clang,
4202   // like x86_64 case, lowers the va_args in the frontend and this pass only
4203   // sees the low level code that deals with va_list internals).
4204   // The first seven GR registers are saved in the first 56 bytes of the
4205   // va_arg tls arra, followers by the first 8 FP/SIMD registers, and then
4206   // the remaining arguments.
4207   // Using constant offset within the va_arg TLS array allows fast copy
4208   // in the finalize instrumentation.
4209   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
4210     unsigned GrOffset = AArch64GrBegOffset;
4211     unsigned VrOffset = AArch64VrBegOffset;
4212     unsigned OverflowOffset = AArch64VAEndOffset;
4213 
4214     const DataLayout &DL = F.getParent()->getDataLayout();
4215     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
4216          ArgIt != End; ++ArgIt) {
4217       Value *A = *ArgIt;
4218       unsigned ArgNo = CS.getArgumentNo(ArgIt);
4219       bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
4220       ArgKind AK = classifyArgument(A);
4221       if (AK == AK_GeneralPurpose && GrOffset >= AArch64GrEndOffset)
4222         AK = AK_Memory;
4223       if (AK == AK_FloatingPoint && VrOffset >= AArch64VrEndOffset)
4224         AK = AK_Memory;
4225       Value *Base;
4226       switch (AK) {
4227         case AK_GeneralPurpose:
4228           Base = getShadowPtrForVAArgument(A->getType(), IRB, GrOffset, 8);
4229           GrOffset += 8;
4230           break;
4231         case AK_FloatingPoint:
4232           Base = getShadowPtrForVAArgument(A->getType(), IRB, VrOffset, 8);
4233           VrOffset += 16;
4234           break;
4235         case AK_Memory:
4236           // Don't count fixed arguments in the overflow area - va_start will
4237           // skip right over them.
4238           if (IsFixed)
4239             continue;
4240           uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4241           Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset,
4242                                            alignTo(ArgSize, 8));
4243           OverflowOffset += alignTo(ArgSize, 8);
4244           break;
4245       }
4246       // Count Gp/Vr fixed arguments to their respective offsets, but don't
4247       // bother to actually store a shadow.
4248       if (IsFixed)
4249         continue;
4250       if (!Base)
4251         continue;
4252       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4253     }
4254     Constant *OverflowSize =
4255       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AArch64VAEndOffset);
4256     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
4257   }
4258 
4259   /// Compute the shadow address for a given va_arg.
4260   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4261                                    unsigned ArgOffset, unsigned ArgSize) {
4262     // Make sure we don't overflow __msan_va_arg_tls.
4263     if (ArgOffset + ArgSize > kParamTLSSize)
4264       return nullptr;
4265     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4266     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4267     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4268                               "_msarg");
4269   }
4270 
4271   void visitVAStartInst(VAStartInst &I) override {
4272     IRBuilder<> IRB(&I);
4273     VAStartInstrumentationList.push_back(&I);
4274     Value *VAListTag = I.getArgOperand(0);
4275     Value *ShadowPtr, *OriginPtr;
4276     const Align Alignment = Align(8);
4277     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4278         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4279     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4280                      /* size */ 32, Alignment, false);
4281   }
4282 
4283   void visitVACopyInst(VACopyInst &I) override {
4284     IRBuilder<> IRB(&I);
4285     VAStartInstrumentationList.push_back(&I);
4286     Value *VAListTag = I.getArgOperand(0);
4287     Value *ShadowPtr, *OriginPtr;
4288     const Align Alignment = Align(8);
4289     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4290         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4291     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4292                      /* size */ 32, Alignment, false);
4293   }
4294 
4295   // Retrieve a va_list field of 'void*' size.
4296   Value* getVAField64(IRBuilder<> &IRB, Value *VAListTag, int offset) {
4297     Value *SaveAreaPtrPtr =
4298       IRB.CreateIntToPtr(
4299         IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4300                       ConstantInt::get(MS.IntptrTy, offset)),
4301         Type::getInt64PtrTy(*MS.C));
4302     return IRB.CreateLoad(Type::getInt64Ty(*MS.C), SaveAreaPtrPtr);
4303   }
4304 
4305   // Retrieve a va_list field of 'int' size.
4306   Value* getVAField32(IRBuilder<> &IRB, Value *VAListTag, int offset) {
4307     Value *SaveAreaPtr =
4308       IRB.CreateIntToPtr(
4309         IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4310                       ConstantInt::get(MS.IntptrTy, offset)),
4311         Type::getInt32PtrTy(*MS.C));
4312     Value *SaveArea32 = IRB.CreateLoad(IRB.getInt32Ty(), SaveAreaPtr);
4313     return IRB.CreateSExt(SaveArea32, MS.IntptrTy);
4314   }
4315 
4316   void finalizeInstrumentation() override {
4317     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
4318            "finalizeInstrumentation called twice");
4319     if (!VAStartInstrumentationList.empty()) {
4320       // If there is a va_start in this function, make a backup copy of
4321       // va_arg_tls somewhere in the function entry block.
4322       IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4323       VAArgOverflowSize =
4324           IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4325       Value *CopySize =
4326         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AArch64VAEndOffset),
4327                       VAArgOverflowSize);
4328       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4329       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4330     }
4331 
4332     Value *GrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64GrArgSize);
4333     Value *VrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64VrArgSize);
4334 
4335     // Instrument va_start, copy va_list shadow from the backup copy of
4336     // the TLS contents.
4337     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4338       CallInst *OrigInst = VAStartInstrumentationList[i];
4339       IRBuilder<> IRB(OrigInst->getNextNode());
4340 
4341       Value *VAListTag = OrigInst->getArgOperand(0);
4342 
4343       // The variadic ABI for AArch64 creates two areas to save the incoming
4344       // argument registers (one for 64-bit general register xn-x7 and another
4345       // for 128-bit FP/SIMD vn-v7).
4346       // We need then to propagate the shadow arguments on both regions
4347       // 'va::__gr_top + va::__gr_offs' and 'va::__vr_top + va::__vr_offs'.
4348       // The remaining arguments are saved on shadow for 'va::stack'.
4349       // One caveat is it requires only to propagate the non-named arguments,
4350       // however on the call site instrumentation 'all' the arguments are
4351       // saved. So to copy the shadow values from the va_arg TLS array
4352       // we need to adjust the offset for both GR and VR fields based on
4353       // the __{gr,vr}_offs value (since they are stores based on incoming
4354       // named arguments).
4355 
4356       // Read the stack pointer from the va_list.
4357       Value *StackSaveAreaPtr = getVAField64(IRB, VAListTag, 0);
4358 
4359       // Read both the __gr_top and __gr_off and add them up.
4360       Value *GrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 8);
4361       Value *GrOffSaveArea = getVAField32(IRB, VAListTag, 24);
4362 
4363       Value *GrRegSaveAreaPtr = IRB.CreateAdd(GrTopSaveAreaPtr, GrOffSaveArea);
4364 
4365       // Read both the __vr_top and __vr_off and add them up.
4366       Value *VrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 16);
4367       Value *VrOffSaveArea = getVAField32(IRB, VAListTag, 28);
4368 
4369       Value *VrRegSaveAreaPtr = IRB.CreateAdd(VrTopSaveAreaPtr, VrOffSaveArea);
4370 
4371       // It does not know how many named arguments is being used and, on the
4372       // callsite all the arguments were saved.  Since __gr_off is defined as
4373       // '0 - ((8 - named_gr) * 8)', the idea is to just propagate the variadic
4374       // argument by ignoring the bytes of shadow from named arguments.
4375       Value *GrRegSaveAreaShadowPtrOff =
4376         IRB.CreateAdd(GrArgSize, GrOffSaveArea);
4377 
4378       Value *GrRegSaveAreaShadowPtr =
4379           MSV.getShadowOriginPtr(GrRegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4380                                  Align(8), /*isStore*/ true)
4381               .first;
4382 
4383       Value *GrSrcPtr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4384                                               GrRegSaveAreaShadowPtrOff);
4385       Value *GrCopySize = IRB.CreateSub(GrArgSize, GrRegSaveAreaShadowPtrOff);
4386 
4387       IRB.CreateMemCpy(GrRegSaveAreaShadowPtr, Align(8), GrSrcPtr, Align(8),
4388                        GrCopySize);
4389 
4390       // Again, but for FP/SIMD values.
4391       Value *VrRegSaveAreaShadowPtrOff =
4392           IRB.CreateAdd(VrArgSize, VrOffSaveArea);
4393 
4394       Value *VrRegSaveAreaShadowPtr =
4395           MSV.getShadowOriginPtr(VrRegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4396                                  Align(8), /*isStore*/ true)
4397               .first;
4398 
4399       Value *VrSrcPtr = IRB.CreateInBoundsGEP(
4400         IRB.getInt8Ty(),
4401         IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4402                               IRB.getInt32(AArch64VrBegOffset)),
4403         VrRegSaveAreaShadowPtrOff);
4404       Value *VrCopySize = IRB.CreateSub(VrArgSize, VrRegSaveAreaShadowPtrOff);
4405 
4406       IRB.CreateMemCpy(VrRegSaveAreaShadowPtr, Align(8), VrSrcPtr, Align(8),
4407                        VrCopySize);
4408 
4409       // And finally for remaining arguments.
4410       Value *StackSaveAreaShadowPtr =
4411           MSV.getShadowOriginPtr(StackSaveAreaPtr, IRB, IRB.getInt8Ty(),
4412                                  Align(16), /*isStore*/ true)
4413               .first;
4414 
4415       Value *StackSrcPtr =
4416         IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4417                               IRB.getInt32(AArch64VAEndOffset));
4418 
4419       IRB.CreateMemCpy(StackSaveAreaShadowPtr, Align(16), StackSrcPtr,
4420                        Align(16), VAArgOverflowSize);
4421     }
4422   }
4423 };
4424 
4425 /// PowerPC64-specific implementation of VarArgHelper.
4426 struct VarArgPowerPC64Helper : public VarArgHelper {
4427   Function &F;
4428   MemorySanitizer &MS;
4429   MemorySanitizerVisitor &MSV;
4430   Value *VAArgTLSCopy = nullptr;
4431   Value *VAArgSize = nullptr;
4432 
4433   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4434 
4435   VarArgPowerPC64Helper(Function &F, MemorySanitizer &MS,
4436                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4437 
4438   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
4439     // For PowerPC, we need to deal with alignment of stack arguments -
4440     // they are mostly aligned to 8 bytes, but vectors and i128 arrays
4441     // are aligned to 16 bytes, byvals can be aligned to 8 or 16 bytes,
4442     // and QPX vectors are aligned to 32 bytes.  For that reason, we
4443     // compute current offset from stack pointer (which is always properly
4444     // aligned), and offset for the first vararg, then subtract them.
4445     unsigned VAArgBase;
4446     Triple TargetTriple(F.getParent()->getTargetTriple());
4447     // Parameter save area starts at 48 bytes from frame pointer for ABIv1,
4448     // and 32 bytes for ABIv2.  This is usually determined by target
4449     // endianness, but in theory could be overridden by function attribute.
4450     // For simplicity, we ignore it here (it'd only matter for QPX vectors).
4451     if (TargetTriple.getArch() == Triple::ppc64)
4452       VAArgBase = 48;
4453     else
4454       VAArgBase = 32;
4455     unsigned VAArgOffset = VAArgBase;
4456     const DataLayout &DL = F.getParent()->getDataLayout();
4457     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
4458          ArgIt != End; ++ArgIt) {
4459       Value *A = *ArgIt;
4460       unsigned ArgNo = CS.getArgumentNo(ArgIt);
4461       bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
4462       bool IsByVal = CS.paramHasAttr(ArgNo, Attribute::ByVal);
4463       if (IsByVal) {
4464         assert(A->getType()->isPointerTy());
4465         Type *RealTy = A->getType()->getPointerElementType();
4466         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
4467         uint64_t ArgAlign = CS.getParamAlignment(ArgNo);
4468         if (ArgAlign < 8)
4469           ArgAlign = 8;
4470         VAArgOffset = alignTo(VAArgOffset, ArgAlign);
4471         if (!IsFixed) {
4472           Value *Base = getShadowPtrForVAArgument(
4473               RealTy, IRB, VAArgOffset - VAArgBase, ArgSize);
4474           if (Base) {
4475             Value *AShadowPtr, *AOriginPtr;
4476             std::tie(AShadowPtr, AOriginPtr) =
4477                 MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(),
4478                                        kShadowTLSAlignment, /*isStore*/ false);
4479 
4480             IRB.CreateMemCpy(Base, kShadowTLSAlignment, AShadowPtr,
4481                              kShadowTLSAlignment, ArgSize);
4482           }
4483         }
4484         VAArgOffset += alignTo(ArgSize, 8);
4485       } else {
4486         Value *Base;
4487         uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4488         uint64_t ArgAlign = 8;
4489         if (A->getType()->isArrayTy()) {
4490           // Arrays are aligned to element size, except for long double
4491           // arrays, which are aligned to 8 bytes.
4492           Type *ElementTy = A->getType()->getArrayElementType();
4493           if (!ElementTy->isPPC_FP128Ty())
4494             ArgAlign = DL.getTypeAllocSize(ElementTy);
4495         } else if (A->getType()->isVectorTy()) {
4496           // Vectors are naturally aligned.
4497           ArgAlign = DL.getTypeAllocSize(A->getType());
4498         }
4499         if (ArgAlign < 8)
4500           ArgAlign = 8;
4501         VAArgOffset = alignTo(VAArgOffset, ArgAlign);
4502         if (DL.isBigEndian()) {
4503           // Adjusting the shadow for argument with size < 8 to match the placement
4504           // of bits in big endian system
4505           if (ArgSize < 8)
4506             VAArgOffset += (8 - ArgSize);
4507         }
4508         if (!IsFixed) {
4509           Base = getShadowPtrForVAArgument(A->getType(), IRB,
4510                                            VAArgOffset - VAArgBase, ArgSize);
4511           if (Base)
4512             IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4513         }
4514         VAArgOffset += ArgSize;
4515         VAArgOffset = alignTo(VAArgOffset, 8);
4516       }
4517       if (IsFixed)
4518         VAArgBase = VAArgOffset;
4519     }
4520 
4521     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(),
4522                                                 VAArgOffset - VAArgBase);
4523     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
4524     // a new class member i.e. it is the total size of all VarArgs.
4525     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
4526   }
4527 
4528   /// Compute the shadow address for a given va_arg.
4529   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4530                                    unsigned ArgOffset, unsigned ArgSize) {
4531     // Make sure we don't overflow __msan_va_arg_tls.
4532     if (ArgOffset + ArgSize > kParamTLSSize)
4533       return nullptr;
4534     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4535     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4536     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4537                               "_msarg");
4538   }
4539 
4540   void visitVAStartInst(VAStartInst &I) override {
4541     IRBuilder<> IRB(&I);
4542     VAStartInstrumentationList.push_back(&I);
4543     Value *VAListTag = I.getArgOperand(0);
4544     Value *ShadowPtr, *OriginPtr;
4545     const Align Alignment = Align(8);
4546     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4547         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4548     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4549                      /* size */ 8, Alignment, false);
4550   }
4551 
4552   void visitVACopyInst(VACopyInst &I) override {
4553     IRBuilder<> IRB(&I);
4554     Value *VAListTag = I.getArgOperand(0);
4555     Value *ShadowPtr, *OriginPtr;
4556     const Align Alignment = Align(8);
4557     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4558         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4559     // Unpoison the whole __va_list_tag.
4560     // FIXME: magic ABI constants.
4561     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4562                      /* size */ 8, Alignment, false);
4563   }
4564 
4565   void finalizeInstrumentation() override {
4566     assert(!VAArgSize && !VAArgTLSCopy &&
4567            "finalizeInstrumentation called twice");
4568     IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4569     VAArgSize = IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS);
4570     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
4571                                     VAArgSize);
4572 
4573     if (!VAStartInstrumentationList.empty()) {
4574       // If there is a va_start in this function, make a backup copy of
4575       // va_arg_tls somewhere in the function entry block.
4576       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4577       IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize);
4578     }
4579 
4580     // Instrument va_start.
4581     // Copy va_list shadow from the backup copy of the TLS contents.
4582     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4583       CallInst *OrigInst = VAStartInstrumentationList[i];
4584       IRBuilder<> IRB(OrigInst->getNextNode());
4585       Value *VAListTag = OrigInst->getArgOperand(0);
4586       Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C);
4587       Value *RegSaveAreaPtrPtr =
4588           IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4589                              PointerType::get(RegSaveAreaPtrTy, 0));
4590       Value *RegSaveAreaPtr =
4591           IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr);
4592       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
4593       const Align Alignment = Align(8);
4594       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
4595           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4596                                  Alignment, /*isStore*/ true);
4597       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
4598                        CopySize);
4599     }
4600   }
4601 };
4602 
4603 /// A no-op implementation of VarArgHelper.
4604 struct VarArgNoOpHelper : public VarArgHelper {
4605   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
4606                    MemorySanitizerVisitor &MSV) {}
4607 
4608   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
4609 
4610   void visitVAStartInst(VAStartInst &I) override {}
4611 
4612   void visitVACopyInst(VACopyInst &I) override {}
4613 
4614   void finalizeInstrumentation() override {}
4615 };
4616 
4617 } // end anonymous namespace
4618 
4619 static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
4620                                         MemorySanitizerVisitor &Visitor) {
4621   // VarArg handling is only implemented on AMD64. False positives are possible
4622   // on other platforms.
4623   Triple TargetTriple(Func.getParent()->getTargetTriple());
4624   if (TargetTriple.getArch() == Triple::x86_64)
4625     return new VarArgAMD64Helper(Func, Msan, Visitor);
4626   else if (TargetTriple.isMIPS64())
4627     return new VarArgMIPS64Helper(Func, Msan, Visitor);
4628   else if (TargetTriple.getArch() == Triple::aarch64)
4629     return new VarArgAArch64Helper(Func, Msan, Visitor);
4630   else if (TargetTriple.getArch() == Triple::ppc64 ||
4631            TargetTriple.getArch() == Triple::ppc64le)
4632     return new VarArgPowerPC64Helper(Func, Msan, Visitor);
4633   else
4634     return new VarArgNoOpHelper(Func, Msan, Visitor);
4635 }
4636 
4637 bool MemorySanitizer::sanitizeFunction(Function &F, TargetLibraryInfo &TLI) {
4638   if (!CompileKernel && F.getName() == kMsanModuleCtorName)
4639     return false;
4640 
4641   MemorySanitizerVisitor Visitor(F, *this, TLI);
4642 
4643   // Clear out readonly/readnone attributes.
4644   AttrBuilder B;
4645   B.addAttribute(Attribute::ReadOnly)
4646       .addAttribute(Attribute::ReadNone)
4647       .addAttribute(Attribute::WriteOnly)
4648       .addAttribute(Attribute::ArgMemOnly)
4649       .addAttribute(Attribute::Speculatable);
4650   F.removeAttributes(AttributeList::FunctionIndex, B);
4651 
4652   return Visitor.runOnFunction();
4653 }
4654