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 /// \file
10 /// This file is a part of MemorySanitizer, a detector of uninitialized
11 /// reads.
12 ///
13 /// The algorithm of the tool is similar to Memcheck
14 /// (http://goo.gl/QKbem). We associate a few shadow bits with every
15 /// byte of the application memory, poison the shadow of the malloc-ed
16 /// or alloca-ed memory, load the shadow bits on every memory read,
17 /// propagate the shadow bits through some of the arithmetic
18 /// instruction (including MOV), store the shadow bits on every memory
19 /// write, report a bug on some other instructions (e.g. JMP) if the
20 /// associated shadow is poisoned.
21 ///
22 /// But there are differences too. The first and the major one:
23 /// compiler instrumentation instead of binary instrumentation. This
24 /// gives us much better register allocation, possible compiler
25 /// optimizations and a fast start-up. But this brings the major issue
26 /// as well: msan needs to see all program events, including system
27 /// calls and reads/writes in system libraries, so we either need to
28 /// compile *everything* with msan or use a binary translation
29 /// component (e.g. DynamoRIO) to instrument pre-built libraries.
30 /// Another difference from Memcheck is that we use 8 shadow bits per
31 /// byte of application memory and use a direct shadow mapping. This
32 /// greatly simplifies the instrumentation code and avoids races on
33 /// shadow updates (Memcheck is single-threaded so races are not a
34 /// concern there. Memcheck uses 2 shadow bits per byte with a slow
35 /// path storage that uses 8 bits per byte).
36 ///
37 /// The default value of shadow is 0, which means "clean" (not poisoned).
38 ///
39 /// Every module initializer should call __msan_init to ensure that the
40 /// shadow memory is ready. On error, __msan_warning is called. Since
41 /// parameters and return values may be passed via registers, we have a
42 /// specialized thread-local shadow for return values
43 /// (__msan_retval_tls) and parameters (__msan_param_tls).
44 ///
45 ///                           Origin tracking.
46 ///
47 /// MemorySanitizer can track origins (allocation points) of all uninitialized
48 /// values. This behavior is controlled with a flag (msan-track-origins) and is
49 /// disabled by default.
50 ///
51 /// Origins are 4-byte values created and interpreted by the runtime library.
52 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
53 /// of application memory. Propagation of origins is basically a bunch of
54 /// "select" instructions that pick the origin of a dirty argument, if an
55 /// instruction has one.
56 ///
57 /// Every 4 aligned, consecutive bytes of application memory have one origin
58 /// value associated with them. If these bytes contain uninitialized data
59 /// coming from 2 different allocations, the last store wins. Because of this,
60 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
61 /// practice.
62 ///
63 /// Origins are meaningless for fully initialized values, so MemorySanitizer
64 /// avoids storing origin to memory when a fully initialized value is stored.
65 /// This way it avoids needless overwritting origin of the 4-byte region on
66 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
67 ///
68 ///                            Atomic handling.
69 ///
70 /// Ideally, every atomic store of application value should update the
71 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
72 /// of two disjoint locations can not be done without severe slowdown.
73 ///
74 /// Therefore, we implement an approximation that may err on the safe side.
75 /// In this implementation, every atomically accessed location in the program
76 /// may only change from (partially) uninitialized to fully initialized, but
77 /// not the other way around. We load the shadow _after_ the application load,
78 /// and we store the shadow _before_ the app store. Also, we always store clean
79 /// shadow (if the application store is atomic). This way, if the store-load
80 /// pair constitutes a happens-before arc, shadow store and load are correctly
81 /// ordered such that the load will get either the value that was stored, or
82 /// some later value (which is always clean).
83 ///
84 /// This does not work very well with Compare-And-Swap (CAS) and
85 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
86 /// must store the new shadow before the app operation, and load the shadow
87 /// after the app operation. Computers don't work this way. Current
88 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
89 /// value. It implements the store part as a simple atomic store by storing a
90 /// clean shadow.
91 
92 //===----------------------------------------------------------------------===//
93 
94 #include "llvm/Transforms/Instrumentation.h"
95 #include "llvm/ADT/DepthFirstIterator.h"
96 #include "llvm/ADT/SmallString.h"
97 #include "llvm/ADT/SmallVector.h"
98 #include "llvm/ADT/StringExtras.h"
99 #include "llvm/ADT/Triple.h"
100 #include "llvm/IR/DataLayout.h"
101 #include "llvm/IR/Function.h"
102 #include "llvm/IR/IRBuilder.h"
103 #include "llvm/IR/InlineAsm.h"
104 #include "llvm/IR/InstVisitor.h"
105 #include "llvm/IR/IntrinsicInst.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/MDBuilder.h"
108 #include "llvm/IR/Module.h"
109 #include "llvm/IR/Type.h"
110 #include "llvm/IR/ValueMap.h"
111 #include "llvm/Support/CommandLine.h"
112 #include "llvm/Support/Compiler.h"
113 #include "llvm/Support/Debug.h"
114 #include "llvm/Support/raw_ostream.h"
115 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include "llvm/Transforms/Utils/ModuleUtils.h"
118 
119 using namespace llvm;
120 
121 #define DEBUG_TYPE "msan"
122 
123 // VMA size definition for architecture that support multiple sizes.
124 // AArch64 has 3 VMA sizes: 39, 42 and 48.
125 #ifndef SANITIZER_AARCH64_VMA
126 # define SANITIZER_AARCH64_VMA 39
127 #else
128 # if SANITIZER_AARCH64_VMA != 39 && SANITIZER_AARCH64_VMA != 42
129 #  error "invalid SANITIZER_AARCH64_VMA size"
130 # endif
131 #endif
132 
133 static const unsigned kOriginSize = 4;
134 static const unsigned kMinOriginAlignment = 4;
135 static const unsigned kShadowTLSAlignment = 8;
136 
137 // These constants must be kept in sync with the ones in msan.h.
138 static const unsigned kParamTLSSize = 800;
139 static const unsigned kRetvalTLSSize = 800;
140 
141 // Accesses sizes are powers of two: 1, 2, 4, 8.
142 static const size_t kNumberOfAccessSizes = 4;
143 
144 /// \brief Track origins of uninitialized values.
145 ///
146 /// Adds a section to MemorySanitizer report that points to the allocation
147 /// (stack or heap) the uninitialized bits came from originally.
148 static cl::opt<int> ClTrackOrigins("msan-track-origins",
149        cl::desc("Track origins (allocation sites) of poisoned memory"),
150        cl::Hidden, cl::init(0));
151 static cl::opt<bool> ClKeepGoing("msan-keep-going",
152        cl::desc("keep going after reporting a UMR"),
153        cl::Hidden, cl::init(false));
154 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
155        cl::desc("poison uninitialized stack variables"),
156        cl::Hidden, cl::init(true));
157 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
158        cl::desc("poison uninitialized stack variables with a call"),
159        cl::Hidden, cl::init(false));
160 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
161        cl::desc("poison uninitialized stack variables with the given pattern"),
162        cl::Hidden, cl::init(0xff));
163 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
164        cl::desc("poison undef temps"),
165        cl::Hidden, cl::init(true));
166 
167 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
168        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
169        cl::Hidden, cl::init(true));
170 
171 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
172        cl::desc("exact handling of relational integer ICmp"),
173        cl::Hidden, cl::init(false));
174 
175 // This flag controls whether we check the shadow of the address
176 // operand of load or store. Such bugs are very rare, since load from
177 // a garbage address typically results in SEGV, but still happen
178 // (e.g. only lower bits of address are garbage, or the access happens
179 // early at program startup where malloc-ed memory is more likely to
180 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
181 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
182        cl::desc("report accesses through a pointer which has poisoned shadow"),
183        cl::Hidden, cl::init(true));
184 
185 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
186        cl::desc("print out instructions with default strict semantics"),
187        cl::Hidden, cl::init(false));
188 
189 static cl::opt<int> ClInstrumentationWithCallThreshold(
190     "msan-instrumentation-with-call-threshold",
191     cl::desc(
192         "If the function being instrumented requires more than "
193         "this number of checks and origin stores, use callbacks instead of "
194         "inline checks (-1 means never use callbacks)."),
195     cl::Hidden, cl::init(3500));
196 
197 // This is an experiment to enable handling of cases where shadow is a non-zero
198 // compile-time constant. For some unexplainable reason they were silently
199 // ignored in the instrumentation.
200 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
201        cl::desc("Insert checks for constant shadow values"),
202        cl::Hidden, cl::init(false));
203 
204 static const char *const kMsanModuleCtorName = "msan.module_ctor";
205 static const char *const kMsanInitName = "__msan_init";
206 
207 namespace {
208 
209 // Memory map parameters used in application-to-shadow address calculation.
210 // Offset = (Addr & ~AndMask) ^ XorMask
211 // Shadow = ShadowBase + Offset
212 // Origin = OriginBase + Offset
213 struct MemoryMapParams {
214   uint64_t AndMask;
215   uint64_t XorMask;
216   uint64_t ShadowBase;
217   uint64_t OriginBase;
218 };
219 
220 struct PlatformMemoryMapParams {
221   const MemoryMapParams *bits32;
222   const MemoryMapParams *bits64;
223 };
224 
225 // i386 Linux
226 static const MemoryMapParams Linux_I386_MemoryMapParams = {
227   0x000080000000,  // AndMask
228   0,               // XorMask (not used)
229   0,               // ShadowBase (not used)
230   0x000040000000,  // OriginBase
231 };
232 
233 // x86_64 Linux
234 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
235 #ifdef MSAN_LINUX_X86_64_OLD_MAPPING
236   0x400000000000,  // AndMask
237   0,               // XorMask (not used)
238   0,               // ShadowBase (not used)
239   0x200000000000,  // OriginBase
240 #else
241   0,               // AndMask (not used)
242   0x500000000000,  // XorMask
243   0,               // ShadowBase (not used)
244   0x100000000000,  // OriginBase
245 #endif
246 };
247 
248 // mips64 Linux
249 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
250   0x004000000000,  // AndMask
251   0,               // XorMask (not used)
252   0,               // ShadowBase (not used)
253   0x002000000000,  // OriginBase
254 };
255 
256 // ppc64 Linux
257 static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
258   0x200000000000,  // AndMask
259   0x100000000000,  // XorMask
260   0x080000000000,  // ShadowBase
261   0x1C0000000000,  // OriginBase
262 };
263 
264 // aarch64 Linux
265 static const MemoryMapParams Linux_AArch64_MemoryMapParams = {
266 #if SANITIZER_AARCH64_VMA == 39
267   0x007C00000000,  // AndMask
268   0x000100000000,  // XorMask
269   0x004000000000,  // ShadowBase
270   0x004300000000,  // OriginBase
271 #elif SANITIZER_AARCH64_VMA == 42
272   0x03E000000000,  // AndMask
273   0x001000000000,  // XorMask
274   0x010000000000,  // ShadowBase
275   0x012000000000,  // OriginBase
276 #endif
277 };
278 
279 // i386 FreeBSD
280 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
281   0x000180000000,  // AndMask
282   0x000040000000,  // XorMask
283   0x000020000000,  // ShadowBase
284   0x000700000000,  // OriginBase
285 };
286 
287 // x86_64 FreeBSD
288 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
289   0xc00000000000,  // AndMask
290   0x200000000000,  // XorMask
291   0x100000000000,  // ShadowBase
292   0x380000000000,  // OriginBase
293 };
294 
295 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
296   &Linux_I386_MemoryMapParams,
297   &Linux_X86_64_MemoryMapParams,
298 };
299 
300 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
301   nullptr,
302   &Linux_MIPS64_MemoryMapParams,
303 };
304 
305 static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
306   nullptr,
307   &Linux_PowerPC64_MemoryMapParams,
308 };
309 
310 static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = {
311   nullptr,
312   &Linux_AArch64_MemoryMapParams,
313 };
314 
315 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
316   &FreeBSD_I386_MemoryMapParams,
317   &FreeBSD_X86_64_MemoryMapParams,
318 };
319 
320 /// \brief An instrumentation pass implementing detection of uninitialized
321 /// reads.
322 ///
323 /// MemorySanitizer: instrument the code in module to find
324 /// uninitialized reads.
325 class MemorySanitizer : public FunctionPass {
326  public:
327   MemorySanitizer(int TrackOrigins = 0)
328       : FunctionPass(ID),
329         TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
330         WarningFn(nullptr) {}
331   const char *getPassName() const override { return "MemorySanitizer"; }
332   bool runOnFunction(Function &F) override;
333   bool doInitialization(Module &M) override;
334   static char ID;  // Pass identification, replacement for typeid.
335 
336  private:
337   void initializeCallbacks(Module &M);
338 
339   /// \brief Track origins (allocation points) of uninitialized values.
340   int TrackOrigins;
341 
342   LLVMContext *C;
343   Type *IntptrTy;
344   Type *OriginTy;
345   /// \brief Thread-local shadow storage for function parameters.
346   GlobalVariable *ParamTLS;
347   /// \brief Thread-local origin storage for function parameters.
348   GlobalVariable *ParamOriginTLS;
349   /// \brief Thread-local shadow storage for function return value.
350   GlobalVariable *RetvalTLS;
351   /// \brief Thread-local origin storage for function return value.
352   GlobalVariable *RetvalOriginTLS;
353   /// \brief Thread-local shadow storage for in-register va_arg function
354   /// parameters (x86_64-specific).
355   GlobalVariable *VAArgTLS;
356   /// \brief Thread-local shadow storage for va_arg overflow area
357   /// (x86_64-specific).
358   GlobalVariable *VAArgOverflowSizeTLS;
359   /// \brief Thread-local space used to pass origin value to the UMR reporting
360   /// function.
361   GlobalVariable *OriginTLS;
362 
363   /// \brief The run-time callback to print a warning.
364   Value *WarningFn;
365   // These arrays are indexed by log2(AccessSize).
366   Value *MaybeWarningFn[kNumberOfAccessSizes];
367   Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
368 
369   /// \brief Run-time helper that generates a new origin value for a stack
370   /// allocation.
371   Value *MsanSetAllocaOrigin4Fn;
372   /// \brief Run-time helper that poisons stack on function entry.
373   Value *MsanPoisonStackFn;
374   /// \brief Run-time helper that records a store (or any event) of an
375   /// uninitialized value and returns an updated origin id encoding this info.
376   Value *MsanChainOriginFn;
377   /// \brief MSan runtime replacements for memmove, memcpy and memset.
378   Value *MemmoveFn, *MemcpyFn, *MemsetFn;
379 
380   /// \brief Memory map parameters used in application-to-shadow calculation.
381   const MemoryMapParams *MapParams;
382 
383   MDNode *ColdCallWeights;
384   /// \brief Branch weights for origin store.
385   MDNode *OriginStoreWeights;
386   /// \brief An empty volatile inline asm that prevents callback merge.
387   InlineAsm *EmptyAsm;
388   Function *MsanCtorFunction;
389 
390   friend struct MemorySanitizerVisitor;
391   friend struct VarArgAMD64Helper;
392   friend struct VarArgMIPS64Helper;
393 };
394 } // anonymous namespace
395 
396 char MemorySanitizer::ID = 0;
397 INITIALIZE_PASS(MemorySanitizer, "msan",
398                 "MemorySanitizer: detects uninitialized reads.",
399                 false, false)
400 
401 FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
402   return new MemorySanitizer(TrackOrigins);
403 }
404 
405 /// \brief Create a non-const global initialized with the given string.
406 ///
407 /// Creates a writable global for Str so that we can pass it to the
408 /// run-time lib. Runtime uses first 4 bytes of the string to store the
409 /// frame ID, so the string needs to be mutable.
410 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
411                                                             StringRef Str) {
412   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
413   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
414                             GlobalValue::PrivateLinkage, StrConst, "");
415 }
416 
417 /// \brief Insert extern declaration of runtime-provided functions and globals.
418 void MemorySanitizer::initializeCallbacks(Module &M) {
419   // Only do this once.
420   if (WarningFn)
421     return;
422 
423   IRBuilder<> IRB(*C);
424   // Create the callback.
425   // FIXME: this function should have "Cold" calling conv,
426   // which is not yet implemented.
427   StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
428                                         : "__msan_warning_noreturn";
429   WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
430 
431   for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
432        AccessSizeIndex++) {
433     unsigned AccessSize = 1 << AccessSizeIndex;
434     std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
435     MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
436         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
437         IRB.getInt32Ty(), nullptr);
438 
439     FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
440     MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
441         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
442         IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
443   }
444 
445   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
446     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
447     IRB.getInt8PtrTy(), IntptrTy, nullptr);
448   MsanPoisonStackFn =
449       M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
450                             IRB.getInt8PtrTy(), IntptrTy, nullptr);
451   MsanChainOriginFn = M.getOrInsertFunction(
452     "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
453   MemmoveFn = M.getOrInsertFunction(
454     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
455     IRB.getInt8PtrTy(), IntptrTy, nullptr);
456   MemcpyFn = M.getOrInsertFunction(
457     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
458     IntptrTy, nullptr);
459   MemsetFn = M.getOrInsertFunction(
460     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
461     IntptrTy, nullptr);
462 
463   // Create globals.
464   RetvalTLS = new GlobalVariable(
465     M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
466     GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
467     GlobalVariable::InitialExecTLSModel);
468   RetvalOriginTLS = new GlobalVariable(
469     M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
470     "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
471 
472   ParamTLS = new GlobalVariable(
473     M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
474     GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
475     GlobalVariable::InitialExecTLSModel);
476   ParamOriginTLS = new GlobalVariable(
477     M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
478     GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
479     nullptr, GlobalVariable::InitialExecTLSModel);
480 
481   VAArgTLS = new GlobalVariable(
482     M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
483     GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
484     GlobalVariable::InitialExecTLSModel);
485   VAArgOverflowSizeTLS = new GlobalVariable(
486     M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
487     "__msan_va_arg_overflow_size_tls", nullptr,
488     GlobalVariable::InitialExecTLSModel);
489   OriginTLS = new GlobalVariable(
490     M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
491     "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
492 
493   // We insert an empty inline asm after __msan_report* to avoid callback merge.
494   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
495                             StringRef(""), StringRef(""),
496                             /*hasSideEffects=*/true);
497 }
498 
499 /// \brief Module-level initialization.
500 ///
501 /// inserts a call to __msan_init to the module's constructor list.
502 bool MemorySanitizer::doInitialization(Module &M) {
503   auto &DL = M.getDataLayout();
504 
505   Triple TargetTriple(M.getTargetTriple());
506   switch (TargetTriple.getOS()) {
507     case Triple::FreeBSD:
508       switch (TargetTriple.getArch()) {
509         case Triple::x86_64:
510           MapParams = FreeBSD_X86_MemoryMapParams.bits64;
511           break;
512         case Triple::x86:
513           MapParams = FreeBSD_X86_MemoryMapParams.bits32;
514           break;
515         default:
516           report_fatal_error("unsupported architecture");
517       }
518       break;
519     case Triple::Linux:
520       switch (TargetTriple.getArch()) {
521         case Triple::x86_64:
522           MapParams = Linux_X86_MemoryMapParams.bits64;
523           break;
524         case Triple::x86:
525           MapParams = Linux_X86_MemoryMapParams.bits32;
526           break;
527         case Triple::mips64:
528         case Triple::mips64el:
529           MapParams = Linux_MIPS_MemoryMapParams.bits64;
530           break;
531         case Triple::ppc64:
532         case Triple::ppc64le:
533           MapParams = Linux_PowerPC_MemoryMapParams.bits64;
534           break;
535         case Triple::aarch64:
536         case Triple::aarch64_be:
537           MapParams = Linux_ARM_MemoryMapParams.bits64;
538           break;
539         default:
540           report_fatal_error("unsupported architecture");
541       }
542       break;
543     default:
544       report_fatal_error("unsupported operating system");
545   }
546 
547   C = &(M.getContext());
548   IRBuilder<> IRB(*C);
549   IntptrTy = IRB.getIntPtrTy(DL);
550   OriginTy = IRB.getInt32Ty();
551 
552   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
553   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
554 
555   std::tie(MsanCtorFunction, std::ignore) =
556       createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
557                                           /*InitArgTypes=*/{},
558                                           /*InitArgs=*/{});
559 
560   appendToGlobalCtors(M, MsanCtorFunction, 0);
561 
562   if (TrackOrigins)
563     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
564                        IRB.getInt32(TrackOrigins), "__msan_track_origins");
565 
566   if (ClKeepGoing)
567     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
568                        IRB.getInt32(ClKeepGoing), "__msan_keep_going");
569 
570   return true;
571 }
572 
573 namespace {
574 
575 /// \brief A helper class that handles instrumentation of VarArg
576 /// functions on a particular platform.
577 ///
578 /// Implementations are expected to insert the instrumentation
579 /// necessary to propagate argument shadow through VarArg function
580 /// calls. Visit* methods are called during an InstVisitor pass over
581 /// the function, and should avoid creating new basic blocks. A new
582 /// instance of this class is created for each instrumented function.
583 struct VarArgHelper {
584   /// \brief Visit a CallSite.
585   virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
586 
587   /// \brief Visit a va_start call.
588   virtual void visitVAStartInst(VAStartInst &I) = 0;
589 
590   /// \brief Visit a va_copy call.
591   virtual void visitVACopyInst(VACopyInst &I) = 0;
592 
593   /// \brief Finalize function instrumentation.
594   ///
595   /// This method is called after visiting all interesting (see above)
596   /// instructions in a function.
597   virtual void finalizeInstrumentation() = 0;
598 
599   virtual ~VarArgHelper() {}
600 };
601 
602 struct MemorySanitizerVisitor;
603 
604 VarArgHelper*
605 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
606                    MemorySanitizerVisitor &Visitor);
607 
608 unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
609   if (TypeSize <= 8) return 0;
610   return Log2_32_Ceil(TypeSize / 8);
611 }
612 
613 /// This class does all the work for a given function. Store and Load
614 /// instructions store and load corresponding shadow and origin
615 /// values. Most instructions propagate shadow from arguments to their
616 /// return values. Certain instructions (most importantly, BranchInst)
617 /// test their argument shadow and print reports (with a runtime call) if it's
618 /// non-zero.
619 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
620   Function &F;
621   MemorySanitizer &MS;
622   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
623   ValueMap<Value*, Value*> ShadowMap, OriginMap;
624   std::unique_ptr<VarArgHelper> VAHelper;
625 
626   // The following flags disable parts of MSan instrumentation based on
627   // blacklist contents and command-line options.
628   bool InsertChecks;
629   bool PropagateShadow;
630   bool PoisonStack;
631   bool PoisonUndef;
632   bool CheckReturnValue;
633 
634   struct ShadowOriginAndInsertPoint {
635     Value *Shadow;
636     Value *Origin;
637     Instruction *OrigIns;
638     ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
639       : Shadow(S), Origin(O), OrigIns(I) { }
640   };
641   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
642   SmallVector<Instruction*, 16> StoreList;
643 
644   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
645       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
646     bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
647     InsertChecks = SanitizeFunction;
648     PropagateShadow = SanitizeFunction;
649     PoisonStack = SanitizeFunction && ClPoisonStack;
650     PoisonUndef = SanitizeFunction && ClPoisonUndef;
651     // FIXME: Consider using SpecialCaseList to specify a list of functions that
652     // must always return fully initialized values. For now, we hardcode "main".
653     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
654 
655     DEBUG(if (!InsertChecks)
656           dbgs() << "MemorySanitizer is not inserting checks into '"
657                  << F.getName() << "'\n");
658   }
659 
660   Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
661     if (MS.TrackOrigins <= 1) return V;
662     return IRB.CreateCall(MS.MsanChainOriginFn, V);
663   }
664 
665   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
666     const DataLayout &DL = F.getParent()->getDataLayout();
667     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
668     if (IntptrSize == kOriginSize) return Origin;
669     assert(IntptrSize == kOriginSize * 2);
670     Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
671     return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
672   }
673 
674   /// \brief Fill memory range with the given origin value.
675   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
676                    unsigned Size, unsigned Alignment) {
677     const DataLayout &DL = F.getParent()->getDataLayout();
678     unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
679     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
680     assert(IntptrAlignment >= kMinOriginAlignment);
681     assert(IntptrSize >= kOriginSize);
682 
683     unsigned Ofs = 0;
684     unsigned CurrentAlignment = Alignment;
685     if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
686       Value *IntptrOrigin = originToIntptr(IRB, Origin);
687       Value *IntptrOriginPtr =
688           IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
689       for (unsigned i = 0; i < Size / IntptrSize; ++i) {
690         Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
691                        : IntptrOriginPtr;
692         IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
693         Ofs += IntptrSize / kOriginSize;
694         CurrentAlignment = IntptrAlignment;
695       }
696     }
697 
698     for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
699       Value *GEP =
700           i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
701       IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
702       CurrentAlignment = kMinOriginAlignment;
703     }
704   }
705 
706   void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
707                    unsigned Alignment, bool AsCall) {
708     const DataLayout &DL = F.getParent()->getDataLayout();
709     unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
710     unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
711     if (isa<StructType>(Shadow->getType())) {
712       paintOrigin(IRB, updateOrigin(Origin, IRB),
713                   getOriginPtr(Addr, IRB, Alignment), StoreSize,
714                   OriginAlignment);
715     } else {
716       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
717       Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
718       if (ConstantShadow) {
719         if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
720           paintOrigin(IRB, updateOrigin(Origin, IRB),
721                       getOriginPtr(Addr, IRB, Alignment), StoreSize,
722                       OriginAlignment);
723         return;
724       }
725 
726       unsigned TypeSizeInBits =
727           DL.getTypeSizeInBits(ConvertedShadow->getType());
728       unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
729       if (AsCall && SizeIndex < kNumberOfAccessSizes) {
730         Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
731         Value *ConvertedShadow2 = IRB.CreateZExt(
732             ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
733         IRB.CreateCall(Fn, {ConvertedShadow2,
734                             IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
735                             Origin});
736       } else {
737         Value *Cmp = IRB.CreateICmpNE(
738             ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
739         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
740             Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
741         IRBuilder<> IRBNew(CheckTerm);
742         paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
743                     getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
744                     OriginAlignment);
745       }
746     }
747   }
748 
749   void materializeStores(bool InstrumentWithCalls) {
750     for (auto Inst : StoreList) {
751       StoreInst &SI = *dyn_cast<StoreInst>(Inst);
752 
753       IRBuilder<> IRB(&SI);
754       Value *Val = SI.getValueOperand();
755       Value *Addr = SI.getPointerOperand();
756       Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
757       Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
758 
759       StoreInst *NewSI =
760           IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
761       DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
762       (void)NewSI;
763 
764       if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
765 
766       if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
767 
768       if (MS.TrackOrigins && !SI.isAtomic())
769         storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI.getAlignment(),
770                     InstrumentWithCalls);
771     }
772   }
773 
774   void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
775                            bool AsCall) {
776     IRBuilder<> IRB(OrigIns);
777     DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
778     Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
779     DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
780 
781     Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
782     if (ConstantShadow) {
783       if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
784         if (MS.TrackOrigins) {
785           IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
786                           MS.OriginTLS);
787         }
788         IRB.CreateCall(MS.WarningFn, {});
789         IRB.CreateCall(MS.EmptyAsm, {});
790         // FIXME: Insert UnreachableInst if !ClKeepGoing?
791         // This may invalidate some of the following checks and needs to be done
792         // at the very end.
793       }
794       return;
795     }
796 
797     const DataLayout &DL = OrigIns->getModule()->getDataLayout();
798 
799     unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
800     unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
801     if (AsCall && SizeIndex < kNumberOfAccessSizes) {
802       Value *Fn = MS.MaybeWarningFn[SizeIndex];
803       Value *ConvertedShadow2 =
804           IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
805       IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
806                                                 ? Origin
807                                                 : (Value *)IRB.getInt32(0)});
808     } else {
809       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
810                                     getCleanShadow(ConvertedShadow), "_mscmp");
811       Instruction *CheckTerm = SplitBlockAndInsertIfThen(
812           Cmp, OrigIns,
813           /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
814 
815       IRB.SetInsertPoint(CheckTerm);
816       if (MS.TrackOrigins) {
817         IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
818                         MS.OriginTLS);
819       }
820       IRB.CreateCall(MS.WarningFn, {});
821       IRB.CreateCall(MS.EmptyAsm, {});
822       DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
823     }
824   }
825 
826   void materializeChecks(bool InstrumentWithCalls) {
827     for (const auto &ShadowData : InstrumentationList) {
828       Instruction *OrigIns = ShadowData.OrigIns;
829       Value *Shadow = ShadowData.Shadow;
830       Value *Origin = ShadowData.Origin;
831       materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
832     }
833     DEBUG(dbgs() << "DONE:\n" << F);
834   }
835 
836   /// \brief Add MemorySanitizer instrumentation to a function.
837   bool runOnFunction() {
838     MS.initializeCallbacks(*F.getParent());
839 
840     // In the presence of unreachable blocks, we may see Phi nodes with
841     // incoming nodes from such blocks. Since InstVisitor skips unreachable
842     // blocks, such nodes will not have any shadow value associated with them.
843     // It's easier to remove unreachable blocks than deal with missing shadow.
844     removeUnreachableBlocks(F);
845 
846     // Iterate all BBs in depth-first order and create shadow instructions
847     // for all instructions (where applicable).
848     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
849     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
850       visit(*BB);
851 
852 
853     // Finalize PHI nodes.
854     for (PHINode *PN : ShadowPHINodes) {
855       PHINode *PNS = cast<PHINode>(getShadow(PN));
856       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
857       size_t NumValues = PN->getNumIncomingValues();
858       for (size_t v = 0; v < NumValues; v++) {
859         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
860         if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
861       }
862     }
863 
864     VAHelper->finalizeInstrumentation();
865 
866     bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
867                                InstrumentationList.size() + StoreList.size() >
868                                    (unsigned)ClInstrumentationWithCallThreshold;
869 
870     // Delayed instrumentation of StoreInst.
871     // This may add new checks to be inserted later.
872     materializeStores(InstrumentWithCalls);
873 
874     // Insert shadow value checks.
875     materializeChecks(InstrumentWithCalls);
876 
877     return true;
878   }
879 
880   /// \brief Compute the shadow type that corresponds to a given Value.
881   Type *getShadowTy(Value *V) {
882     return getShadowTy(V->getType());
883   }
884 
885   /// \brief Compute the shadow type that corresponds to a given Type.
886   Type *getShadowTy(Type *OrigTy) {
887     if (!OrigTy->isSized()) {
888       return nullptr;
889     }
890     // For integer type, shadow is the same as the original type.
891     // This may return weird-sized types like i1.
892     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
893       return IT;
894     const DataLayout &DL = F.getParent()->getDataLayout();
895     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
896       uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
897       return VectorType::get(IntegerType::get(*MS.C, EltSize),
898                              VT->getNumElements());
899     }
900     if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
901       return ArrayType::get(getShadowTy(AT->getElementType()),
902                             AT->getNumElements());
903     }
904     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
905       SmallVector<Type*, 4> Elements;
906       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
907         Elements.push_back(getShadowTy(ST->getElementType(i)));
908       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
909       DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
910       return Res;
911     }
912     uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
913     return IntegerType::get(*MS.C, TypeSize);
914   }
915 
916   /// \brief Flatten a vector type.
917   Type *getShadowTyNoVec(Type *ty) {
918     if (VectorType *vt = dyn_cast<VectorType>(ty))
919       return IntegerType::get(*MS.C, vt->getBitWidth());
920     return ty;
921   }
922 
923   /// \brief Convert a shadow value to it's flattened variant.
924   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
925     Type *Ty = V->getType();
926     Type *NoVecTy = getShadowTyNoVec(Ty);
927     if (Ty == NoVecTy) return V;
928     return IRB.CreateBitCast(V, NoVecTy);
929   }
930 
931   /// \brief Compute the integer shadow offset that corresponds to a given
932   /// application address.
933   ///
934   /// Offset = (Addr & ~AndMask) ^ XorMask
935   Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
936     Value *OffsetLong = IRB.CreatePointerCast(Addr, MS.IntptrTy);
937 
938     uint64_t AndMask = MS.MapParams->AndMask;
939     if (AndMask)
940       OffsetLong =
941           IRB.CreateAnd(OffsetLong, ConstantInt::get(MS.IntptrTy, ~AndMask));
942 
943     uint64_t XorMask = MS.MapParams->XorMask;
944     if (XorMask)
945       OffsetLong =
946           IRB.CreateXor(OffsetLong, ConstantInt::get(MS.IntptrTy, XorMask));
947     return OffsetLong;
948   }
949 
950   /// \brief Compute the shadow address that corresponds to a given application
951   /// address.
952   ///
953   /// Shadow = ShadowBase + Offset
954   Value *getShadowPtr(Value *Addr, Type *ShadowTy,
955                       IRBuilder<> &IRB) {
956     Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
957     uint64_t ShadowBase = MS.MapParams->ShadowBase;
958     if (ShadowBase != 0)
959       ShadowLong =
960         IRB.CreateAdd(ShadowLong,
961                       ConstantInt::get(MS.IntptrTy, ShadowBase));
962     return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
963   }
964 
965   /// \brief Compute the origin address that corresponds to a given application
966   /// address.
967   ///
968   /// OriginAddr = (OriginBase + Offset) & ~3ULL
969   Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
970     Value *OriginLong = getShadowPtrOffset(Addr, IRB);
971     uint64_t OriginBase = MS.MapParams->OriginBase;
972     if (OriginBase != 0)
973       OriginLong =
974         IRB.CreateAdd(OriginLong,
975                       ConstantInt::get(MS.IntptrTy, OriginBase));
976     if (Alignment < kMinOriginAlignment) {
977       uint64_t Mask = kMinOriginAlignment - 1;
978       OriginLong = IRB.CreateAnd(OriginLong,
979                                  ConstantInt::get(MS.IntptrTy, ~Mask));
980     }
981     return IRB.CreateIntToPtr(OriginLong,
982                               PointerType::get(IRB.getInt32Ty(), 0));
983   }
984 
985   /// \brief Compute the shadow address for a given function argument.
986   ///
987   /// Shadow = ParamTLS+ArgOffset.
988   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
989                                  int ArgOffset) {
990     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
991     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
992     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
993                               "_msarg");
994   }
995 
996   /// \brief Compute the origin address for a given function argument.
997   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
998                                  int ArgOffset) {
999     if (!MS.TrackOrigins) return nullptr;
1000     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
1001     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1002     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
1003                               "_msarg_o");
1004   }
1005 
1006   /// \brief Compute the shadow address for a retval.
1007   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
1008     Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
1009     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
1010                               "_msret");
1011   }
1012 
1013   /// \brief Compute the origin address for a retval.
1014   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
1015     // We keep a single origin for the entire retval. Might be too optimistic.
1016     return MS.RetvalOriginTLS;
1017   }
1018 
1019   /// \brief Set SV to be the shadow value for V.
1020   void setShadow(Value *V, Value *SV) {
1021     assert(!ShadowMap.count(V) && "Values may only have one shadow");
1022     ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
1023   }
1024 
1025   /// \brief Set Origin to be the origin value for V.
1026   void setOrigin(Value *V, Value *Origin) {
1027     if (!MS.TrackOrigins) return;
1028     assert(!OriginMap.count(V) && "Values may only have one origin");
1029     DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
1030     OriginMap[V] = Origin;
1031   }
1032 
1033   /// \brief Create a clean shadow value for a given value.
1034   ///
1035   /// Clean shadow (all zeroes) means all bits of the value are defined
1036   /// (initialized).
1037   Constant *getCleanShadow(Value *V) {
1038     Type *ShadowTy = getShadowTy(V);
1039     if (!ShadowTy)
1040       return nullptr;
1041     return Constant::getNullValue(ShadowTy);
1042   }
1043 
1044   /// \brief Create a dirty shadow of a given shadow type.
1045   Constant *getPoisonedShadow(Type *ShadowTy) {
1046     assert(ShadowTy);
1047     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
1048       return Constant::getAllOnesValue(ShadowTy);
1049     if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
1050       SmallVector<Constant *, 4> Vals(AT->getNumElements(),
1051                                       getPoisonedShadow(AT->getElementType()));
1052       return ConstantArray::get(AT, Vals);
1053     }
1054     if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
1055       SmallVector<Constant *, 4> Vals;
1056       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1057         Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1058       return ConstantStruct::get(ST, Vals);
1059     }
1060     llvm_unreachable("Unexpected shadow type");
1061   }
1062 
1063   /// \brief Create a dirty shadow for a given value.
1064   Constant *getPoisonedShadow(Value *V) {
1065     Type *ShadowTy = getShadowTy(V);
1066     if (!ShadowTy)
1067       return nullptr;
1068     return getPoisonedShadow(ShadowTy);
1069   }
1070 
1071   /// \brief Create a clean (zero) origin.
1072   Value *getCleanOrigin() {
1073     return Constant::getNullValue(MS.OriginTy);
1074   }
1075 
1076   /// \brief Get the shadow value for a given Value.
1077   ///
1078   /// This function either returns the value set earlier with setShadow,
1079   /// or extracts if from ParamTLS (for function arguments).
1080   Value *getShadow(Value *V) {
1081     if (!PropagateShadow) return getCleanShadow(V);
1082     if (Instruction *I = dyn_cast<Instruction>(V)) {
1083       // For instructions the shadow is already stored in the map.
1084       Value *Shadow = ShadowMap[V];
1085       if (!Shadow) {
1086         DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
1087         (void)I;
1088         assert(Shadow && "No shadow for a value");
1089       }
1090       return Shadow;
1091     }
1092     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
1093       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
1094       DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
1095       (void)U;
1096       return AllOnes;
1097     }
1098     if (Argument *A = dyn_cast<Argument>(V)) {
1099       // For arguments we compute the shadow on demand and store it in the map.
1100       Value **ShadowPtr = &ShadowMap[V];
1101       if (*ShadowPtr)
1102         return *ShadowPtr;
1103       Function *F = A->getParent();
1104       IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
1105       unsigned ArgOffset = 0;
1106       const DataLayout &DL = F->getParent()->getDataLayout();
1107       for (auto &FArg : F->args()) {
1108         if (!FArg.getType()->isSized()) {
1109           DEBUG(dbgs() << "Arg is not sized\n");
1110           continue;
1111         }
1112         unsigned Size =
1113             FArg.hasByValAttr()
1114                 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
1115                 : DL.getTypeAllocSize(FArg.getType());
1116         if (A == &FArg) {
1117           bool Overflow = ArgOffset + Size > kParamTLSSize;
1118           Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1119           if (FArg.hasByValAttr()) {
1120             // ByVal pointer itself has clean shadow. We copy the actual
1121             // argument shadow to the underlying memory.
1122             // Figure out maximal valid memcpy alignment.
1123             unsigned ArgAlign = FArg.getParamAlignment();
1124             if (ArgAlign == 0) {
1125               Type *EltType = A->getType()->getPointerElementType();
1126               ArgAlign = DL.getABITypeAlignment(EltType);
1127             }
1128             if (Overflow) {
1129               // ParamTLS overflow.
1130               EntryIRB.CreateMemSet(
1131                   getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
1132                   Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
1133             } else {
1134               unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1135               Value *Cpy = EntryIRB.CreateMemCpy(
1136                   getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
1137                   CopyAlign);
1138               DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
1139               (void)Cpy;
1140             }
1141             *ShadowPtr = getCleanShadow(V);
1142           } else {
1143             if (Overflow) {
1144               // ParamTLS overflow.
1145               *ShadowPtr = getCleanShadow(V);
1146             } else {
1147               *ShadowPtr =
1148                   EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1149             }
1150           }
1151           DEBUG(dbgs() << "  ARG:    "  << FArg << " ==> " <<
1152                 **ShadowPtr << "\n");
1153           if (MS.TrackOrigins && !Overflow) {
1154             Value *OriginPtr =
1155                 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
1156             setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
1157           } else {
1158             setOrigin(A, getCleanOrigin());
1159           }
1160         }
1161         ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
1162       }
1163       assert(*ShadowPtr && "Could not find shadow for an argument");
1164       return *ShadowPtr;
1165     }
1166     // For everything else the shadow is zero.
1167     return getCleanShadow(V);
1168   }
1169 
1170   /// \brief Get the shadow for i-th argument of the instruction I.
1171   Value *getShadow(Instruction *I, int i) {
1172     return getShadow(I->getOperand(i));
1173   }
1174 
1175   /// \brief Get the origin for a value.
1176   Value *getOrigin(Value *V) {
1177     if (!MS.TrackOrigins) return nullptr;
1178     if (!PropagateShadow) return getCleanOrigin();
1179     if (isa<Constant>(V)) return getCleanOrigin();
1180     assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1181            "Unexpected value type in getOrigin()");
1182     Value *Origin = OriginMap[V];
1183     assert(Origin && "Missing origin");
1184     return Origin;
1185   }
1186 
1187   /// \brief Get the origin for i-th argument of the instruction I.
1188   Value *getOrigin(Instruction *I, int i) {
1189     return getOrigin(I->getOperand(i));
1190   }
1191 
1192   /// \brief Remember the place where a shadow check should be inserted.
1193   ///
1194   /// This location will be later instrumented with a check that will print a
1195   /// UMR warning in runtime if the shadow value is not 0.
1196   void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1197     assert(Shadow);
1198     if (!InsertChecks) return;
1199 #ifndef NDEBUG
1200     Type *ShadowTy = Shadow->getType();
1201     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1202            "Can only insert checks for integer and vector shadow types");
1203 #endif
1204     InstrumentationList.push_back(
1205         ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1206   }
1207 
1208   /// \brief Remember the place where a shadow check should be inserted.
1209   ///
1210   /// This location will be later instrumented with a check that will print a
1211   /// UMR warning in runtime if the value is not fully defined.
1212   void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1213     assert(Val);
1214     Value *Shadow, *Origin;
1215     if (ClCheckConstantShadow) {
1216       Shadow = getShadow(Val);
1217       if (!Shadow) return;
1218       Origin = getOrigin(Val);
1219     } else {
1220       Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1221       if (!Shadow) return;
1222       Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1223     }
1224     insertShadowCheck(Shadow, Origin, OrigIns);
1225   }
1226 
1227   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1228     switch (a) {
1229       case NotAtomic:
1230         return NotAtomic;
1231       case Unordered:
1232       case Monotonic:
1233       case Release:
1234         return Release;
1235       case Acquire:
1236       case AcquireRelease:
1237         return AcquireRelease;
1238       case SequentiallyConsistent:
1239         return SequentiallyConsistent;
1240     }
1241     llvm_unreachable("Unknown ordering");
1242   }
1243 
1244   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1245     switch (a) {
1246       case NotAtomic:
1247         return NotAtomic;
1248       case Unordered:
1249       case Monotonic:
1250       case Acquire:
1251         return Acquire;
1252       case Release:
1253       case AcquireRelease:
1254         return AcquireRelease;
1255       case SequentiallyConsistent:
1256         return SequentiallyConsistent;
1257     }
1258     llvm_unreachable("Unknown ordering");
1259   }
1260 
1261   // ------------------- Visitors.
1262 
1263   /// \brief Instrument LoadInst
1264   ///
1265   /// Loads the corresponding shadow and (optionally) origin.
1266   /// Optionally, checks that the load address is fully defined.
1267   void visitLoadInst(LoadInst &I) {
1268     assert(I.getType()->isSized() && "Load type must have size");
1269     IRBuilder<> IRB(I.getNextNode());
1270     Type *ShadowTy = getShadowTy(&I);
1271     Value *Addr = I.getPointerOperand();
1272     if (PropagateShadow && !I.getMetadata("nosanitize")) {
1273       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1274       setShadow(&I,
1275                 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1276     } else {
1277       setShadow(&I, getCleanShadow(&I));
1278     }
1279 
1280     if (ClCheckAccessAddress)
1281       insertShadowCheck(I.getPointerOperand(), &I);
1282 
1283     if (I.isAtomic())
1284       I.setOrdering(addAcquireOrdering(I.getOrdering()));
1285 
1286     if (MS.TrackOrigins) {
1287       if (PropagateShadow) {
1288         unsigned Alignment = I.getAlignment();
1289         unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1290         setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
1291                                             OriginAlignment));
1292       } else {
1293         setOrigin(&I, getCleanOrigin());
1294       }
1295     }
1296   }
1297 
1298   /// \brief Instrument StoreInst
1299   ///
1300   /// Stores the corresponding shadow and (optionally) origin.
1301   /// Optionally, checks that the store address is fully defined.
1302   void visitStoreInst(StoreInst &I) {
1303     StoreList.push_back(&I);
1304   }
1305 
1306   void handleCASOrRMW(Instruction &I) {
1307     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1308 
1309     IRBuilder<> IRB(&I);
1310     Value *Addr = I.getOperand(0);
1311     Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1312 
1313     if (ClCheckAccessAddress)
1314       insertShadowCheck(Addr, &I);
1315 
1316     // Only test the conditional argument of cmpxchg instruction.
1317     // The other argument can potentially be uninitialized, but we can not
1318     // detect this situation reliably without possible false positives.
1319     if (isa<AtomicCmpXchgInst>(I))
1320       insertShadowCheck(I.getOperand(1), &I);
1321 
1322     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1323 
1324     setShadow(&I, getCleanShadow(&I));
1325     setOrigin(&I, getCleanOrigin());
1326   }
1327 
1328   void visitAtomicRMWInst(AtomicRMWInst &I) {
1329     handleCASOrRMW(I);
1330     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1331   }
1332 
1333   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1334     handleCASOrRMW(I);
1335     I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1336   }
1337 
1338   // Vector manipulation.
1339   void visitExtractElementInst(ExtractElementInst &I) {
1340     insertShadowCheck(I.getOperand(1), &I);
1341     IRBuilder<> IRB(&I);
1342     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1343               "_msprop"));
1344     setOrigin(&I, getOrigin(&I, 0));
1345   }
1346 
1347   void visitInsertElementInst(InsertElementInst &I) {
1348     insertShadowCheck(I.getOperand(2), &I);
1349     IRBuilder<> IRB(&I);
1350     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1351               I.getOperand(2), "_msprop"));
1352     setOriginForNaryOp(I);
1353   }
1354 
1355   void visitShuffleVectorInst(ShuffleVectorInst &I) {
1356     insertShadowCheck(I.getOperand(2), &I);
1357     IRBuilder<> IRB(&I);
1358     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1359               I.getOperand(2), "_msprop"));
1360     setOriginForNaryOp(I);
1361   }
1362 
1363   // Casts.
1364   void visitSExtInst(SExtInst &I) {
1365     IRBuilder<> IRB(&I);
1366     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1367     setOrigin(&I, getOrigin(&I, 0));
1368   }
1369 
1370   void visitZExtInst(ZExtInst &I) {
1371     IRBuilder<> IRB(&I);
1372     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1373     setOrigin(&I, getOrigin(&I, 0));
1374   }
1375 
1376   void visitTruncInst(TruncInst &I) {
1377     IRBuilder<> IRB(&I);
1378     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1379     setOrigin(&I, getOrigin(&I, 0));
1380   }
1381 
1382   void visitBitCastInst(BitCastInst &I) {
1383     // Special case: if this is the bitcast (there is exactly 1 allowed) between
1384     // a musttail call and a ret, don't instrument. New instructions are not
1385     // allowed after a musttail call.
1386     if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
1387       if (CI->isMustTailCall())
1388         return;
1389     IRBuilder<> IRB(&I);
1390     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1391     setOrigin(&I, getOrigin(&I, 0));
1392   }
1393 
1394   void visitPtrToIntInst(PtrToIntInst &I) {
1395     IRBuilder<> IRB(&I);
1396     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1397              "_msprop_ptrtoint"));
1398     setOrigin(&I, getOrigin(&I, 0));
1399   }
1400 
1401   void visitIntToPtrInst(IntToPtrInst &I) {
1402     IRBuilder<> IRB(&I);
1403     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1404              "_msprop_inttoptr"));
1405     setOrigin(&I, getOrigin(&I, 0));
1406   }
1407 
1408   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1409   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1410   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1411   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1412   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1413   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1414 
1415   /// \brief Propagate shadow for bitwise AND.
1416   ///
1417   /// This code is exact, i.e. if, for example, a bit in the left argument
1418   /// is defined and 0, then neither the value not definedness of the
1419   /// corresponding bit in B don't affect the resulting shadow.
1420   void visitAnd(BinaryOperator &I) {
1421     IRBuilder<> IRB(&I);
1422     //  "And" of 0 and a poisoned value results in unpoisoned value.
1423     //  1&1 => 1;     0&1 => 0;     p&1 => p;
1424     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
1425     //  1&p => p;     0&p => 0;     p&p => p;
1426     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1427     Value *S1 = getShadow(&I, 0);
1428     Value *S2 = getShadow(&I, 1);
1429     Value *V1 = I.getOperand(0);
1430     Value *V2 = I.getOperand(1);
1431     if (V1->getType() != S1->getType()) {
1432       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1433       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1434     }
1435     Value *S1S2 = IRB.CreateAnd(S1, S2);
1436     Value *V1S2 = IRB.CreateAnd(V1, S2);
1437     Value *S1V2 = IRB.CreateAnd(S1, V2);
1438     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1439     setOriginForNaryOp(I);
1440   }
1441 
1442   void visitOr(BinaryOperator &I) {
1443     IRBuilder<> IRB(&I);
1444     //  "Or" of 1 and a poisoned value results in unpoisoned value.
1445     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
1446     //  1|0 => 1;     0|0 => 0;     p|0 => p;
1447     //  1|p => 1;     0|p => p;     p|p => p;
1448     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1449     Value *S1 = getShadow(&I, 0);
1450     Value *S2 = getShadow(&I, 1);
1451     Value *V1 = IRB.CreateNot(I.getOperand(0));
1452     Value *V2 = IRB.CreateNot(I.getOperand(1));
1453     if (V1->getType() != S1->getType()) {
1454       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1455       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1456     }
1457     Value *S1S2 = IRB.CreateAnd(S1, S2);
1458     Value *V1S2 = IRB.CreateAnd(V1, S2);
1459     Value *S1V2 = IRB.CreateAnd(S1, V2);
1460     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1461     setOriginForNaryOp(I);
1462   }
1463 
1464   /// \brief Default propagation of shadow and/or origin.
1465   ///
1466   /// This class implements the general case of shadow propagation, used in all
1467   /// cases where we don't know and/or don't care about what the operation
1468   /// actually does. It converts all input shadow values to a common type
1469   /// (extending or truncating as necessary), and bitwise OR's them.
1470   ///
1471   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1472   /// fully initialized), and less prone to false positives.
1473   ///
1474   /// This class also implements the general case of origin propagation. For a
1475   /// Nary operation, result origin is set to the origin of an argument that is
1476   /// not entirely initialized. If there is more than one such arguments, the
1477   /// rightmost of them is picked. It does not matter which one is picked if all
1478   /// arguments are initialized.
1479   template <bool CombineShadow>
1480   class Combiner {
1481     Value *Shadow;
1482     Value *Origin;
1483     IRBuilder<> &IRB;
1484     MemorySanitizerVisitor *MSV;
1485 
1486   public:
1487     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1488       Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
1489 
1490     /// \brief Add a pair of shadow and origin values to the mix.
1491     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1492       if (CombineShadow) {
1493         assert(OpShadow);
1494         if (!Shadow)
1495           Shadow = OpShadow;
1496         else {
1497           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1498           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1499         }
1500       }
1501 
1502       if (MSV->MS.TrackOrigins) {
1503         assert(OpOrigin);
1504         if (!Origin) {
1505           Origin = OpOrigin;
1506         } else {
1507           Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1508           // No point in adding something that might result in 0 origin value.
1509           if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1510             Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1511             Value *Cond =
1512                 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1513             Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1514           }
1515         }
1516       }
1517       return *this;
1518     }
1519 
1520     /// \brief Add an application value to the mix.
1521     Combiner &Add(Value *V) {
1522       Value *OpShadow = MSV->getShadow(V);
1523       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
1524       return Add(OpShadow, OpOrigin);
1525     }
1526 
1527     /// \brief Set the current combined values as the given instruction's shadow
1528     /// and origin.
1529     void Done(Instruction *I) {
1530       if (CombineShadow) {
1531         assert(Shadow);
1532         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1533         MSV->setShadow(I, Shadow);
1534       }
1535       if (MSV->MS.TrackOrigins) {
1536         assert(Origin);
1537         MSV->setOrigin(I, Origin);
1538       }
1539     }
1540   };
1541 
1542   typedef Combiner<true> ShadowAndOriginCombiner;
1543   typedef Combiner<false> OriginCombiner;
1544 
1545   /// \brief Propagate origin for arbitrary operation.
1546   void setOriginForNaryOp(Instruction &I) {
1547     if (!MS.TrackOrigins) return;
1548     IRBuilder<> IRB(&I);
1549     OriginCombiner OC(this, IRB);
1550     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1551       OC.Add(OI->get());
1552     OC.Done(&I);
1553   }
1554 
1555   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1556     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1557            "Vector of pointers is not a valid shadow type");
1558     return Ty->isVectorTy() ?
1559       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1560       Ty->getPrimitiveSizeInBits();
1561   }
1562 
1563   /// \brief Cast between two shadow types, extending or truncating as
1564   /// necessary.
1565   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1566                           bool Signed = false) {
1567     Type *srcTy = V->getType();
1568     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1569       return IRB.CreateIntCast(V, dstTy, Signed);
1570     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1571         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1572       return IRB.CreateIntCast(V, dstTy, Signed);
1573     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1574     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1575     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1576     Value *V2 =
1577       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1578     return IRB.CreateBitCast(V2, dstTy);
1579     // TODO: handle struct types.
1580   }
1581 
1582   /// \brief Cast an application value to the type of its own shadow.
1583   Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1584     Type *ShadowTy = getShadowTy(V);
1585     if (V->getType() == ShadowTy)
1586       return V;
1587     if (V->getType()->isPtrOrPtrVectorTy())
1588       return IRB.CreatePtrToInt(V, ShadowTy);
1589     else
1590       return IRB.CreateBitCast(V, ShadowTy);
1591   }
1592 
1593   /// \brief Propagate shadow for arbitrary operation.
1594   void handleShadowOr(Instruction &I) {
1595     IRBuilder<> IRB(&I);
1596     ShadowAndOriginCombiner SC(this, IRB);
1597     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1598       SC.Add(OI->get());
1599     SC.Done(&I);
1600   }
1601 
1602   // \brief Handle multiplication by constant.
1603   //
1604   // Handle a special case of multiplication by constant that may have one or
1605   // more zeros in the lower bits. This makes corresponding number of lower bits
1606   // of the result zero as well. We model it by shifting the other operand
1607   // shadow left by the required number of bits. Effectively, we transform
1608   // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1609   // We use multiplication by 2**N instead of shift to cover the case of
1610   // multiplication by 0, which may occur in some elements of a vector operand.
1611   void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1612                            Value *OtherArg) {
1613     Constant *ShadowMul;
1614     Type *Ty = ConstArg->getType();
1615     if (Ty->isVectorTy()) {
1616       unsigned NumElements = Ty->getVectorNumElements();
1617       Type *EltTy = Ty->getSequentialElementType();
1618       SmallVector<Constant *, 16> Elements;
1619       for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1620         if (ConstantInt *Elt =
1621                 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx))) {
1622           APInt V = Elt->getValue();
1623           APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1624           Elements.push_back(ConstantInt::get(EltTy, V2));
1625         } else {
1626           Elements.push_back(ConstantInt::get(EltTy, 1));
1627         }
1628       }
1629       ShadowMul = ConstantVector::get(Elements);
1630     } else {
1631       if (ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg)) {
1632         APInt V = Elt->getValue();
1633         APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1634         ShadowMul = ConstantInt::get(Ty, V2);
1635       } else {
1636         ShadowMul = ConstantInt::get(Ty, 1);
1637       }
1638     }
1639 
1640     IRBuilder<> IRB(&I);
1641     setShadow(&I,
1642               IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1643     setOrigin(&I, getOrigin(OtherArg));
1644   }
1645 
1646   void visitMul(BinaryOperator &I) {
1647     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1648     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1649     if (constOp0 && !constOp1)
1650       handleMulByConstant(I, constOp0, I.getOperand(1));
1651     else if (constOp1 && !constOp0)
1652       handleMulByConstant(I, constOp1, I.getOperand(0));
1653     else
1654       handleShadowOr(I);
1655   }
1656 
1657   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1658   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1659   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1660   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1661   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1662   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1663 
1664   void handleDiv(Instruction &I) {
1665     IRBuilder<> IRB(&I);
1666     // Strict on the second argument.
1667     insertShadowCheck(I.getOperand(1), &I);
1668     setShadow(&I, getShadow(&I, 0));
1669     setOrigin(&I, getOrigin(&I, 0));
1670   }
1671 
1672   void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1673   void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1674   void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1675   void visitURem(BinaryOperator &I) { handleDiv(I); }
1676   void visitSRem(BinaryOperator &I) { handleDiv(I); }
1677   void visitFRem(BinaryOperator &I) { handleDiv(I); }
1678 
1679   /// \brief Instrument == and != comparisons.
1680   ///
1681   /// Sometimes the comparison result is known even if some of the bits of the
1682   /// arguments are not.
1683   void handleEqualityComparison(ICmpInst &I) {
1684     IRBuilder<> IRB(&I);
1685     Value *A = I.getOperand(0);
1686     Value *B = I.getOperand(1);
1687     Value *Sa = getShadow(A);
1688     Value *Sb = getShadow(B);
1689 
1690     // Get rid of pointers and vectors of pointers.
1691     // For ints (and vectors of ints), types of A and Sa match,
1692     // and this is a no-op.
1693     A = IRB.CreatePointerCast(A, Sa->getType());
1694     B = IRB.CreatePointerCast(B, Sb->getType());
1695 
1696     // A == B  <==>  (C = A^B) == 0
1697     // A != B  <==>  (C = A^B) != 0
1698     // Sc = Sa | Sb
1699     Value *C = IRB.CreateXor(A, B);
1700     Value *Sc = IRB.CreateOr(Sa, Sb);
1701     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1702     // Result is defined if one of the following is true
1703     // * there is a defined 1 bit in C
1704     // * C is fully defined
1705     // Si = !(C & ~Sc) && Sc
1706     Value *Zero = Constant::getNullValue(Sc->getType());
1707     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1708     Value *Si =
1709       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1710                     IRB.CreateICmpEQ(
1711                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1712     Si->setName("_msprop_icmp");
1713     setShadow(&I, Si);
1714     setOriginForNaryOp(I);
1715   }
1716 
1717   /// \brief Build the lowest possible value of V, taking into account V's
1718   ///        uninitialized bits.
1719   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1720                                 bool isSigned) {
1721     if (isSigned) {
1722       // Split shadow into sign bit and other bits.
1723       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1724       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1725       // Maximise the undefined shadow bit, minimize other undefined bits.
1726       return
1727         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1728     } else {
1729       // Minimize undefined bits.
1730       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1731     }
1732   }
1733 
1734   /// \brief Build the highest possible value of V, taking into account V's
1735   ///        uninitialized bits.
1736   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1737                                 bool isSigned) {
1738     if (isSigned) {
1739       // Split shadow into sign bit and other bits.
1740       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1741       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1742       // Minimise the undefined shadow bit, maximise other undefined bits.
1743       return
1744         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1745     } else {
1746       // Maximize undefined bits.
1747       return IRB.CreateOr(A, Sa);
1748     }
1749   }
1750 
1751   /// \brief Instrument relational comparisons.
1752   ///
1753   /// This function does exact shadow propagation for all relational
1754   /// comparisons of integers, pointers and vectors of those.
1755   /// FIXME: output seems suboptimal when one of the operands is a constant
1756   void handleRelationalComparisonExact(ICmpInst &I) {
1757     IRBuilder<> IRB(&I);
1758     Value *A = I.getOperand(0);
1759     Value *B = I.getOperand(1);
1760     Value *Sa = getShadow(A);
1761     Value *Sb = getShadow(B);
1762 
1763     // Get rid of pointers and vectors of pointers.
1764     // For ints (and vectors of ints), types of A and Sa match,
1765     // and this is a no-op.
1766     A = IRB.CreatePointerCast(A, Sa->getType());
1767     B = IRB.CreatePointerCast(B, Sb->getType());
1768 
1769     // Let [a0, a1] be the interval of possible values of A, taking into account
1770     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1771     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1772     bool IsSigned = I.isSigned();
1773     Value *S1 = IRB.CreateICmp(I.getPredicate(),
1774                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
1775                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
1776     Value *S2 = IRB.CreateICmp(I.getPredicate(),
1777                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
1778                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
1779     Value *Si = IRB.CreateXor(S1, S2);
1780     setShadow(&I, Si);
1781     setOriginForNaryOp(I);
1782   }
1783 
1784   /// \brief Instrument signed relational comparisons.
1785   ///
1786   /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest
1787   /// bit of the shadow. Everything else is delegated to handleShadowOr().
1788   void handleSignedRelationalComparison(ICmpInst &I) {
1789     Constant *constOp;
1790     Value *op = nullptr;
1791     CmpInst::Predicate pre;
1792     if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) {
1793       op = I.getOperand(0);
1794       pre = I.getPredicate();
1795     } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) {
1796       op = I.getOperand(1);
1797       pre = I.getSwappedPredicate();
1798     } else {
1799       handleShadowOr(I);
1800       return;
1801     }
1802 
1803     if ((constOp->isNullValue() &&
1804          (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) ||
1805         (constOp->isAllOnesValue() &&
1806          (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) {
1807       IRBuilder<> IRB(&I);
1808       Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op),
1809                                         "_msprop_icmp_s");
1810       setShadow(&I, Shadow);
1811       setOrigin(&I, getOrigin(op));
1812     } else {
1813       handleShadowOr(I);
1814     }
1815   }
1816 
1817   void visitICmpInst(ICmpInst &I) {
1818     if (!ClHandleICmp) {
1819       handleShadowOr(I);
1820       return;
1821     }
1822     if (I.isEquality()) {
1823       handleEqualityComparison(I);
1824       return;
1825     }
1826 
1827     assert(I.isRelational());
1828     if (ClHandleICmpExact) {
1829       handleRelationalComparisonExact(I);
1830       return;
1831     }
1832     if (I.isSigned()) {
1833       handleSignedRelationalComparison(I);
1834       return;
1835     }
1836 
1837     assert(I.isUnsigned());
1838     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1839       handleRelationalComparisonExact(I);
1840       return;
1841     }
1842 
1843     handleShadowOr(I);
1844   }
1845 
1846   void visitFCmpInst(FCmpInst &I) {
1847     handleShadowOr(I);
1848   }
1849 
1850   void handleShift(BinaryOperator &I) {
1851     IRBuilder<> IRB(&I);
1852     // If any of the S2 bits are poisoned, the whole thing is poisoned.
1853     // Otherwise perform the same shift on S1.
1854     Value *S1 = getShadow(&I, 0);
1855     Value *S2 = getShadow(&I, 1);
1856     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1857                                    S2->getType());
1858     Value *V2 = I.getOperand(1);
1859     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1860     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1861     setOriginForNaryOp(I);
1862   }
1863 
1864   void visitShl(BinaryOperator &I) { handleShift(I); }
1865   void visitAShr(BinaryOperator &I) { handleShift(I); }
1866   void visitLShr(BinaryOperator &I) { handleShift(I); }
1867 
1868   /// \brief Instrument llvm.memmove
1869   ///
1870   /// At this point we don't know if llvm.memmove will be inlined or not.
1871   /// If we don't instrument it and it gets inlined,
1872   /// our interceptor will not kick in and we will lose the memmove.
1873   /// If we instrument the call here, but it does not get inlined,
1874   /// we will memove the shadow twice: which is bad in case
1875   /// of overlapping regions. So, we simply lower the intrinsic to a call.
1876   ///
1877   /// Similar situation exists for memcpy and memset.
1878   void visitMemMoveInst(MemMoveInst &I) {
1879     IRBuilder<> IRB(&I);
1880     IRB.CreateCall(
1881         MS.MemmoveFn,
1882         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1883          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1884          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1885     I.eraseFromParent();
1886   }
1887 
1888   // Similar to memmove: avoid copying shadow twice.
1889   // This is somewhat unfortunate as it may slowdown small constant memcpys.
1890   // FIXME: consider doing manual inline for small constant sizes and proper
1891   // alignment.
1892   void visitMemCpyInst(MemCpyInst &I) {
1893     IRBuilder<> IRB(&I);
1894     IRB.CreateCall(
1895         MS.MemcpyFn,
1896         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1897          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1898          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1899     I.eraseFromParent();
1900   }
1901 
1902   // Same as memcpy.
1903   void visitMemSetInst(MemSetInst &I) {
1904     IRBuilder<> IRB(&I);
1905     IRB.CreateCall(
1906         MS.MemsetFn,
1907         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1908          IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1909          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1910     I.eraseFromParent();
1911   }
1912 
1913   void visitVAStartInst(VAStartInst &I) {
1914     VAHelper->visitVAStartInst(I);
1915   }
1916 
1917   void visitVACopyInst(VACopyInst &I) {
1918     VAHelper->visitVACopyInst(I);
1919   }
1920 
1921   /// \brief Handle vector store-like intrinsics.
1922   ///
1923   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1924   /// has 1 pointer argument and 1 vector argument, returns void.
1925   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1926     IRBuilder<> IRB(&I);
1927     Value* Addr = I.getArgOperand(0);
1928     Value *Shadow = getShadow(&I, 1);
1929     Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1930 
1931     // We don't know the pointer alignment (could be unaligned SSE store!).
1932     // Have to assume to worst case.
1933     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1934 
1935     if (ClCheckAccessAddress)
1936       insertShadowCheck(Addr, &I);
1937 
1938     // FIXME: use ClStoreCleanOrigin
1939     // FIXME: factor out common code from materializeStores
1940     if (MS.TrackOrigins)
1941       IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
1942     return true;
1943   }
1944 
1945   /// \brief Handle vector load-like intrinsics.
1946   ///
1947   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1948   /// has 1 pointer argument, returns a vector.
1949   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1950     IRBuilder<> IRB(&I);
1951     Value *Addr = I.getArgOperand(0);
1952 
1953     Type *ShadowTy = getShadowTy(&I);
1954     if (PropagateShadow) {
1955       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1956       // We don't know the pointer alignment (could be unaligned SSE load!).
1957       // Have to assume to worst case.
1958       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1959     } else {
1960       setShadow(&I, getCleanShadow(&I));
1961     }
1962 
1963     if (ClCheckAccessAddress)
1964       insertShadowCheck(Addr, &I);
1965 
1966     if (MS.TrackOrigins) {
1967       if (PropagateShadow)
1968         setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
1969       else
1970         setOrigin(&I, getCleanOrigin());
1971     }
1972     return true;
1973   }
1974 
1975   /// \brief Handle (SIMD arithmetic)-like intrinsics.
1976   ///
1977   /// Instrument intrinsics with any number of arguments of the same type,
1978   /// equal to the return type. The type should be simple (no aggregates or
1979   /// pointers; vectors are fine).
1980   /// Caller guarantees that this intrinsic does not access memory.
1981   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1982     Type *RetTy = I.getType();
1983     if (!(RetTy->isIntOrIntVectorTy() ||
1984           RetTy->isFPOrFPVectorTy() ||
1985           RetTy->isX86_MMXTy()))
1986       return false;
1987 
1988     unsigned NumArgOperands = I.getNumArgOperands();
1989 
1990     for (unsigned i = 0; i < NumArgOperands; ++i) {
1991       Type *Ty = I.getArgOperand(i)->getType();
1992       if (Ty != RetTy)
1993         return false;
1994     }
1995 
1996     IRBuilder<> IRB(&I);
1997     ShadowAndOriginCombiner SC(this, IRB);
1998     for (unsigned i = 0; i < NumArgOperands; ++i)
1999       SC.Add(I.getArgOperand(i));
2000     SC.Done(&I);
2001 
2002     return true;
2003   }
2004 
2005   /// \brief Heuristically instrument unknown intrinsics.
2006   ///
2007   /// The main purpose of this code is to do something reasonable with all
2008   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
2009   /// We recognize several classes of intrinsics by their argument types and
2010   /// ModRefBehaviour and apply special intrumentation when we are reasonably
2011   /// sure that we know what the intrinsic does.
2012   ///
2013   /// We special-case intrinsics where this approach fails. See llvm.bswap
2014   /// handling as an example of that.
2015   bool handleUnknownIntrinsic(IntrinsicInst &I) {
2016     unsigned NumArgOperands = I.getNumArgOperands();
2017     if (NumArgOperands == 0)
2018       return false;
2019 
2020     if (NumArgOperands == 2 &&
2021         I.getArgOperand(0)->getType()->isPointerTy() &&
2022         I.getArgOperand(1)->getType()->isVectorTy() &&
2023         I.getType()->isVoidTy() &&
2024         !I.onlyReadsMemory()) {
2025       // This looks like a vector store.
2026       return handleVectorStoreIntrinsic(I);
2027     }
2028 
2029     if (NumArgOperands == 1 &&
2030         I.getArgOperand(0)->getType()->isPointerTy() &&
2031         I.getType()->isVectorTy() &&
2032         I.onlyReadsMemory()) {
2033       // This looks like a vector load.
2034       return handleVectorLoadIntrinsic(I);
2035     }
2036 
2037     if (I.doesNotAccessMemory())
2038       if (maybeHandleSimpleNomemIntrinsic(I))
2039         return true;
2040 
2041     // FIXME: detect and handle SSE maskstore/maskload
2042     return false;
2043   }
2044 
2045   void handleBswap(IntrinsicInst &I) {
2046     IRBuilder<> IRB(&I);
2047     Value *Op = I.getArgOperand(0);
2048     Type *OpType = Op->getType();
2049     Function *BswapFunc = Intrinsic::getDeclaration(
2050       F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
2051     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2052     setOrigin(&I, getOrigin(Op));
2053   }
2054 
2055   // \brief Instrument vector convert instrinsic.
2056   //
2057   // This function instruments intrinsics like cvtsi2ss:
2058   // %Out = int_xxx_cvtyyy(%ConvertOp)
2059   // or
2060   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2061   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2062   // number \p Out elements, and (if has 2 arguments) copies the rest of the
2063   // elements from \p CopyOp.
2064   // In most cases conversion involves floating-point value which may trigger a
2065   // hardware exception when not fully initialized. For this reason we require
2066   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2067   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2068   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2069   // return a fully initialized value.
2070   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2071     IRBuilder<> IRB(&I);
2072     Value *CopyOp, *ConvertOp;
2073 
2074     switch (I.getNumArgOperands()) {
2075     case 3:
2076       assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
2077     case 2:
2078       CopyOp = I.getArgOperand(0);
2079       ConvertOp = I.getArgOperand(1);
2080       break;
2081     case 1:
2082       ConvertOp = I.getArgOperand(0);
2083       CopyOp = nullptr;
2084       break;
2085     default:
2086       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2087     }
2088 
2089     // The first *NumUsedElements* elements of ConvertOp are converted to the
2090     // same number of output elements. The rest of the output is copied from
2091     // CopyOp, or (if not available) filled with zeroes.
2092     // Combine shadow for elements of ConvertOp that are used in this operation,
2093     // and insert a check.
2094     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2095     // int->any conversion.
2096     Value *ConvertShadow = getShadow(ConvertOp);
2097     Value *AggShadow = nullptr;
2098     if (ConvertOp->getType()->isVectorTy()) {
2099       AggShadow = IRB.CreateExtractElement(
2100           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2101       for (int i = 1; i < NumUsedElements; ++i) {
2102         Value *MoreShadow = IRB.CreateExtractElement(
2103             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2104         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2105       }
2106     } else {
2107       AggShadow = ConvertShadow;
2108     }
2109     assert(AggShadow->getType()->isIntegerTy());
2110     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2111 
2112     // Build result shadow by zero-filling parts of CopyOp shadow that come from
2113     // ConvertOp.
2114     if (CopyOp) {
2115       assert(CopyOp->getType() == I.getType());
2116       assert(CopyOp->getType()->isVectorTy());
2117       Value *ResultShadow = getShadow(CopyOp);
2118       Type *EltTy = ResultShadow->getType()->getVectorElementType();
2119       for (int i = 0; i < NumUsedElements; ++i) {
2120         ResultShadow = IRB.CreateInsertElement(
2121             ResultShadow, ConstantInt::getNullValue(EltTy),
2122             ConstantInt::get(IRB.getInt32Ty(), i));
2123       }
2124       setShadow(&I, ResultShadow);
2125       setOrigin(&I, getOrigin(CopyOp));
2126     } else {
2127       setShadow(&I, getCleanShadow(&I));
2128       setOrigin(&I, getCleanOrigin());
2129     }
2130   }
2131 
2132   // Given a scalar or vector, extract lower 64 bits (or less), and return all
2133   // zeroes if it is zero, and all ones otherwise.
2134   Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2135     if (S->getType()->isVectorTy())
2136       S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2137     assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2138     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2139     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2140   }
2141 
2142   Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2143     Type *T = S->getType();
2144     assert(T->isVectorTy());
2145     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2146     return IRB.CreateSExt(S2, T);
2147   }
2148 
2149   // \brief Instrument vector shift instrinsic.
2150   //
2151   // This function instruments intrinsics like int_x86_avx2_psll_w.
2152   // Intrinsic shifts %In by %ShiftSize bits.
2153   // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2154   // size, and the rest is ignored. Behavior is defined even if shift size is
2155   // greater than register (or field) width.
2156   void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2157     assert(I.getNumArgOperands() == 2);
2158     IRBuilder<> IRB(&I);
2159     // If any of the S2 bits are poisoned, the whole thing is poisoned.
2160     // Otherwise perform the same shift on S1.
2161     Value *S1 = getShadow(&I, 0);
2162     Value *S2 = getShadow(&I, 1);
2163     Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2164                              : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2165     Value *V1 = I.getOperand(0);
2166     Value *V2 = I.getOperand(1);
2167     Value *Shift = IRB.CreateCall(I.getCalledValue(),
2168                                   {IRB.CreateBitCast(S1, V1->getType()), V2});
2169     Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2170     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2171     setOriginForNaryOp(I);
2172   }
2173 
2174   // \brief Get an X86_MMX-sized vector type.
2175   Type *getMMXVectorTy(unsigned EltSizeInBits) {
2176     const unsigned X86_MMXSizeInBits = 64;
2177     return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2178                            X86_MMXSizeInBits / EltSizeInBits);
2179   }
2180 
2181   // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2182   // intrinsic.
2183   Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2184     switch (id) {
2185       case llvm::Intrinsic::x86_sse2_packsswb_128:
2186       case llvm::Intrinsic::x86_sse2_packuswb_128:
2187         return llvm::Intrinsic::x86_sse2_packsswb_128;
2188 
2189       case llvm::Intrinsic::x86_sse2_packssdw_128:
2190       case llvm::Intrinsic::x86_sse41_packusdw:
2191         return llvm::Intrinsic::x86_sse2_packssdw_128;
2192 
2193       case llvm::Intrinsic::x86_avx2_packsswb:
2194       case llvm::Intrinsic::x86_avx2_packuswb:
2195         return llvm::Intrinsic::x86_avx2_packsswb;
2196 
2197       case llvm::Intrinsic::x86_avx2_packssdw:
2198       case llvm::Intrinsic::x86_avx2_packusdw:
2199         return llvm::Intrinsic::x86_avx2_packssdw;
2200 
2201       case llvm::Intrinsic::x86_mmx_packsswb:
2202       case llvm::Intrinsic::x86_mmx_packuswb:
2203         return llvm::Intrinsic::x86_mmx_packsswb;
2204 
2205       case llvm::Intrinsic::x86_mmx_packssdw:
2206         return llvm::Intrinsic::x86_mmx_packssdw;
2207       default:
2208         llvm_unreachable("unexpected intrinsic id");
2209     }
2210   }
2211 
2212   // \brief Instrument vector pack instrinsic.
2213   //
2214   // This function instruments intrinsics like x86_mmx_packsswb, that
2215   // packs elements of 2 input vectors into half as many bits with saturation.
2216   // Shadow is propagated with the signed variant of the same intrinsic applied
2217   // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2218   // EltSizeInBits is used only for x86mmx arguments.
2219   void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
2220     assert(I.getNumArgOperands() == 2);
2221     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2222     IRBuilder<> IRB(&I);
2223     Value *S1 = getShadow(&I, 0);
2224     Value *S2 = getShadow(&I, 1);
2225     assert(isX86_MMX || S1->getType()->isVectorTy());
2226 
2227     // SExt and ICmpNE below must apply to individual elements of input vectors.
2228     // In case of x86mmx arguments, cast them to appropriate vector types and
2229     // back.
2230     Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2231     if (isX86_MMX) {
2232       S1 = IRB.CreateBitCast(S1, T);
2233       S2 = IRB.CreateBitCast(S2, T);
2234     }
2235     Value *S1_ext = IRB.CreateSExt(
2236         IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2237     Value *S2_ext = IRB.CreateSExt(
2238         IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
2239     if (isX86_MMX) {
2240       Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2241       S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2242       S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2243     }
2244 
2245     Function *ShadowFn = Intrinsic::getDeclaration(
2246         F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2247 
2248     Value *S =
2249         IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
2250     if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2251     setShadow(&I, S);
2252     setOriginForNaryOp(I);
2253   }
2254 
2255   // \brief Instrument sum-of-absolute-differencies intrinsic.
2256   void handleVectorSadIntrinsic(IntrinsicInst &I) {
2257     const unsigned SignificantBitsPerResultElement = 16;
2258     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2259     Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2260     unsigned ZeroBitsPerResultElement =
2261         ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2262 
2263     IRBuilder<> IRB(&I);
2264     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2265     S = IRB.CreateBitCast(S, ResTy);
2266     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2267                        ResTy);
2268     S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2269     S = IRB.CreateBitCast(S, getShadowTy(&I));
2270     setShadow(&I, S);
2271     setOriginForNaryOp(I);
2272   }
2273 
2274   // \brief Instrument multiply-add intrinsic.
2275   void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2276                                   unsigned EltSizeInBits = 0) {
2277     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2278     Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2279     IRBuilder<> IRB(&I);
2280     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2281     S = IRB.CreateBitCast(S, ResTy);
2282     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2283                        ResTy);
2284     S = IRB.CreateBitCast(S, getShadowTy(&I));
2285     setShadow(&I, S);
2286     setOriginForNaryOp(I);
2287   }
2288 
2289   void visitIntrinsicInst(IntrinsicInst &I) {
2290     switch (I.getIntrinsicID()) {
2291     case llvm::Intrinsic::bswap:
2292       handleBswap(I);
2293       break;
2294     case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2295     case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2296     case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2297     case llvm::Intrinsic::x86_avx512_cvtss2usi:
2298     case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2299     case llvm::Intrinsic::x86_avx512_cvttss2usi:
2300     case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2301     case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2302     case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2303     case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2304     case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2305     case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2306     case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2307     case llvm::Intrinsic::x86_sse2_cvtsd2si:
2308     case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2309     case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2310     case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2311     case llvm::Intrinsic::x86_sse2_cvtss2sd:
2312     case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2313     case llvm::Intrinsic::x86_sse2_cvttsd2si:
2314     case llvm::Intrinsic::x86_sse_cvtsi2ss:
2315     case llvm::Intrinsic::x86_sse_cvtsi642ss:
2316     case llvm::Intrinsic::x86_sse_cvtss2si64:
2317     case llvm::Intrinsic::x86_sse_cvtss2si:
2318     case llvm::Intrinsic::x86_sse_cvttss2si64:
2319     case llvm::Intrinsic::x86_sse_cvttss2si:
2320       handleVectorConvertIntrinsic(I, 1);
2321       break;
2322     case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2323     case llvm::Intrinsic::x86_sse2_cvtps2pd:
2324     case llvm::Intrinsic::x86_sse_cvtps2pi:
2325     case llvm::Intrinsic::x86_sse_cvttps2pi:
2326       handleVectorConvertIntrinsic(I, 2);
2327       break;
2328     case llvm::Intrinsic::x86_avx2_psll_w:
2329     case llvm::Intrinsic::x86_avx2_psll_d:
2330     case llvm::Intrinsic::x86_avx2_psll_q:
2331     case llvm::Intrinsic::x86_avx2_pslli_w:
2332     case llvm::Intrinsic::x86_avx2_pslli_d:
2333     case llvm::Intrinsic::x86_avx2_pslli_q:
2334     case llvm::Intrinsic::x86_avx2_psrl_w:
2335     case llvm::Intrinsic::x86_avx2_psrl_d:
2336     case llvm::Intrinsic::x86_avx2_psrl_q:
2337     case llvm::Intrinsic::x86_avx2_psra_w:
2338     case llvm::Intrinsic::x86_avx2_psra_d:
2339     case llvm::Intrinsic::x86_avx2_psrli_w:
2340     case llvm::Intrinsic::x86_avx2_psrli_d:
2341     case llvm::Intrinsic::x86_avx2_psrli_q:
2342     case llvm::Intrinsic::x86_avx2_psrai_w:
2343     case llvm::Intrinsic::x86_avx2_psrai_d:
2344     case llvm::Intrinsic::x86_sse2_psll_w:
2345     case llvm::Intrinsic::x86_sse2_psll_d:
2346     case llvm::Intrinsic::x86_sse2_psll_q:
2347     case llvm::Intrinsic::x86_sse2_pslli_w:
2348     case llvm::Intrinsic::x86_sse2_pslli_d:
2349     case llvm::Intrinsic::x86_sse2_pslli_q:
2350     case llvm::Intrinsic::x86_sse2_psrl_w:
2351     case llvm::Intrinsic::x86_sse2_psrl_d:
2352     case llvm::Intrinsic::x86_sse2_psrl_q:
2353     case llvm::Intrinsic::x86_sse2_psra_w:
2354     case llvm::Intrinsic::x86_sse2_psra_d:
2355     case llvm::Intrinsic::x86_sse2_psrli_w:
2356     case llvm::Intrinsic::x86_sse2_psrli_d:
2357     case llvm::Intrinsic::x86_sse2_psrli_q:
2358     case llvm::Intrinsic::x86_sse2_psrai_w:
2359     case llvm::Intrinsic::x86_sse2_psrai_d:
2360     case llvm::Intrinsic::x86_mmx_psll_w:
2361     case llvm::Intrinsic::x86_mmx_psll_d:
2362     case llvm::Intrinsic::x86_mmx_psll_q:
2363     case llvm::Intrinsic::x86_mmx_pslli_w:
2364     case llvm::Intrinsic::x86_mmx_pslli_d:
2365     case llvm::Intrinsic::x86_mmx_pslli_q:
2366     case llvm::Intrinsic::x86_mmx_psrl_w:
2367     case llvm::Intrinsic::x86_mmx_psrl_d:
2368     case llvm::Intrinsic::x86_mmx_psrl_q:
2369     case llvm::Intrinsic::x86_mmx_psra_w:
2370     case llvm::Intrinsic::x86_mmx_psra_d:
2371     case llvm::Intrinsic::x86_mmx_psrli_w:
2372     case llvm::Intrinsic::x86_mmx_psrli_d:
2373     case llvm::Intrinsic::x86_mmx_psrli_q:
2374     case llvm::Intrinsic::x86_mmx_psrai_w:
2375     case llvm::Intrinsic::x86_mmx_psrai_d:
2376       handleVectorShiftIntrinsic(I, /* Variable */ false);
2377       break;
2378     case llvm::Intrinsic::x86_avx2_psllv_d:
2379     case llvm::Intrinsic::x86_avx2_psllv_d_256:
2380     case llvm::Intrinsic::x86_avx2_psllv_q:
2381     case llvm::Intrinsic::x86_avx2_psllv_q_256:
2382     case llvm::Intrinsic::x86_avx2_psrlv_d:
2383     case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2384     case llvm::Intrinsic::x86_avx2_psrlv_q:
2385     case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2386     case llvm::Intrinsic::x86_avx2_psrav_d:
2387     case llvm::Intrinsic::x86_avx2_psrav_d_256:
2388       handleVectorShiftIntrinsic(I, /* Variable */ true);
2389       break;
2390 
2391     case llvm::Intrinsic::x86_sse2_packsswb_128:
2392     case llvm::Intrinsic::x86_sse2_packssdw_128:
2393     case llvm::Intrinsic::x86_sse2_packuswb_128:
2394     case llvm::Intrinsic::x86_sse41_packusdw:
2395     case llvm::Intrinsic::x86_avx2_packsswb:
2396     case llvm::Intrinsic::x86_avx2_packssdw:
2397     case llvm::Intrinsic::x86_avx2_packuswb:
2398     case llvm::Intrinsic::x86_avx2_packusdw:
2399       handleVectorPackIntrinsic(I);
2400       break;
2401 
2402     case llvm::Intrinsic::x86_mmx_packsswb:
2403     case llvm::Intrinsic::x86_mmx_packuswb:
2404       handleVectorPackIntrinsic(I, 16);
2405       break;
2406 
2407     case llvm::Intrinsic::x86_mmx_packssdw:
2408       handleVectorPackIntrinsic(I, 32);
2409       break;
2410 
2411     case llvm::Intrinsic::x86_mmx_psad_bw:
2412     case llvm::Intrinsic::x86_sse2_psad_bw:
2413     case llvm::Intrinsic::x86_avx2_psad_bw:
2414       handleVectorSadIntrinsic(I);
2415       break;
2416 
2417     case llvm::Intrinsic::x86_sse2_pmadd_wd:
2418     case llvm::Intrinsic::x86_avx2_pmadd_wd:
2419     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2420     case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2421       handleVectorPmaddIntrinsic(I);
2422       break;
2423 
2424     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2425       handleVectorPmaddIntrinsic(I, 8);
2426       break;
2427 
2428     case llvm::Intrinsic::x86_mmx_pmadd_wd:
2429       handleVectorPmaddIntrinsic(I, 16);
2430       break;
2431 
2432     default:
2433       if (!handleUnknownIntrinsic(I))
2434         visitInstruction(I);
2435       break;
2436     }
2437   }
2438 
2439   void visitCallSite(CallSite CS) {
2440     Instruction &I = *CS.getInstruction();
2441     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2442     if (CS.isCall()) {
2443       CallInst *Call = cast<CallInst>(&I);
2444 
2445       // For inline asm, do the usual thing: check argument shadow and mark all
2446       // outputs as clean. Note that any side effects of the inline asm that are
2447       // not immediately visible in its constraints are not handled.
2448       if (Call->isInlineAsm()) {
2449         visitInstruction(I);
2450         return;
2451       }
2452 
2453       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
2454 
2455       // We are going to insert code that relies on the fact that the callee
2456       // will become a non-readonly function after it is instrumented by us. To
2457       // prevent this code from being optimized out, mark that function
2458       // non-readonly in advance.
2459       if (Function *Func = Call->getCalledFunction()) {
2460         // Clear out readonly/readnone attributes.
2461         AttrBuilder B;
2462         B.addAttribute(Attribute::ReadOnly)
2463           .addAttribute(Attribute::ReadNone);
2464         Func->removeAttributes(AttributeSet::FunctionIndex,
2465                                AttributeSet::get(Func->getContext(),
2466                                                  AttributeSet::FunctionIndex,
2467                                                  B));
2468       }
2469     }
2470     IRBuilder<> IRB(&I);
2471 
2472     unsigned ArgOffset = 0;
2473     DEBUG(dbgs() << "  CallSite: " << I << "\n");
2474     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2475          ArgIt != End; ++ArgIt) {
2476       Value *A = *ArgIt;
2477       unsigned i = ArgIt - CS.arg_begin();
2478       if (!A->getType()->isSized()) {
2479         DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2480         continue;
2481       }
2482       unsigned Size = 0;
2483       Value *Store = nullptr;
2484       // Compute the Shadow for arg even if it is ByVal, because
2485       // in that case getShadow() will copy the actual arg shadow to
2486       // __msan_param_tls.
2487       Value *ArgShadow = getShadow(A);
2488       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2489       DEBUG(dbgs() << "  Arg#" << i << ": " << *A <<
2490             " Shadow: " << *ArgShadow << "\n");
2491       bool ArgIsInitialized = false;
2492       const DataLayout &DL = F.getParent()->getDataLayout();
2493       if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
2494         assert(A->getType()->isPointerTy() &&
2495                "ByVal argument is not a pointer!");
2496         Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
2497         if (ArgOffset + Size > kParamTLSSize) break;
2498         unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2499         unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
2500         Store = IRB.CreateMemCpy(ArgShadowBase,
2501                                  getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2502                                  Size, Alignment);
2503       } else {
2504         Size = DL.getTypeAllocSize(A->getType());
2505         if (ArgOffset + Size > kParamTLSSize) break;
2506         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2507                                        kShadowTLSAlignment);
2508         Constant *Cst = dyn_cast<Constant>(ArgShadow);
2509         if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
2510       }
2511       if (MS.TrackOrigins && !ArgIsInitialized)
2512         IRB.CreateStore(getOrigin(A),
2513                         getOriginPtrForArgument(A, IRB, ArgOffset));
2514       (void)Store;
2515       assert(Size != 0 && Store != nullptr);
2516       DEBUG(dbgs() << "  Param:" << *Store << "\n");
2517       ArgOffset += RoundUpToAlignment(Size, 8);
2518     }
2519     DEBUG(dbgs() << "  done with call args\n");
2520 
2521     FunctionType *FT =
2522       cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
2523     if (FT->isVarArg()) {
2524       VAHelper->visitCallSite(CS, IRB);
2525     }
2526 
2527     // Now, get the shadow for the RetVal.
2528     if (!I.getType()->isSized()) return;
2529     // Don't emit the epilogue for musttail call returns.
2530     if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
2531     IRBuilder<> IRBBefore(&I);
2532     // Until we have full dynamic coverage, make sure the retval shadow is 0.
2533     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
2534     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
2535     BasicBlock::iterator NextInsn;
2536     if (CS.isCall()) {
2537       NextInsn = ++I.getIterator();
2538       assert(NextInsn != I.getParent()->end());
2539     } else {
2540       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2541       if (!NormalDest->getSinglePredecessor()) {
2542         // FIXME: this case is tricky, so we are just conservative here.
2543         // Perhaps we need to split the edge between this BB and NormalDest,
2544         // but a naive attempt to use SplitEdge leads to a crash.
2545         setShadow(&I, getCleanShadow(&I));
2546         setOrigin(&I, getCleanOrigin());
2547         return;
2548       }
2549       NextInsn = NormalDest->getFirstInsertionPt();
2550       assert(NextInsn != NormalDest->end() &&
2551              "Could not find insertion point for retval shadow load");
2552     }
2553     IRBuilder<> IRBAfter(&*NextInsn);
2554     Value *RetvalShadow =
2555       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2556                                  kShadowTLSAlignment, "_msret");
2557     setShadow(&I, RetvalShadow);
2558     if (MS.TrackOrigins)
2559       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2560   }
2561 
2562   bool isAMustTailRetVal(Value *RetVal) {
2563     if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
2564       RetVal = I->getOperand(0);
2565     }
2566     if (auto *I = dyn_cast<CallInst>(RetVal)) {
2567       return I->isMustTailCall();
2568     }
2569     return false;
2570   }
2571 
2572   void visitReturnInst(ReturnInst &I) {
2573     IRBuilder<> IRB(&I);
2574     Value *RetVal = I.getReturnValue();
2575     if (!RetVal) return;
2576     // Don't emit the epilogue for musttail call returns.
2577     if (isAMustTailRetVal(RetVal)) return;
2578     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2579     if (CheckReturnValue) {
2580       insertShadowCheck(RetVal, &I);
2581       Value *Shadow = getCleanShadow(RetVal);
2582       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2583     } else {
2584       Value *Shadow = getShadow(RetVal);
2585       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2586       // FIXME: make it conditional if ClStoreCleanOrigin==0
2587       if (MS.TrackOrigins)
2588         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2589     }
2590   }
2591 
2592   void visitPHINode(PHINode &I) {
2593     IRBuilder<> IRB(&I);
2594     if (!PropagateShadow) {
2595       setShadow(&I, getCleanShadow(&I));
2596       setOrigin(&I, getCleanOrigin());
2597       return;
2598     }
2599 
2600     ShadowPHINodes.push_back(&I);
2601     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2602                                 "_msphi_s"));
2603     if (MS.TrackOrigins)
2604       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2605                                   "_msphi_o"));
2606   }
2607 
2608   void visitAllocaInst(AllocaInst &I) {
2609     setShadow(&I, getCleanShadow(&I));
2610     setOrigin(&I, getCleanOrigin());
2611     IRBuilder<> IRB(I.getNextNode());
2612     const DataLayout &DL = F.getParent()->getDataLayout();
2613     uint64_t Size = DL.getTypeAllocSize(I.getAllocatedType());
2614     if (PoisonStack && ClPoisonStackWithCall) {
2615       IRB.CreateCall(MS.MsanPoisonStackFn,
2616                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2617                       ConstantInt::get(MS.IntptrTy, Size)});
2618     } else {
2619       Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2620       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2621       IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2622     }
2623 
2624     if (PoisonStack && MS.TrackOrigins) {
2625       SmallString<2048> StackDescriptionStorage;
2626       raw_svector_ostream StackDescription(StackDescriptionStorage);
2627       // We create a string with a description of the stack allocation and
2628       // pass it into __msan_set_alloca_origin.
2629       // It will be printed by the run-time if stack-originated UMR is found.
2630       // The first 4 bytes of the string are set to '----' and will be replaced
2631       // by __msan_va_arg_overflow_size_tls at the first call.
2632       StackDescription << "----" << I.getName() << "@" << F.getName();
2633       Value *Descr =
2634           createPrivateNonConstGlobalForString(*F.getParent(),
2635                                                StackDescription.str());
2636 
2637       IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
2638                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2639                       ConstantInt::get(MS.IntptrTy, Size),
2640                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2641                       IRB.CreatePointerCast(&F, MS.IntptrTy)});
2642     }
2643   }
2644 
2645   void visitSelectInst(SelectInst& I) {
2646     IRBuilder<> IRB(&I);
2647     // a = select b, c, d
2648     Value *B = I.getCondition();
2649     Value *C = I.getTrueValue();
2650     Value *D = I.getFalseValue();
2651     Value *Sb = getShadow(B);
2652     Value *Sc = getShadow(C);
2653     Value *Sd = getShadow(D);
2654 
2655     // Result shadow if condition shadow is 0.
2656     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2657     Value *Sa1;
2658     if (I.getType()->isAggregateType()) {
2659       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2660       // an extra "select". This results in much more compact IR.
2661       // Sa = select Sb, poisoned, (select b, Sc, Sd)
2662       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
2663     } else {
2664       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2665       // If Sb (condition is poisoned), look for bits in c and d that are equal
2666       // and both unpoisoned.
2667       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2668 
2669       // Cast arguments to shadow-compatible type.
2670       C = CreateAppToShadowCast(IRB, C);
2671       D = CreateAppToShadowCast(IRB, D);
2672 
2673       // Result shadow if condition shadow is 1.
2674       Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
2675     }
2676     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2677     setShadow(&I, Sa);
2678     if (MS.TrackOrigins) {
2679       // Origins are always i32, so any vector conditions must be flattened.
2680       // FIXME: consider tracking vector origins for app vectors?
2681       if (B->getType()->isVectorTy()) {
2682         Type *FlatTy = getShadowTyNoVec(B->getType());
2683         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
2684                                 ConstantInt::getNullValue(FlatTy));
2685         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
2686                                       ConstantInt::getNullValue(FlatTy));
2687       }
2688       // a = select b, c, d
2689       // Oa = Sb ? Ob : (b ? Oc : Od)
2690       setOrigin(
2691           &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2692                                IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2693                                                 getOrigin(I.getFalseValue()))));
2694     }
2695   }
2696 
2697   void visitLandingPadInst(LandingPadInst &I) {
2698     // Do nothing.
2699     // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2700     setShadow(&I, getCleanShadow(&I));
2701     setOrigin(&I, getCleanOrigin());
2702   }
2703 
2704   void visitCleanupPadInst(CleanupPadInst &I) {
2705     setShadow(&I, getCleanShadow(&I));
2706     setOrigin(&I, getCleanOrigin());
2707   }
2708 
2709   void visitCatchPad(CatchPadInst &I) {
2710     setShadow(&I, getCleanShadow(&I));
2711     setOrigin(&I, getCleanOrigin());
2712   }
2713 
2714   void visitTerminatePad(TerminatePadInst &I) {
2715     DEBUG(dbgs() << "TerminatePad: " << I << "\n");
2716     // Nothing to do here.
2717   }
2718 
2719   void visitCatchEndPadInst(CatchEndPadInst &I) {
2720     DEBUG(dbgs() << "CatchEndPad: " << I << "\n");
2721     // Nothing to do here.
2722   }
2723 
2724   void visitCleanupEndPadInst(CleanupEndPadInst &I) {
2725     DEBUG(dbgs() << "CleanupEndPad: " << I << "\n");
2726     // Nothing to do here.
2727   }
2728 
2729   void visitGetElementPtrInst(GetElementPtrInst &I) {
2730     handleShadowOr(I);
2731   }
2732 
2733   void visitExtractValueInst(ExtractValueInst &I) {
2734     IRBuilder<> IRB(&I);
2735     Value *Agg = I.getAggregateOperand();
2736     DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
2737     Value *AggShadow = getShadow(Agg);
2738     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2739     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2740     DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
2741     setShadow(&I, ResShadow);
2742     setOriginForNaryOp(I);
2743   }
2744 
2745   void visitInsertValueInst(InsertValueInst &I) {
2746     IRBuilder<> IRB(&I);
2747     DEBUG(dbgs() << "InsertValue:  " << I << "\n");
2748     Value *AggShadow = getShadow(I.getAggregateOperand());
2749     Value *InsShadow = getShadow(I.getInsertedValueOperand());
2750     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2751     DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
2752     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2753     DEBUG(dbgs() << "   Res:        " << *Res << "\n");
2754     setShadow(&I, Res);
2755     setOriginForNaryOp(I);
2756   }
2757 
2758   void dumpInst(Instruction &I) {
2759     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2760       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2761     } else {
2762       errs() << "ZZZ " << I.getOpcodeName() << "\n";
2763     }
2764     errs() << "QQQ " << I << "\n";
2765   }
2766 
2767   void visitResumeInst(ResumeInst &I) {
2768     DEBUG(dbgs() << "Resume: " << I << "\n");
2769     // Nothing to do here.
2770   }
2771 
2772   void visitCleanupReturnInst(CleanupReturnInst &CRI) {
2773     DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
2774     // Nothing to do here.
2775   }
2776 
2777   void visitCatchReturnInst(CatchReturnInst &CRI) {
2778     DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
2779     // Nothing to do here.
2780   }
2781 
2782   void visitInstruction(Instruction &I) {
2783     // Everything else: stop propagating and check for poisoned shadow.
2784     if (ClDumpStrictInstructions)
2785       dumpInst(I);
2786     DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2787     for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2788       insertShadowCheck(I.getOperand(i), &I);
2789     setShadow(&I, getCleanShadow(&I));
2790     setOrigin(&I, getCleanOrigin());
2791   }
2792 };
2793 
2794 /// \brief AMD64-specific implementation of VarArgHelper.
2795 struct VarArgAMD64Helper : public VarArgHelper {
2796   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2797   // See a comment in visitCallSite for more details.
2798   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
2799   static const unsigned AMD64FpEndOffset = 176;
2800 
2801   Function &F;
2802   MemorySanitizer &MS;
2803   MemorySanitizerVisitor &MSV;
2804   Value *VAArgTLSCopy;
2805   Value *VAArgOverflowSize;
2806 
2807   SmallVector<CallInst*, 16> VAStartInstrumentationList;
2808 
2809   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2810                     MemorySanitizerVisitor &MSV)
2811     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2812       VAArgOverflowSize(nullptr) {}
2813 
2814   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2815 
2816   ArgKind classifyArgument(Value* arg) {
2817     // A very rough approximation of X86_64 argument classification rules.
2818     Type *T = arg->getType();
2819     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2820       return AK_FloatingPoint;
2821     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2822       return AK_GeneralPurpose;
2823     if (T->isPointerTy())
2824       return AK_GeneralPurpose;
2825     return AK_Memory;
2826   }
2827 
2828   // For VarArg functions, store the argument shadow in an ABI-specific format
2829   // that corresponds to va_list layout.
2830   // We do this because Clang lowers va_arg in the frontend, and this pass
2831   // only sees the low level code that deals with va_list internals.
2832   // A much easier alternative (provided that Clang emits va_arg instructions)
2833   // would have been to associate each live instance of va_list with a copy of
2834   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2835   // order.
2836   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2837     unsigned GpOffset = 0;
2838     unsigned FpOffset = AMD64GpEndOffset;
2839     unsigned OverflowOffset = AMD64FpEndOffset;
2840     const DataLayout &DL = F.getParent()->getDataLayout();
2841     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2842          ArgIt != End; ++ArgIt) {
2843       Value *A = *ArgIt;
2844       unsigned ArgNo = CS.getArgumentNo(ArgIt);
2845       bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2846       if (IsByVal) {
2847         // ByVal arguments always go to the overflow area.
2848         assert(A->getType()->isPointerTy());
2849         Type *RealTy = A->getType()->getPointerElementType();
2850         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
2851         Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
2852         OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2853         IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2854                          ArgSize, kShadowTLSAlignment);
2855       } else {
2856         ArgKind AK = classifyArgument(A);
2857         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2858           AK = AK_Memory;
2859         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2860           AK = AK_Memory;
2861         Value *Base;
2862         switch (AK) {
2863           case AK_GeneralPurpose:
2864             Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2865             GpOffset += 8;
2866             break;
2867           case AK_FloatingPoint:
2868             Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2869             FpOffset += 16;
2870             break;
2871           case AK_Memory:
2872             uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
2873             Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2874             OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2875         }
2876         IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2877       }
2878     }
2879     Constant *OverflowSize =
2880       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2881     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2882   }
2883 
2884   /// \brief Compute the shadow address for a given va_arg.
2885   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2886                                    int ArgOffset) {
2887     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2888     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2889     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2890                               "_msarg");
2891   }
2892 
2893   void visitVAStartInst(VAStartInst &I) override {
2894     if (F.getCallingConv() == CallingConv::X86_64_Win64)
2895       return;
2896     IRBuilder<> IRB(&I);
2897     VAStartInstrumentationList.push_back(&I);
2898     Value *VAListTag = I.getArgOperand(0);
2899     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2900 
2901     // Unpoison the whole __va_list_tag.
2902     // FIXME: magic ABI constants.
2903     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2904                      /* size */24, /* alignment */8, false);
2905   }
2906 
2907   void visitVACopyInst(VACopyInst &I) override {
2908     if (F.getCallingConv() == CallingConv::X86_64_Win64)
2909       return;
2910     IRBuilder<> IRB(&I);
2911     Value *VAListTag = I.getArgOperand(0);
2912     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2913 
2914     // Unpoison the whole __va_list_tag.
2915     // FIXME: magic ABI constants.
2916     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2917                      /* size */24, /* alignment */8, false);
2918   }
2919 
2920   void finalizeInstrumentation() override {
2921     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2922            "finalizeInstrumentation called twice");
2923     if (!VAStartInstrumentationList.empty()) {
2924       // If there is a va_start in this function, make a backup copy of
2925       // va_arg_tls somewhere in the function entry block.
2926       IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2927       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2928       Value *CopySize =
2929         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2930                       VAArgOverflowSize);
2931       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2932       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2933     }
2934 
2935     // Instrument va_start.
2936     // Copy va_list shadow from the backup copy of the TLS contents.
2937     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2938       CallInst *OrigInst = VAStartInstrumentationList[i];
2939       IRBuilder<> IRB(OrigInst->getNextNode());
2940       Value *VAListTag = OrigInst->getArgOperand(0);
2941 
2942       Value *RegSaveAreaPtrPtr =
2943         IRB.CreateIntToPtr(
2944           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2945                         ConstantInt::get(MS.IntptrTy, 16)),
2946           Type::getInt64PtrTy(*MS.C));
2947       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2948       Value *RegSaveAreaShadowPtr =
2949         MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2950       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2951                        AMD64FpEndOffset, 16);
2952 
2953       Value *OverflowArgAreaPtrPtr =
2954         IRB.CreateIntToPtr(
2955           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2956                         ConstantInt::get(MS.IntptrTy, 8)),
2957           Type::getInt64PtrTy(*MS.C));
2958       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2959       Value *OverflowArgAreaShadowPtr =
2960         MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2961       Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
2962                                              AMD64FpEndOffset);
2963       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2964     }
2965   }
2966 };
2967 
2968 /// \brief MIPS64-specific implementation of VarArgHelper.
2969 struct VarArgMIPS64Helper : public VarArgHelper {
2970   Function &F;
2971   MemorySanitizer &MS;
2972   MemorySanitizerVisitor &MSV;
2973   Value *VAArgTLSCopy;
2974   Value *VAArgSize;
2975 
2976   SmallVector<CallInst*, 16> VAStartInstrumentationList;
2977 
2978   VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
2979                     MemorySanitizerVisitor &MSV)
2980     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2981       VAArgSize(nullptr) {}
2982 
2983   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2984     unsigned VAArgOffset = 0;
2985     const DataLayout &DL = F.getParent()->getDataLayout();
2986     for (CallSite::arg_iterator ArgIt = CS.arg_begin() + 1, End = CS.arg_end();
2987          ArgIt != End; ++ArgIt) {
2988       Value *A = *ArgIt;
2989       Value *Base;
2990       uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
2991 #if defined(__MIPSEB__) || defined(MIPSEB)
2992       // Adjusting the shadow for argument with size < 8 to match the placement
2993       // of bits in big endian system
2994       if (ArgSize < 8)
2995         VAArgOffset += (8 - ArgSize);
2996 #endif
2997       Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
2998       VAArgOffset += ArgSize;
2999       VAArgOffset = RoundUpToAlignment(VAArgOffset, 8);
3000       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
3001     }
3002 
3003     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
3004     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
3005     // a new class member i.e. it is the total size of all VarArgs.
3006     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
3007   }
3008 
3009   /// \brief Compute the shadow address for a given va_arg.
3010   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3011                                    int ArgOffset) {
3012     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3013     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3014     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3015                               "_msarg");
3016   }
3017 
3018   void visitVAStartInst(VAStartInst &I) override {
3019     IRBuilder<> IRB(&I);
3020     VAStartInstrumentationList.push_back(&I);
3021     Value *VAListTag = I.getArgOperand(0);
3022     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3023     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3024                      /* size */8, /* alignment */8, false);
3025   }
3026 
3027   void visitVACopyInst(VACopyInst &I) override {
3028     IRBuilder<> IRB(&I);
3029     Value *VAListTag = I.getArgOperand(0);
3030     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3031     // Unpoison the whole __va_list_tag.
3032     // FIXME: magic ABI constants.
3033     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3034                      /* size */8, /* alignment */8, false);
3035   }
3036 
3037   void finalizeInstrumentation() override {
3038     assert(!VAArgSize && !VAArgTLSCopy &&
3039            "finalizeInstrumentation called twice");
3040     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
3041     VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3042     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
3043                                     VAArgSize);
3044 
3045     if (!VAStartInstrumentationList.empty()) {
3046       // If there is a va_start in this function, make a backup copy of
3047       // va_arg_tls somewhere in the function entry block.
3048       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3049       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
3050     }
3051 
3052     // Instrument va_start.
3053     // Copy va_list shadow from the backup copy of the TLS contents.
3054     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3055       CallInst *OrigInst = VAStartInstrumentationList[i];
3056       IRBuilder<> IRB(OrigInst->getNextNode());
3057       Value *VAListTag = OrigInst->getArgOperand(0);
3058       Value *RegSaveAreaPtrPtr =
3059         IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3060                         Type::getInt64PtrTy(*MS.C));
3061       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3062       Value *RegSaveAreaShadowPtr =
3063       MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
3064       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
3065     }
3066   }
3067 };
3068 
3069 /// \brief A no-op implementation of VarArgHelper.
3070 struct VarArgNoOpHelper : public VarArgHelper {
3071   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
3072                    MemorySanitizerVisitor &MSV) {}
3073 
3074   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
3075 
3076   void visitVAStartInst(VAStartInst &I) override {}
3077 
3078   void visitVACopyInst(VACopyInst &I) override {}
3079 
3080   void finalizeInstrumentation() override {}
3081 };
3082 
3083 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
3084                                  MemorySanitizerVisitor &Visitor) {
3085   // VarArg handling is only implemented on AMD64. False positives are possible
3086   // on other platforms.
3087   llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
3088   if (TargetTriple.getArch() == llvm::Triple::x86_64)
3089     return new VarArgAMD64Helper(Func, Msan, Visitor);
3090   else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
3091            TargetTriple.getArch() == llvm::Triple::mips64el)
3092     return new VarArgMIPS64Helper(Func, Msan, Visitor);
3093   else
3094     return new VarArgNoOpHelper(Func, Msan, Visitor);
3095 }
3096 
3097 } // anonymous namespace
3098 
3099 bool MemorySanitizer::runOnFunction(Function &F) {
3100   if (&F == MsanCtorFunction)
3101     return false;
3102   MemorySanitizerVisitor Visitor(F, *this);
3103 
3104   // Clear out readonly/readnone attributes.
3105   AttrBuilder B;
3106   B.addAttribute(Attribute::ReadOnly)
3107     .addAttribute(Attribute::ReadNone);
3108   F.removeAttributes(AttributeSet::FunctionIndex,
3109                      AttributeSet::get(F.getContext(),
3110                                        AttributeSet::FunctionIndex, B));
3111 
3112   return Visitor.runOnFunction();
3113 }
3114