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