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