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