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