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