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