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   enum IntrinsicKind {
1922     IK_DoesNotAccessMemory,
1923     IK_OnlyReadsMemory,
1924     IK_WritesMemory
1925   };
1926 
1927   static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1928     const int FMRB_DoesNotAccessMemory = IK_DoesNotAccessMemory;
1929     const int FMRB_OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1930     const int FMRB_OnlyReadsMemory = IK_OnlyReadsMemory;
1931     const int FMRB_OnlyAccessesArgumentPointees = IK_WritesMemory;
1932     const int FMRB_UnknownModRefBehavior = IK_WritesMemory;
1933 #define GET_INTRINSIC_MODREF_BEHAVIOR
1934 #define FunctionModRefBehavior IntrinsicKind
1935 #include "llvm/IR/Intrinsics.gen"
1936 #undef FunctionModRefBehavior
1937 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1938   }
1939 
1940   /// \brief Handle vector store-like intrinsics.
1941   ///
1942   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1943   /// has 1 pointer argument and 1 vector argument, returns void.
1944   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1945     IRBuilder<> IRB(&I);
1946     Value* Addr = I.getArgOperand(0);
1947     Value *Shadow = getShadow(&I, 1);
1948     Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1949 
1950     // We don't know the pointer alignment (could be unaligned SSE store!).
1951     // Have to assume to worst case.
1952     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1953 
1954     if (ClCheckAccessAddress)
1955       insertShadowCheck(Addr, &I);
1956 
1957     // FIXME: use ClStoreCleanOrigin
1958     // FIXME: factor out common code from materializeStores
1959     if (MS.TrackOrigins)
1960       IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
1961     return true;
1962   }
1963 
1964   /// \brief Handle vector load-like intrinsics.
1965   ///
1966   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1967   /// has 1 pointer argument, returns a vector.
1968   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1969     IRBuilder<> IRB(&I);
1970     Value *Addr = I.getArgOperand(0);
1971 
1972     Type *ShadowTy = getShadowTy(&I);
1973     if (PropagateShadow) {
1974       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1975       // We don't know the pointer alignment (could be unaligned SSE load!).
1976       // Have to assume to worst case.
1977       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1978     } else {
1979       setShadow(&I, getCleanShadow(&I));
1980     }
1981 
1982     if (ClCheckAccessAddress)
1983       insertShadowCheck(Addr, &I);
1984 
1985     if (MS.TrackOrigins) {
1986       if (PropagateShadow)
1987         setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
1988       else
1989         setOrigin(&I, getCleanOrigin());
1990     }
1991     return true;
1992   }
1993 
1994   /// \brief Handle (SIMD arithmetic)-like intrinsics.
1995   ///
1996   /// Instrument intrinsics with any number of arguments of the same type,
1997   /// equal to the return type. The type should be simple (no aggregates or
1998   /// pointers; vectors are fine).
1999   /// Caller guarantees that this intrinsic does not access memory.
2000   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
2001     Type *RetTy = I.getType();
2002     if (!(RetTy->isIntOrIntVectorTy() ||
2003           RetTy->isFPOrFPVectorTy() ||
2004           RetTy->isX86_MMXTy()))
2005       return false;
2006 
2007     unsigned NumArgOperands = I.getNumArgOperands();
2008 
2009     for (unsigned i = 0; i < NumArgOperands; ++i) {
2010       Type *Ty = I.getArgOperand(i)->getType();
2011       if (Ty != RetTy)
2012         return false;
2013     }
2014 
2015     IRBuilder<> IRB(&I);
2016     ShadowAndOriginCombiner SC(this, IRB);
2017     for (unsigned i = 0; i < NumArgOperands; ++i)
2018       SC.Add(I.getArgOperand(i));
2019     SC.Done(&I);
2020 
2021     return true;
2022   }
2023 
2024   /// \brief Heuristically instrument unknown intrinsics.
2025   ///
2026   /// The main purpose of this code is to do something reasonable with all
2027   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
2028   /// We recognize several classes of intrinsics by their argument types and
2029   /// ModRefBehaviour and apply special intrumentation when we are reasonably
2030   /// sure that we know what the intrinsic does.
2031   ///
2032   /// We special-case intrinsics where this approach fails. See llvm.bswap
2033   /// handling as an example of that.
2034   bool handleUnknownIntrinsic(IntrinsicInst &I) {
2035     unsigned NumArgOperands = I.getNumArgOperands();
2036     if (NumArgOperands == 0)
2037       return false;
2038 
2039     Intrinsic::ID iid = I.getIntrinsicID();
2040     IntrinsicKind IK = getIntrinsicKind(iid);
2041     bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
2042     bool WritesMemory = IK == IK_WritesMemory;
2043     assert(!(OnlyReadsMemory && WritesMemory));
2044 
2045     if (NumArgOperands == 2 &&
2046         I.getArgOperand(0)->getType()->isPointerTy() &&
2047         I.getArgOperand(1)->getType()->isVectorTy() &&
2048         I.getType()->isVoidTy() &&
2049         WritesMemory) {
2050       // This looks like a vector store.
2051       return handleVectorStoreIntrinsic(I);
2052     }
2053 
2054     if (NumArgOperands == 1 &&
2055         I.getArgOperand(0)->getType()->isPointerTy() &&
2056         I.getType()->isVectorTy() &&
2057         OnlyReadsMemory) {
2058       // This looks like a vector load.
2059       return handleVectorLoadIntrinsic(I);
2060     }
2061 
2062     if (!OnlyReadsMemory && !WritesMemory)
2063       if (maybeHandleSimpleNomemIntrinsic(I))
2064         return true;
2065 
2066     // FIXME: detect and handle SSE maskstore/maskload
2067     return false;
2068   }
2069 
2070   void handleBswap(IntrinsicInst &I) {
2071     IRBuilder<> IRB(&I);
2072     Value *Op = I.getArgOperand(0);
2073     Type *OpType = Op->getType();
2074     Function *BswapFunc = Intrinsic::getDeclaration(
2075       F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
2076     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2077     setOrigin(&I, getOrigin(Op));
2078   }
2079 
2080   // \brief Instrument vector convert instrinsic.
2081   //
2082   // This function instruments intrinsics like cvtsi2ss:
2083   // %Out = int_xxx_cvtyyy(%ConvertOp)
2084   // or
2085   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2086   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2087   // number \p Out elements, and (if has 2 arguments) copies the rest of the
2088   // elements from \p CopyOp.
2089   // In most cases conversion involves floating-point value which may trigger a
2090   // hardware exception when not fully initialized. For this reason we require
2091   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2092   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2093   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2094   // return a fully initialized value.
2095   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2096     IRBuilder<> IRB(&I);
2097     Value *CopyOp, *ConvertOp;
2098 
2099     switch (I.getNumArgOperands()) {
2100     case 3:
2101       assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
2102     case 2:
2103       CopyOp = I.getArgOperand(0);
2104       ConvertOp = I.getArgOperand(1);
2105       break;
2106     case 1:
2107       ConvertOp = I.getArgOperand(0);
2108       CopyOp = nullptr;
2109       break;
2110     default:
2111       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2112     }
2113 
2114     // The first *NumUsedElements* elements of ConvertOp are converted to the
2115     // same number of output elements. The rest of the output is copied from
2116     // CopyOp, or (if not available) filled with zeroes.
2117     // Combine shadow for elements of ConvertOp that are used in this operation,
2118     // and insert a check.
2119     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2120     // int->any conversion.
2121     Value *ConvertShadow = getShadow(ConvertOp);
2122     Value *AggShadow = nullptr;
2123     if (ConvertOp->getType()->isVectorTy()) {
2124       AggShadow = IRB.CreateExtractElement(
2125           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2126       for (int i = 1; i < NumUsedElements; ++i) {
2127         Value *MoreShadow = IRB.CreateExtractElement(
2128             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2129         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2130       }
2131     } else {
2132       AggShadow = ConvertShadow;
2133     }
2134     assert(AggShadow->getType()->isIntegerTy());
2135     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2136 
2137     // Build result shadow by zero-filling parts of CopyOp shadow that come from
2138     // ConvertOp.
2139     if (CopyOp) {
2140       assert(CopyOp->getType() == I.getType());
2141       assert(CopyOp->getType()->isVectorTy());
2142       Value *ResultShadow = getShadow(CopyOp);
2143       Type *EltTy = ResultShadow->getType()->getVectorElementType();
2144       for (int i = 0; i < NumUsedElements; ++i) {
2145         ResultShadow = IRB.CreateInsertElement(
2146             ResultShadow, ConstantInt::getNullValue(EltTy),
2147             ConstantInt::get(IRB.getInt32Ty(), i));
2148       }
2149       setShadow(&I, ResultShadow);
2150       setOrigin(&I, getOrigin(CopyOp));
2151     } else {
2152       setShadow(&I, getCleanShadow(&I));
2153       setOrigin(&I, getCleanOrigin());
2154     }
2155   }
2156 
2157   // Given a scalar or vector, extract lower 64 bits (or less), and return all
2158   // zeroes if it is zero, and all ones otherwise.
2159   Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2160     if (S->getType()->isVectorTy())
2161       S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2162     assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2163     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2164     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2165   }
2166 
2167   Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2168     Type *T = S->getType();
2169     assert(T->isVectorTy());
2170     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2171     return IRB.CreateSExt(S2, T);
2172   }
2173 
2174   // \brief Instrument vector shift instrinsic.
2175   //
2176   // This function instruments intrinsics like int_x86_avx2_psll_w.
2177   // Intrinsic shifts %In by %ShiftSize bits.
2178   // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2179   // size, and the rest is ignored. Behavior is defined even if shift size is
2180   // greater than register (or field) width.
2181   void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2182     assert(I.getNumArgOperands() == 2);
2183     IRBuilder<> IRB(&I);
2184     // If any of the S2 bits are poisoned, the whole thing is poisoned.
2185     // Otherwise perform the same shift on S1.
2186     Value *S1 = getShadow(&I, 0);
2187     Value *S2 = getShadow(&I, 1);
2188     Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2189                              : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2190     Value *V1 = I.getOperand(0);
2191     Value *V2 = I.getOperand(1);
2192     Value *Shift = IRB.CreateCall(I.getCalledValue(),
2193                                   {IRB.CreateBitCast(S1, V1->getType()), V2});
2194     Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2195     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2196     setOriginForNaryOp(I);
2197   }
2198 
2199   // \brief Get an X86_MMX-sized vector type.
2200   Type *getMMXVectorTy(unsigned EltSizeInBits) {
2201     const unsigned X86_MMXSizeInBits = 64;
2202     return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2203                            X86_MMXSizeInBits / EltSizeInBits);
2204   }
2205 
2206   // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2207   // intrinsic.
2208   Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2209     switch (id) {
2210       case llvm::Intrinsic::x86_sse2_packsswb_128:
2211       case llvm::Intrinsic::x86_sse2_packuswb_128:
2212         return llvm::Intrinsic::x86_sse2_packsswb_128;
2213 
2214       case llvm::Intrinsic::x86_sse2_packssdw_128:
2215       case llvm::Intrinsic::x86_sse41_packusdw:
2216         return llvm::Intrinsic::x86_sse2_packssdw_128;
2217 
2218       case llvm::Intrinsic::x86_avx2_packsswb:
2219       case llvm::Intrinsic::x86_avx2_packuswb:
2220         return llvm::Intrinsic::x86_avx2_packsswb;
2221 
2222       case llvm::Intrinsic::x86_avx2_packssdw:
2223       case llvm::Intrinsic::x86_avx2_packusdw:
2224         return llvm::Intrinsic::x86_avx2_packssdw;
2225 
2226       case llvm::Intrinsic::x86_mmx_packsswb:
2227       case llvm::Intrinsic::x86_mmx_packuswb:
2228         return llvm::Intrinsic::x86_mmx_packsswb;
2229 
2230       case llvm::Intrinsic::x86_mmx_packssdw:
2231         return llvm::Intrinsic::x86_mmx_packssdw;
2232       default:
2233         llvm_unreachable("unexpected intrinsic id");
2234     }
2235   }
2236 
2237   // \brief Instrument vector pack instrinsic.
2238   //
2239   // This function instruments intrinsics like x86_mmx_packsswb, that
2240   // packs elements of 2 input vectors into half as many bits with saturation.
2241   // Shadow is propagated with the signed variant of the same intrinsic applied
2242   // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2243   // EltSizeInBits is used only for x86mmx arguments.
2244   void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
2245     assert(I.getNumArgOperands() == 2);
2246     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2247     IRBuilder<> IRB(&I);
2248     Value *S1 = getShadow(&I, 0);
2249     Value *S2 = getShadow(&I, 1);
2250     assert(isX86_MMX || S1->getType()->isVectorTy());
2251 
2252     // SExt and ICmpNE below must apply to individual elements of input vectors.
2253     // In case of x86mmx arguments, cast them to appropriate vector types and
2254     // back.
2255     Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2256     if (isX86_MMX) {
2257       S1 = IRB.CreateBitCast(S1, T);
2258       S2 = IRB.CreateBitCast(S2, T);
2259     }
2260     Value *S1_ext = IRB.CreateSExt(
2261         IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2262     Value *S2_ext = IRB.CreateSExt(
2263         IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
2264     if (isX86_MMX) {
2265       Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2266       S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2267       S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2268     }
2269 
2270     Function *ShadowFn = Intrinsic::getDeclaration(
2271         F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2272 
2273     Value *S =
2274         IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
2275     if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2276     setShadow(&I, S);
2277     setOriginForNaryOp(I);
2278   }
2279 
2280   // \brief Instrument sum-of-absolute-differencies intrinsic.
2281   void handleVectorSadIntrinsic(IntrinsicInst &I) {
2282     const unsigned SignificantBitsPerResultElement = 16;
2283     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2284     Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2285     unsigned ZeroBitsPerResultElement =
2286         ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2287 
2288     IRBuilder<> IRB(&I);
2289     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2290     S = IRB.CreateBitCast(S, ResTy);
2291     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2292                        ResTy);
2293     S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2294     S = IRB.CreateBitCast(S, getShadowTy(&I));
2295     setShadow(&I, S);
2296     setOriginForNaryOp(I);
2297   }
2298 
2299   // \brief Instrument multiply-add intrinsic.
2300   void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2301                                   unsigned EltSizeInBits = 0) {
2302     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2303     Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2304     IRBuilder<> IRB(&I);
2305     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2306     S = IRB.CreateBitCast(S, ResTy);
2307     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2308                        ResTy);
2309     S = IRB.CreateBitCast(S, getShadowTy(&I));
2310     setShadow(&I, S);
2311     setOriginForNaryOp(I);
2312   }
2313 
2314   void visitIntrinsicInst(IntrinsicInst &I) {
2315     switch (I.getIntrinsicID()) {
2316     case llvm::Intrinsic::bswap:
2317       handleBswap(I);
2318       break;
2319     case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2320     case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2321     case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2322     case llvm::Intrinsic::x86_avx512_cvtss2usi:
2323     case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2324     case llvm::Intrinsic::x86_avx512_cvttss2usi:
2325     case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2326     case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2327     case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2328     case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2329     case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2330     case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2331     case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2332     case llvm::Intrinsic::x86_sse2_cvtsd2si:
2333     case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2334     case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2335     case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2336     case llvm::Intrinsic::x86_sse2_cvtss2sd:
2337     case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2338     case llvm::Intrinsic::x86_sse2_cvttsd2si:
2339     case llvm::Intrinsic::x86_sse_cvtsi2ss:
2340     case llvm::Intrinsic::x86_sse_cvtsi642ss:
2341     case llvm::Intrinsic::x86_sse_cvtss2si64:
2342     case llvm::Intrinsic::x86_sse_cvtss2si:
2343     case llvm::Intrinsic::x86_sse_cvttss2si64:
2344     case llvm::Intrinsic::x86_sse_cvttss2si:
2345       handleVectorConvertIntrinsic(I, 1);
2346       break;
2347     case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2348     case llvm::Intrinsic::x86_sse2_cvtps2pd:
2349     case llvm::Intrinsic::x86_sse_cvtps2pi:
2350     case llvm::Intrinsic::x86_sse_cvttps2pi:
2351       handleVectorConvertIntrinsic(I, 2);
2352       break;
2353     case llvm::Intrinsic::x86_avx2_psll_w:
2354     case llvm::Intrinsic::x86_avx2_psll_d:
2355     case llvm::Intrinsic::x86_avx2_psll_q:
2356     case llvm::Intrinsic::x86_avx2_pslli_w:
2357     case llvm::Intrinsic::x86_avx2_pslli_d:
2358     case llvm::Intrinsic::x86_avx2_pslli_q:
2359     case llvm::Intrinsic::x86_avx2_psrl_w:
2360     case llvm::Intrinsic::x86_avx2_psrl_d:
2361     case llvm::Intrinsic::x86_avx2_psrl_q:
2362     case llvm::Intrinsic::x86_avx2_psra_w:
2363     case llvm::Intrinsic::x86_avx2_psra_d:
2364     case llvm::Intrinsic::x86_avx2_psrli_w:
2365     case llvm::Intrinsic::x86_avx2_psrli_d:
2366     case llvm::Intrinsic::x86_avx2_psrli_q:
2367     case llvm::Intrinsic::x86_avx2_psrai_w:
2368     case llvm::Intrinsic::x86_avx2_psrai_d:
2369     case llvm::Intrinsic::x86_sse2_psll_w:
2370     case llvm::Intrinsic::x86_sse2_psll_d:
2371     case llvm::Intrinsic::x86_sse2_psll_q:
2372     case llvm::Intrinsic::x86_sse2_pslli_w:
2373     case llvm::Intrinsic::x86_sse2_pslli_d:
2374     case llvm::Intrinsic::x86_sse2_pslli_q:
2375     case llvm::Intrinsic::x86_sse2_psrl_w:
2376     case llvm::Intrinsic::x86_sse2_psrl_d:
2377     case llvm::Intrinsic::x86_sse2_psrl_q:
2378     case llvm::Intrinsic::x86_sse2_psra_w:
2379     case llvm::Intrinsic::x86_sse2_psra_d:
2380     case llvm::Intrinsic::x86_sse2_psrli_w:
2381     case llvm::Intrinsic::x86_sse2_psrli_d:
2382     case llvm::Intrinsic::x86_sse2_psrli_q:
2383     case llvm::Intrinsic::x86_sse2_psrai_w:
2384     case llvm::Intrinsic::x86_sse2_psrai_d:
2385     case llvm::Intrinsic::x86_mmx_psll_w:
2386     case llvm::Intrinsic::x86_mmx_psll_d:
2387     case llvm::Intrinsic::x86_mmx_psll_q:
2388     case llvm::Intrinsic::x86_mmx_pslli_w:
2389     case llvm::Intrinsic::x86_mmx_pslli_d:
2390     case llvm::Intrinsic::x86_mmx_pslli_q:
2391     case llvm::Intrinsic::x86_mmx_psrl_w:
2392     case llvm::Intrinsic::x86_mmx_psrl_d:
2393     case llvm::Intrinsic::x86_mmx_psrl_q:
2394     case llvm::Intrinsic::x86_mmx_psra_w:
2395     case llvm::Intrinsic::x86_mmx_psra_d:
2396     case llvm::Intrinsic::x86_mmx_psrli_w:
2397     case llvm::Intrinsic::x86_mmx_psrli_d:
2398     case llvm::Intrinsic::x86_mmx_psrli_q:
2399     case llvm::Intrinsic::x86_mmx_psrai_w:
2400     case llvm::Intrinsic::x86_mmx_psrai_d:
2401       handleVectorShiftIntrinsic(I, /* Variable */ false);
2402       break;
2403     case llvm::Intrinsic::x86_avx2_psllv_d:
2404     case llvm::Intrinsic::x86_avx2_psllv_d_256:
2405     case llvm::Intrinsic::x86_avx2_psllv_q:
2406     case llvm::Intrinsic::x86_avx2_psllv_q_256:
2407     case llvm::Intrinsic::x86_avx2_psrlv_d:
2408     case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2409     case llvm::Intrinsic::x86_avx2_psrlv_q:
2410     case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2411     case llvm::Intrinsic::x86_avx2_psrav_d:
2412     case llvm::Intrinsic::x86_avx2_psrav_d_256:
2413       handleVectorShiftIntrinsic(I, /* Variable */ true);
2414       break;
2415 
2416     case llvm::Intrinsic::x86_sse2_packsswb_128:
2417     case llvm::Intrinsic::x86_sse2_packssdw_128:
2418     case llvm::Intrinsic::x86_sse2_packuswb_128:
2419     case llvm::Intrinsic::x86_sse41_packusdw:
2420     case llvm::Intrinsic::x86_avx2_packsswb:
2421     case llvm::Intrinsic::x86_avx2_packssdw:
2422     case llvm::Intrinsic::x86_avx2_packuswb:
2423     case llvm::Intrinsic::x86_avx2_packusdw:
2424       handleVectorPackIntrinsic(I);
2425       break;
2426 
2427     case llvm::Intrinsic::x86_mmx_packsswb:
2428     case llvm::Intrinsic::x86_mmx_packuswb:
2429       handleVectorPackIntrinsic(I, 16);
2430       break;
2431 
2432     case llvm::Intrinsic::x86_mmx_packssdw:
2433       handleVectorPackIntrinsic(I, 32);
2434       break;
2435 
2436     case llvm::Intrinsic::x86_mmx_psad_bw:
2437     case llvm::Intrinsic::x86_sse2_psad_bw:
2438     case llvm::Intrinsic::x86_avx2_psad_bw:
2439       handleVectorSadIntrinsic(I);
2440       break;
2441 
2442     case llvm::Intrinsic::x86_sse2_pmadd_wd:
2443     case llvm::Intrinsic::x86_avx2_pmadd_wd:
2444     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2445     case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2446       handleVectorPmaddIntrinsic(I);
2447       break;
2448 
2449     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2450       handleVectorPmaddIntrinsic(I, 8);
2451       break;
2452 
2453     case llvm::Intrinsic::x86_mmx_pmadd_wd:
2454       handleVectorPmaddIntrinsic(I, 16);
2455       break;
2456 
2457     default:
2458       if (!handleUnknownIntrinsic(I))
2459         visitInstruction(I);
2460       break;
2461     }
2462   }
2463 
2464   void visitCallSite(CallSite CS) {
2465     Instruction &I = *CS.getInstruction();
2466     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2467     if (CS.isCall()) {
2468       CallInst *Call = cast<CallInst>(&I);
2469 
2470       // For inline asm, do the usual thing: check argument shadow and mark all
2471       // outputs as clean. Note that any side effects of the inline asm that are
2472       // not immediately visible in its constraints are not handled.
2473       if (Call->isInlineAsm()) {
2474         visitInstruction(I);
2475         return;
2476       }
2477 
2478       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
2479 
2480       // We are going to insert code that relies on the fact that the callee
2481       // will become a non-readonly function after it is instrumented by us. To
2482       // prevent this code from being optimized out, mark that function
2483       // non-readonly in advance.
2484       if (Function *Func = Call->getCalledFunction()) {
2485         // Clear out readonly/readnone attributes.
2486         AttrBuilder B;
2487         B.addAttribute(Attribute::ReadOnly)
2488           .addAttribute(Attribute::ReadNone);
2489         Func->removeAttributes(AttributeSet::FunctionIndex,
2490                                AttributeSet::get(Func->getContext(),
2491                                                  AttributeSet::FunctionIndex,
2492                                                  B));
2493       }
2494     }
2495     IRBuilder<> IRB(&I);
2496 
2497     unsigned ArgOffset = 0;
2498     DEBUG(dbgs() << "  CallSite: " << I << "\n");
2499     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2500          ArgIt != End; ++ArgIt) {
2501       Value *A = *ArgIt;
2502       unsigned i = ArgIt - CS.arg_begin();
2503       if (!A->getType()->isSized()) {
2504         DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2505         continue;
2506       }
2507       unsigned Size = 0;
2508       Value *Store = nullptr;
2509       // Compute the Shadow for arg even if it is ByVal, because
2510       // in that case getShadow() will copy the actual arg shadow to
2511       // __msan_param_tls.
2512       Value *ArgShadow = getShadow(A);
2513       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2514       DEBUG(dbgs() << "  Arg#" << i << ": " << *A <<
2515             " Shadow: " << *ArgShadow << "\n");
2516       bool ArgIsInitialized = false;
2517       const DataLayout &DL = F.getParent()->getDataLayout();
2518       if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
2519         assert(A->getType()->isPointerTy() &&
2520                "ByVal argument is not a pointer!");
2521         Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
2522         if (ArgOffset + Size > kParamTLSSize) break;
2523         unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2524         unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
2525         Store = IRB.CreateMemCpy(ArgShadowBase,
2526                                  getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2527                                  Size, Alignment);
2528       } else {
2529         Size = DL.getTypeAllocSize(A->getType());
2530         if (ArgOffset + Size > kParamTLSSize) break;
2531         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2532                                        kShadowTLSAlignment);
2533         Constant *Cst = dyn_cast<Constant>(ArgShadow);
2534         if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
2535       }
2536       if (MS.TrackOrigins && !ArgIsInitialized)
2537         IRB.CreateStore(getOrigin(A),
2538                         getOriginPtrForArgument(A, IRB, ArgOffset));
2539       (void)Store;
2540       assert(Size != 0 && Store != nullptr);
2541       DEBUG(dbgs() << "  Param:" << *Store << "\n");
2542       ArgOffset += RoundUpToAlignment(Size, 8);
2543     }
2544     DEBUG(dbgs() << "  done with call args\n");
2545 
2546     FunctionType *FT =
2547       cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
2548     if (FT->isVarArg()) {
2549       VAHelper->visitCallSite(CS, IRB);
2550     }
2551 
2552     // Now, get the shadow for the RetVal.
2553     if (!I.getType()->isSized()) return;
2554     // Don't emit the epilogue for musttail call returns.
2555     if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
2556     IRBuilder<> IRBBefore(&I);
2557     // Until we have full dynamic coverage, make sure the retval shadow is 0.
2558     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
2559     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
2560     BasicBlock::iterator NextInsn;
2561     if (CS.isCall()) {
2562       NextInsn = ++I.getIterator();
2563       assert(NextInsn != I.getParent()->end());
2564     } else {
2565       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2566       if (!NormalDest->getSinglePredecessor()) {
2567         // FIXME: this case is tricky, so we are just conservative here.
2568         // Perhaps we need to split the edge between this BB and NormalDest,
2569         // but a naive attempt to use SplitEdge leads to a crash.
2570         setShadow(&I, getCleanShadow(&I));
2571         setOrigin(&I, getCleanOrigin());
2572         return;
2573       }
2574       NextInsn = NormalDest->getFirstInsertionPt();
2575       assert(NextInsn != NormalDest->end() &&
2576              "Could not find insertion point for retval shadow load");
2577     }
2578     IRBuilder<> IRBAfter(&*NextInsn);
2579     Value *RetvalShadow =
2580       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2581                                  kShadowTLSAlignment, "_msret");
2582     setShadow(&I, RetvalShadow);
2583     if (MS.TrackOrigins)
2584       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2585   }
2586 
2587   bool isAMustTailRetVal(Value *RetVal) {
2588     if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
2589       RetVal = I->getOperand(0);
2590     }
2591     if (auto *I = dyn_cast<CallInst>(RetVal)) {
2592       return I->isMustTailCall();
2593     }
2594     return false;
2595   }
2596 
2597   void visitReturnInst(ReturnInst &I) {
2598     IRBuilder<> IRB(&I);
2599     Value *RetVal = I.getReturnValue();
2600     if (!RetVal) return;
2601     // Don't emit the epilogue for musttail call returns.
2602     if (isAMustTailRetVal(RetVal)) return;
2603     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2604     if (CheckReturnValue) {
2605       insertShadowCheck(RetVal, &I);
2606       Value *Shadow = getCleanShadow(RetVal);
2607       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2608     } else {
2609       Value *Shadow = getShadow(RetVal);
2610       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2611       // FIXME: make it conditional if ClStoreCleanOrigin==0
2612       if (MS.TrackOrigins)
2613         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2614     }
2615   }
2616 
2617   void visitPHINode(PHINode &I) {
2618     IRBuilder<> IRB(&I);
2619     if (!PropagateShadow) {
2620       setShadow(&I, getCleanShadow(&I));
2621       setOrigin(&I, getCleanOrigin());
2622       return;
2623     }
2624 
2625     ShadowPHINodes.push_back(&I);
2626     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2627                                 "_msphi_s"));
2628     if (MS.TrackOrigins)
2629       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2630                                   "_msphi_o"));
2631   }
2632 
2633   void visitAllocaInst(AllocaInst &I) {
2634     setShadow(&I, getCleanShadow(&I));
2635     setOrigin(&I, getCleanOrigin());
2636     IRBuilder<> IRB(I.getNextNode());
2637     const DataLayout &DL = F.getParent()->getDataLayout();
2638     uint64_t Size = DL.getTypeAllocSize(I.getAllocatedType());
2639     if (PoisonStack && ClPoisonStackWithCall) {
2640       IRB.CreateCall(MS.MsanPoisonStackFn,
2641                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2642                       ConstantInt::get(MS.IntptrTy, Size)});
2643     } else {
2644       Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2645       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2646       IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2647     }
2648 
2649     if (PoisonStack && MS.TrackOrigins) {
2650       SmallString<2048> StackDescriptionStorage;
2651       raw_svector_ostream StackDescription(StackDescriptionStorage);
2652       // We create a string with a description of the stack allocation and
2653       // pass it into __msan_set_alloca_origin.
2654       // It will be printed by the run-time if stack-originated UMR is found.
2655       // The first 4 bytes of the string are set to '----' and will be replaced
2656       // by __msan_va_arg_overflow_size_tls at the first call.
2657       StackDescription << "----" << I.getName() << "@" << F.getName();
2658       Value *Descr =
2659           createPrivateNonConstGlobalForString(*F.getParent(),
2660                                                StackDescription.str());
2661 
2662       IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
2663                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2664                       ConstantInt::get(MS.IntptrTy, Size),
2665                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2666                       IRB.CreatePointerCast(&F, MS.IntptrTy)});
2667     }
2668   }
2669 
2670   void visitSelectInst(SelectInst& I) {
2671     IRBuilder<> IRB(&I);
2672     // a = select b, c, d
2673     Value *B = I.getCondition();
2674     Value *C = I.getTrueValue();
2675     Value *D = I.getFalseValue();
2676     Value *Sb = getShadow(B);
2677     Value *Sc = getShadow(C);
2678     Value *Sd = getShadow(D);
2679 
2680     // Result shadow if condition shadow is 0.
2681     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2682     Value *Sa1;
2683     if (I.getType()->isAggregateType()) {
2684       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2685       // an extra "select". This results in much more compact IR.
2686       // Sa = select Sb, poisoned, (select b, Sc, Sd)
2687       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
2688     } else {
2689       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2690       // If Sb (condition is poisoned), look for bits in c and d that are equal
2691       // and both unpoisoned.
2692       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2693 
2694       // Cast arguments to shadow-compatible type.
2695       C = CreateAppToShadowCast(IRB, C);
2696       D = CreateAppToShadowCast(IRB, D);
2697 
2698       // Result shadow if condition shadow is 1.
2699       Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
2700     }
2701     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2702     setShadow(&I, Sa);
2703     if (MS.TrackOrigins) {
2704       // Origins are always i32, so any vector conditions must be flattened.
2705       // FIXME: consider tracking vector origins for app vectors?
2706       if (B->getType()->isVectorTy()) {
2707         Type *FlatTy = getShadowTyNoVec(B->getType());
2708         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
2709                                 ConstantInt::getNullValue(FlatTy));
2710         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
2711                                       ConstantInt::getNullValue(FlatTy));
2712       }
2713       // a = select b, c, d
2714       // Oa = Sb ? Ob : (b ? Oc : Od)
2715       setOrigin(
2716           &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2717                                IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2718                                                 getOrigin(I.getFalseValue()))));
2719     }
2720   }
2721 
2722   void visitLandingPadInst(LandingPadInst &I) {
2723     // Do nothing.
2724     // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2725     setShadow(&I, getCleanShadow(&I));
2726     setOrigin(&I, getCleanOrigin());
2727   }
2728 
2729   void visitCleanupPadInst(CleanupPadInst &I) {
2730     setShadow(&I, getCleanShadow(&I));
2731     setOrigin(&I, getCleanOrigin());
2732   }
2733 
2734   void visitCatchPad(CatchPadInst &I) {
2735     setShadow(&I, getCleanShadow(&I));
2736     setOrigin(&I, getCleanOrigin());
2737   }
2738 
2739   void visitTerminatePad(TerminatePadInst &I) {
2740     DEBUG(dbgs() << "TerminatePad: " << I << "\n");
2741     // Nothing to do here.
2742   }
2743 
2744   void visitCatchEndPadInst(CatchEndPadInst &I) {
2745     DEBUG(dbgs() << "CatchEndPad: " << I << "\n");
2746     // Nothing to do here.
2747   }
2748 
2749   void visitCleanupEndPadInst(CleanupEndPadInst &I) {
2750     DEBUG(dbgs() << "CleanupEndPad: " << I << "\n");
2751     // Nothing to do here.
2752   }
2753 
2754   void visitGetElementPtrInst(GetElementPtrInst &I) {
2755     handleShadowOr(I);
2756   }
2757 
2758   void visitExtractValueInst(ExtractValueInst &I) {
2759     IRBuilder<> IRB(&I);
2760     Value *Agg = I.getAggregateOperand();
2761     DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
2762     Value *AggShadow = getShadow(Agg);
2763     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2764     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2765     DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
2766     setShadow(&I, ResShadow);
2767     setOriginForNaryOp(I);
2768   }
2769 
2770   void visitInsertValueInst(InsertValueInst &I) {
2771     IRBuilder<> IRB(&I);
2772     DEBUG(dbgs() << "InsertValue:  " << I << "\n");
2773     Value *AggShadow = getShadow(I.getAggregateOperand());
2774     Value *InsShadow = getShadow(I.getInsertedValueOperand());
2775     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2776     DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
2777     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2778     DEBUG(dbgs() << "   Res:        " << *Res << "\n");
2779     setShadow(&I, Res);
2780     setOriginForNaryOp(I);
2781   }
2782 
2783   void dumpInst(Instruction &I) {
2784     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2785       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2786     } else {
2787       errs() << "ZZZ " << I.getOpcodeName() << "\n";
2788     }
2789     errs() << "QQQ " << I << "\n";
2790   }
2791 
2792   void visitResumeInst(ResumeInst &I) {
2793     DEBUG(dbgs() << "Resume: " << I << "\n");
2794     // Nothing to do here.
2795   }
2796 
2797   void visitCleanupReturnInst(CleanupReturnInst &CRI) {
2798     DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
2799     // Nothing to do here.
2800   }
2801 
2802   void visitCatchReturnInst(CatchReturnInst &CRI) {
2803     DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
2804     // Nothing to do here.
2805   }
2806 
2807   void visitInstruction(Instruction &I) {
2808     // Everything else: stop propagating and check for poisoned shadow.
2809     if (ClDumpStrictInstructions)
2810       dumpInst(I);
2811     DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2812     for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2813       insertShadowCheck(I.getOperand(i), &I);
2814     setShadow(&I, getCleanShadow(&I));
2815     setOrigin(&I, getCleanOrigin());
2816   }
2817 };
2818 
2819 /// \brief AMD64-specific implementation of VarArgHelper.
2820 struct VarArgAMD64Helper : public VarArgHelper {
2821   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2822   // See a comment in visitCallSite for more details.
2823   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
2824   static const unsigned AMD64FpEndOffset = 176;
2825 
2826   Function &F;
2827   MemorySanitizer &MS;
2828   MemorySanitizerVisitor &MSV;
2829   Value *VAArgTLSCopy;
2830   Value *VAArgOverflowSize;
2831 
2832   SmallVector<CallInst*, 16> VAStartInstrumentationList;
2833 
2834   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2835                     MemorySanitizerVisitor &MSV)
2836     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2837       VAArgOverflowSize(nullptr) {}
2838 
2839   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2840 
2841   ArgKind classifyArgument(Value* arg) {
2842     // A very rough approximation of X86_64 argument classification rules.
2843     Type *T = arg->getType();
2844     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2845       return AK_FloatingPoint;
2846     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2847       return AK_GeneralPurpose;
2848     if (T->isPointerTy())
2849       return AK_GeneralPurpose;
2850     return AK_Memory;
2851   }
2852 
2853   // For VarArg functions, store the argument shadow in an ABI-specific format
2854   // that corresponds to va_list layout.
2855   // We do this because Clang lowers va_arg in the frontend, and this pass
2856   // only sees the low level code that deals with va_list internals.
2857   // A much easier alternative (provided that Clang emits va_arg instructions)
2858   // would have been to associate each live instance of va_list with a copy of
2859   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2860   // order.
2861   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2862     unsigned GpOffset = 0;
2863     unsigned FpOffset = AMD64GpEndOffset;
2864     unsigned OverflowOffset = AMD64FpEndOffset;
2865     const DataLayout &DL = F.getParent()->getDataLayout();
2866     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2867          ArgIt != End; ++ArgIt) {
2868       Value *A = *ArgIt;
2869       unsigned ArgNo = CS.getArgumentNo(ArgIt);
2870       bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2871       if (IsByVal) {
2872         // ByVal arguments always go to the overflow area.
2873         assert(A->getType()->isPointerTy());
2874         Type *RealTy = A->getType()->getPointerElementType();
2875         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
2876         Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
2877         OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2878         IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2879                          ArgSize, kShadowTLSAlignment);
2880       } else {
2881         ArgKind AK = classifyArgument(A);
2882         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2883           AK = AK_Memory;
2884         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2885           AK = AK_Memory;
2886         Value *Base;
2887         switch (AK) {
2888           case AK_GeneralPurpose:
2889             Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2890             GpOffset += 8;
2891             break;
2892           case AK_FloatingPoint:
2893             Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2894             FpOffset += 16;
2895             break;
2896           case AK_Memory:
2897             uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
2898             Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2899             OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2900         }
2901         IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2902       }
2903     }
2904     Constant *OverflowSize =
2905       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2906     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2907   }
2908 
2909   /// \brief Compute the shadow address for a given va_arg.
2910   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2911                                    int ArgOffset) {
2912     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2913     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2914     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2915                               "_msarg");
2916   }
2917 
2918   void visitVAStartInst(VAStartInst &I) override {
2919     if (F.getCallingConv() == CallingConv::X86_64_Win64)
2920       return;
2921     IRBuilder<> IRB(&I);
2922     VAStartInstrumentationList.push_back(&I);
2923     Value *VAListTag = I.getArgOperand(0);
2924     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2925 
2926     // Unpoison the whole __va_list_tag.
2927     // FIXME: magic ABI constants.
2928     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2929                      /* size */24, /* alignment */8, false);
2930   }
2931 
2932   void visitVACopyInst(VACopyInst &I) override {
2933     if (F.getCallingConv() == CallingConv::X86_64_Win64)
2934       return;
2935     IRBuilder<> IRB(&I);
2936     Value *VAListTag = I.getArgOperand(0);
2937     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2938 
2939     // Unpoison the whole __va_list_tag.
2940     // FIXME: magic ABI constants.
2941     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2942                      /* size */24, /* alignment */8, false);
2943   }
2944 
2945   void finalizeInstrumentation() override {
2946     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2947            "finalizeInstrumentation called twice");
2948     if (!VAStartInstrumentationList.empty()) {
2949       // If there is a va_start in this function, make a backup copy of
2950       // va_arg_tls somewhere in the function entry block.
2951       IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2952       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2953       Value *CopySize =
2954         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2955                       VAArgOverflowSize);
2956       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2957       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2958     }
2959 
2960     // Instrument va_start.
2961     // Copy va_list shadow from the backup copy of the TLS contents.
2962     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2963       CallInst *OrigInst = VAStartInstrumentationList[i];
2964       IRBuilder<> IRB(OrigInst->getNextNode());
2965       Value *VAListTag = OrigInst->getArgOperand(0);
2966 
2967       Value *RegSaveAreaPtrPtr =
2968         IRB.CreateIntToPtr(
2969           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2970                         ConstantInt::get(MS.IntptrTy, 16)),
2971           Type::getInt64PtrTy(*MS.C));
2972       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2973       Value *RegSaveAreaShadowPtr =
2974         MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2975       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2976                        AMD64FpEndOffset, 16);
2977 
2978       Value *OverflowArgAreaPtrPtr =
2979         IRB.CreateIntToPtr(
2980           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2981                         ConstantInt::get(MS.IntptrTy, 8)),
2982           Type::getInt64PtrTy(*MS.C));
2983       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2984       Value *OverflowArgAreaShadowPtr =
2985         MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2986       Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
2987                                              AMD64FpEndOffset);
2988       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2989     }
2990   }
2991 };
2992 
2993 /// \brief MIPS64-specific implementation of VarArgHelper.
2994 struct VarArgMIPS64Helper : public VarArgHelper {
2995   Function &F;
2996   MemorySanitizer &MS;
2997   MemorySanitizerVisitor &MSV;
2998   Value *VAArgTLSCopy;
2999   Value *VAArgSize;
3000 
3001   SmallVector<CallInst*, 16> VAStartInstrumentationList;
3002 
3003   VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
3004                     MemorySanitizerVisitor &MSV)
3005     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
3006       VAArgSize(nullptr) {}
3007 
3008   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
3009     unsigned VAArgOffset = 0;
3010     const DataLayout &DL = F.getParent()->getDataLayout();
3011     for (CallSite::arg_iterator ArgIt = CS.arg_begin() + 1, End = CS.arg_end();
3012          ArgIt != End; ++ArgIt) {
3013       Value *A = *ArgIt;
3014       Value *Base;
3015       uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
3016 #if defined(__MIPSEB__) || defined(MIPSEB)
3017       // Adjusting the shadow for argument with size < 8 to match the placement
3018       // of bits in big endian system
3019       if (ArgSize < 8)
3020         VAArgOffset += (8 - ArgSize);
3021 #endif
3022       Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
3023       VAArgOffset += ArgSize;
3024       VAArgOffset = RoundUpToAlignment(VAArgOffset, 8);
3025       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
3026     }
3027 
3028     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
3029     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
3030     // a new class member i.e. it is the total size of all VarArgs.
3031     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
3032   }
3033 
3034   /// \brief Compute the shadow address for a given va_arg.
3035   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3036                                    int ArgOffset) {
3037     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3038     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3039     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3040                               "_msarg");
3041   }
3042 
3043   void visitVAStartInst(VAStartInst &I) override {
3044     IRBuilder<> IRB(&I);
3045     VAStartInstrumentationList.push_back(&I);
3046     Value *VAListTag = I.getArgOperand(0);
3047     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3048     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3049                      /* size */8, /* alignment */8, false);
3050   }
3051 
3052   void visitVACopyInst(VACopyInst &I) override {
3053     IRBuilder<> IRB(&I);
3054     Value *VAListTag = I.getArgOperand(0);
3055     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3056     // Unpoison the whole __va_list_tag.
3057     // FIXME: magic ABI constants.
3058     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3059                      /* size */8, /* alignment */8, false);
3060   }
3061 
3062   void finalizeInstrumentation() override {
3063     assert(!VAArgSize && !VAArgTLSCopy &&
3064            "finalizeInstrumentation called twice");
3065     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
3066     VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3067     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
3068                                     VAArgSize);
3069 
3070     if (!VAStartInstrumentationList.empty()) {
3071       // If there is a va_start in this function, make a backup copy of
3072       // va_arg_tls somewhere in the function entry block.
3073       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3074       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
3075     }
3076 
3077     // Instrument va_start.
3078     // Copy va_list shadow from the backup copy of the TLS contents.
3079     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3080       CallInst *OrigInst = VAStartInstrumentationList[i];
3081       IRBuilder<> IRB(OrigInst->getNextNode());
3082       Value *VAListTag = OrigInst->getArgOperand(0);
3083       Value *RegSaveAreaPtrPtr =
3084         IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3085                         Type::getInt64PtrTy(*MS.C));
3086       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3087       Value *RegSaveAreaShadowPtr =
3088       MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
3089       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
3090     }
3091   }
3092 };
3093 
3094 /// \brief A no-op implementation of VarArgHelper.
3095 struct VarArgNoOpHelper : public VarArgHelper {
3096   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
3097                    MemorySanitizerVisitor &MSV) {}
3098 
3099   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
3100 
3101   void visitVAStartInst(VAStartInst &I) override {}
3102 
3103   void visitVACopyInst(VACopyInst &I) override {}
3104 
3105   void finalizeInstrumentation() override {}
3106 };
3107 
3108 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
3109                                  MemorySanitizerVisitor &Visitor) {
3110   // VarArg handling is only implemented on AMD64. False positives are possible
3111   // on other platforms.
3112   llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
3113   if (TargetTriple.getArch() == llvm::Triple::x86_64)
3114     return new VarArgAMD64Helper(Func, Msan, Visitor);
3115   else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
3116            TargetTriple.getArch() == llvm::Triple::mips64el)
3117     return new VarArgMIPS64Helper(Func, Msan, Visitor);
3118   else
3119     return new VarArgNoOpHelper(Func, Msan, Visitor);
3120 }
3121 
3122 } // anonymous namespace
3123 
3124 bool MemorySanitizer::runOnFunction(Function &F) {
3125   if (&F == MsanCtorFunction)
3126     return false;
3127   MemorySanitizerVisitor Visitor(F, *this);
3128 
3129   // Clear out readonly/readnone attributes.
3130   AttrBuilder B;
3131   B.addAttribute(Attribute::ReadOnly)
3132     .addAttribute(Attribute::ReadNone);
3133   F.removeAttributes(AttributeSet::FunctionIndex,
3134                      AttributeSet::get(F.getContext(),
3135                                        AttributeSet::FunctionIndex, B));
3136 
3137   return Visitor.runOnFunction();
3138 }
3139