[msan] Handling of atomic load/store, atomic rmw, cmpxchg.
[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 /// Status: early prototype.
14 ///
15 /// The algorithm of the tool is similar to Memcheck
16 /// (http://goo.gl/QKbem). We associate a few shadow bits with every
17 /// byte of the application memory, poison the shadow of the malloc-ed
18 /// or alloca-ed memory, load the shadow bits on every memory read,
19 /// propagate the shadow bits through some of the arithmetic
20 /// instruction (including MOV), store the shadow bits on every memory
21 /// write, report a bug on some other instructions (e.g. JMP) if the
22 /// associated shadow is poisoned.
23 ///
24 /// But there are differences too. The first and the major one:
25 /// compiler instrumentation instead of binary instrumentation. This
26 /// gives us much better register allocation, possible compiler
27 /// optimizations and a fast start-up. But this brings the major issue
28 /// as well: msan needs to see all program events, including system
29 /// calls and reads/writes in system libraries, so we either need to
30 /// compile *everything* with msan or use a binary translation
31 /// component (e.g. DynamoRIO) to instrument pre-built libraries.
32 /// Another difference from Memcheck is that we use 8 shadow bits per
33 /// byte of application memory and use a direct shadow mapping. This
34 /// greatly simplifies the instrumentation code and avoids races on
35 /// shadow updates (Memcheck is single-threaded so races are not a
36 /// concern there. Memcheck uses 2 shadow bits per byte with a slow
37 /// path storage that uses 8 bits per byte).
38 ///
39 /// The default value of shadow is 0, which means "clean" (not poisoned).
40 ///
41 /// Every module initializer should call __msan_init to ensure that the
42 /// shadow memory is ready. On error, __msan_warning is called. Since
43 /// parameters and return values may be passed via registers, we have a
44 /// specialized thread-local shadow for return values
45 /// (__msan_retval_tls) and parameters (__msan_param_tls).
46 ///
47 ///                           Origin tracking.
48 ///
49 /// MemorySanitizer can track origins (allocation points) of all uninitialized
50 /// values. This behavior is controlled with a flag (msan-track-origins) and is
51 /// disabled by default.
52 ///
53 /// Origins are 4-byte values created and interpreted by the runtime library.
54 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
55 /// of application memory. Propagation of origins is basically a bunch of
56 /// "select" instructions that pick the origin of a dirty argument, if an
57 /// instruction has one.
58 ///
59 /// Every 4 aligned, consecutive bytes of application memory have one origin
60 /// value associated with them. If these bytes contain uninitialized data
61 /// coming from 2 different allocations, the last store wins. Because of this,
62 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
63 /// practice.
64 ///
65 /// Origins are meaningless for fully initialized values, so MemorySanitizer
66 /// avoids storing origin to memory when a fully initialized value is stored.
67 /// This way it avoids needless overwritting origin of the 4-byte region on
68 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
69 ///
70 ///                            Atomic handling.
71 ///
72 /// Ideally, every atomic store of application value should update the
73 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
74 /// of two disjoint locations can not be done without severe slowdown.
75 ///
76 /// Therefore, we implement an approximation that may err on the safe side.
77 /// In this implementation, every atomically accessed location in the program
78 /// may only change from (partially) uninitialized to fully initialized, but
79 /// not the other way around. We load the shadow _after_ the application load,
80 /// and we store the shadow _before_ the app store. Also, we always store clean
81 /// shadow (if the application store is atomic). This way, if the store-load
82 /// pair constitutes a happens-before arc, shadow store and load are correctly
83 /// ordered such that the load will get either the value that was stored, or
84 /// some later value (which is always clean).
85 ///
86 /// This does not work very well with Compare-And-Swap (CAS) and
87 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
88 /// must store the new shadow before the app operation, and load the shadow
89 /// after the app operation. Computers don't work this way. Current
90 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
91 /// value. It implements the store part as a simple atomic store by storing a
92 /// clean shadow.
93
94 //===----------------------------------------------------------------------===//
95
96 #define DEBUG_TYPE "msan"
97
98 #include "llvm/Transforms/Instrumentation.h"
99 #include "llvm/ADT/DepthFirstIterator.h"
100 #include "llvm/ADT/SmallString.h"
101 #include "llvm/ADT/SmallVector.h"
102 #include "llvm/ADT/Triple.h"
103 #include "llvm/ADT/ValueMap.h"
104 #include "llvm/IR/DataLayout.h"
105 #include "llvm/IR/Function.h"
106 #include "llvm/IR/IRBuilder.h"
107 #include "llvm/IR/InlineAsm.h"
108 #include "llvm/IR/IntrinsicInst.h"
109 #include "llvm/IR/LLVMContext.h"
110 #include "llvm/IR/MDBuilder.h"
111 #include "llvm/IR/Module.h"
112 #include "llvm/IR/Type.h"
113 #include "llvm/InstVisitor.h"
114 #include "llvm/Support/CommandLine.h"
115 #include "llvm/Support/Compiler.h"
116 #include "llvm/Support/Debug.h"
117 #include "llvm/Support/raw_ostream.h"
118 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
119 #include "llvm/Transforms/Utils/Local.h"
120 #include "llvm/Transforms/Utils/ModuleUtils.h"
121 #include "llvm/Transforms/Utils/SpecialCaseList.h"
122
123 using namespace llvm;
124
125 static const uint64_t kShadowMask32 = 1ULL << 31;
126 static const uint64_t kShadowMask64 = 1ULL << 46;
127 static const uint64_t kOriginOffset32 = 1ULL << 30;
128 static const uint64_t kOriginOffset64 = 1ULL << 45;
129 static const unsigned kMinOriginAlignment = 4;
130 static const unsigned kShadowTLSAlignment = 8;
131
132 /// \brief Track origins of uninitialized values.
133 ///
134 /// Adds a section to MemorySanitizer report that points to the allocation
135 /// (stack or heap) the uninitialized bits came from originally.
136 static cl::opt<bool> ClTrackOrigins("msan-track-origins",
137        cl::desc("Track origins (allocation sites) of poisoned memory"),
138        cl::Hidden, cl::init(false));
139 static cl::opt<bool> ClKeepGoing("msan-keep-going",
140        cl::desc("keep going after reporting a UMR"),
141        cl::Hidden, cl::init(false));
142 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
143        cl::desc("poison uninitialized stack variables"),
144        cl::Hidden, cl::init(true));
145 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
146        cl::desc("poison uninitialized stack variables with a call"),
147        cl::Hidden, cl::init(false));
148 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
149        cl::desc("poison uninitialized stack variables with the given patter"),
150        cl::Hidden, cl::init(0xff));
151 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
152        cl::desc("poison undef temps"),
153        cl::Hidden, cl::init(true));
154
155 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
156        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
157        cl::Hidden, cl::init(true));
158
159 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
160        cl::desc("exact handling of relational integer ICmp"),
161        cl::Hidden, cl::init(false));
162
163 static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
164        cl::desc("store origin for clean (fully initialized) values"),
165        cl::Hidden, cl::init(false));
166
167 // This flag controls whether we check the shadow of the address
168 // operand of load or store. Such bugs are very rare, since load from
169 // a garbage address typically results in SEGV, but still happen
170 // (e.g. only lower bits of address are garbage, or the access happens
171 // early at program startup where malloc-ed memory is more likely to
172 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
173 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
174        cl::desc("report accesses through a pointer which has poisoned shadow"),
175        cl::Hidden, cl::init(true));
176
177 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
178        cl::desc("print out instructions with default strict semantics"),
179        cl::Hidden, cl::init(false));
180
181 static cl::opt<std::string>  ClBlacklistFile("msan-blacklist",
182        cl::desc("File containing the list of functions where MemorySanitizer "
183                 "should not report bugs"), cl::Hidden);
184
185 // Experimental. Wraps all indirect calls in the instrumented code with
186 // a call to the given function. This is needed to assist the dynamic
187 // helper tool (MSanDR) to regain control on transition between instrumented and
188 // non-instrumented code.
189 static cl::opt<std::string> ClWrapIndirectCalls("msan-wrap-indirect-calls",
190        cl::desc("Wrap indirect calls with a given function"),
191        cl::Hidden);
192
193 namespace {
194
195 /// \brief An instrumentation pass implementing detection of uninitialized
196 /// reads.
197 ///
198 /// MemorySanitizer: instrument the code in module to find
199 /// uninitialized reads.
200 class MemorySanitizer : public FunctionPass {
201  public:
202   MemorySanitizer(bool TrackOrigins = false,
203                   StringRef BlacklistFile = StringRef())
204       : FunctionPass(ID),
205         TrackOrigins(TrackOrigins || ClTrackOrigins),
206         TD(0),
207         WarningFn(0),
208         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile : BlacklistFile),
209         WrapIndirectCalls(!ClWrapIndirectCalls.empty()) {}
210   const char *getPassName() const { return "MemorySanitizer"; }
211   bool runOnFunction(Function &F);
212   bool doInitialization(Module &M);
213   static char ID;  // Pass identification, replacement for typeid.
214
215  private:
216   void initializeCallbacks(Module &M);
217
218   /// \brief Track origins (allocation points) of uninitialized values.
219   bool TrackOrigins;
220
221   DataLayout *TD;
222   LLVMContext *C;
223   Type *IntptrTy;
224   Type *OriginTy;
225   /// \brief Thread-local shadow storage for function parameters.
226   GlobalVariable *ParamTLS;
227   /// \brief Thread-local origin storage for function parameters.
228   GlobalVariable *ParamOriginTLS;
229   /// \brief Thread-local shadow storage for function return value.
230   GlobalVariable *RetvalTLS;
231   /// \brief Thread-local origin storage for function return value.
232   GlobalVariable *RetvalOriginTLS;
233   /// \brief Thread-local shadow storage for in-register va_arg function
234   /// parameters (x86_64-specific).
235   GlobalVariable *VAArgTLS;
236   /// \brief Thread-local shadow storage for va_arg overflow area
237   /// (x86_64-specific).
238   GlobalVariable *VAArgOverflowSizeTLS;
239   /// \brief Thread-local space used to pass origin value to the UMR reporting
240   /// function.
241   GlobalVariable *OriginTLS;
242
243   /// \brief The run-time callback to print a warning.
244   Value *WarningFn;
245   /// \brief Run-time helper that copies origin info for a memory range.
246   Value *MsanCopyOriginFn;
247   /// \brief Run-time helper that generates a new origin value for a stack
248   /// allocation.
249   Value *MsanSetAllocaOrigin4Fn;
250   /// \brief Run-time helper that poisons stack on function entry.
251   Value *MsanPoisonStackFn;
252   /// \brief MSan runtime replacements for memmove, memcpy and memset.
253   Value *MemmoveFn, *MemcpyFn, *MemsetFn;
254
255   /// \brief Address mask used in application-to-shadow address calculation.
256   /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
257   uint64_t ShadowMask;
258   /// \brief Offset of the origin shadow from the "normal" shadow.
259   /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
260   uint64_t OriginOffset;
261   /// \brief Branch weights for error reporting.
262   MDNode *ColdCallWeights;
263   /// \brief Branch weights for origin store.
264   MDNode *OriginStoreWeights;
265   /// \brief Path to blacklist file.
266   SmallString<64> BlacklistFile;
267   /// \brief The blacklist.
268   OwningPtr<SpecialCaseList> BL;
269   /// \brief An empty volatile inline asm that prevents callback merge.
270   InlineAsm *EmptyAsm;
271
272   bool WrapIndirectCalls;
273   /// \brief Run-time wrapper for indirect calls.
274   Value *IndirectCallWrapperFn;
275   // Argument and return type of IndirectCallWrapperFn: void (*f)(void).
276   Type *AnyFunctionPtrTy;
277
278   friend struct MemorySanitizerVisitor;
279   friend struct VarArgAMD64Helper;
280 };
281 }  // namespace
282
283 char MemorySanitizer::ID = 0;
284 INITIALIZE_PASS(MemorySanitizer, "msan",
285                 "MemorySanitizer: detects uninitialized reads.",
286                 false, false)
287
288 FunctionPass *llvm::createMemorySanitizerPass(bool TrackOrigins,
289                                               StringRef BlacklistFile) {
290   return new MemorySanitizer(TrackOrigins, BlacklistFile);
291 }
292
293 /// \brief Create a non-const global initialized with the given string.
294 ///
295 /// Creates a writable global for Str so that we can pass it to the
296 /// run-time lib. Runtime uses first 4 bytes of the string to store the
297 /// frame ID, so the string needs to be mutable.
298 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
299                                                             StringRef Str) {
300   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
301   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
302                             GlobalValue::PrivateLinkage, StrConst, "");
303 }
304
305
306 /// \brief Insert extern declaration of runtime-provided functions and globals.
307 void MemorySanitizer::initializeCallbacks(Module &M) {
308   // Only do this once.
309   if (WarningFn)
310     return;
311
312   IRBuilder<> IRB(*C);
313   // Create the callback.
314   // FIXME: this function should have "Cold" calling conv,
315   // which is not yet implemented.
316   StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
317                                         : "__msan_warning_noreturn";
318   WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
319
320   MsanCopyOriginFn = M.getOrInsertFunction(
321     "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
322     IRB.getInt8PtrTy(), IntptrTy, NULL);
323   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
324     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
325     IRB.getInt8PtrTy(), IntptrTy, NULL);
326   MsanPoisonStackFn = M.getOrInsertFunction(
327     "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
328   MemmoveFn = M.getOrInsertFunction(
329     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
330     IRB.getInt8PtrTy(), IntptrTy, NULL);
331   MemcpyFn = M.getOrInsertFunction(
332     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
333     IntptrTy, NULL);
334   MemsetFn = M.getOrInsertFunction(
335     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
336     IntptrTy, NULL);
337
338   // Create globals.
339   RetvalTLS = new GlobalVariable(
340     M, ArrayType::get(IRB.getInt64Ty(), 8), false,
341     GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
342     GlobalVariable::InitialExecTLSModel);
343   RetvalOriginTLS = new GlobalVariable(
344     M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
345     "__msan_retval_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
346
347   ParamTLS = new GlobalVariable(
348     M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
349     GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
350     GlobalVariable::InitialExecTLSModel);
351   ParamOriginTLS = new GlobalVariable(
352     M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
353     0, "__msan_param_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
354
355   VAArgTLS = new GlobalVariable(
356     M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
357     GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
358     GlobalVariable::InitialExecTLSModel);
359   VAArgOverflowSizeTLS = new GlobalVariable(
360     M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
361     "__msan_va_arg_overflow_size_tls", 0,
362     GlobalVariable::InitialExecTLSModel);
363   OriginTLS = new GlobalVariable(
364     M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
365     "__msan_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
366
367   // We insert an empty inline asm after __msan_report* to avoid callback merge.
368   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
369                             StringRef(""), StringRef(""),
370                             /*hasSideEffects=*/true);
371
372   if (WrapIndirectCalls) {
373     AnyFunctionPtrTy =
374         PointerType::getUnqual(FunctionType::get(IRB.getVoidTy(), false));
375     IndirectCallWrapperFn = M.getOrInsertFunction(
376         ClWrapIndirectCalls, AnyFunctionPtrTy, AnyFunctionPtrTy, NULL);
377   }
378 }
379
380 /// \brief Module-level initialization.
381 ///
382 /// inserts a call to __msan_init to the module's constructor list.
383 bool MemorySanitizer::doInitialization(Module &M) {
384   TD = getAnalysisIfAvailable<DataLayout>();
385   if (!TD)
386     return false;
387   BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
388   C = &(M.getContext());
389   unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
390   switch (PtrSize) {
391     case 64:
392       ShadowMask = kShadowMask64;
393       OriginOffset = kOriginOffset64;
394       break;
395     case 32:
396       ShadowMask = kShadowMask32;
397       OriginOffset = kOriginOffset32;
398       break;
399     default:
400       report_fatal_error("unsupported pointer size");
401       break;
402   }
403
404   IRBuilder<> IRB(*C);
405   IntptrTy = IRB.getIntPtrTy(TD);
406   OriginTy = IRB.getInt32Ty();
407
408   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
409   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
410
411   // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
412   appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
413                       "__msan_init", IRB.getVoidTy(), NULL)), 0);
414
415   if (TrackOrigins)
416     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
417                        IRB.getInt32(TrackOrigins), "__msan_track_origins");
418
419   if (ClKeepGoing)
420     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
421                        IRB.getInt32(ClKeepGoing), "__msan_keep_going");
422
423   return true;
424 }
425
426 namespace {
427
428 /// \brief A helper class that handles instrumentation of VarArg
429 /// functions on a particular platform.
430 ///
431 /// Implementations are expected to insert the instrumentation
432 /// necessary to propagate argument shadow through VarArg function
433 /// calls. Visit* methods are called during an InstVisitor pass over
434 /// the function, and should avoid creating new basic blocks. A new
435 /// instance of this class is created for each instrumented function.
436 struct VarArgHelper {
437   /// \brief Visit a CallSite.
438   virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
439
440   /// \brief Visit a va_start call.
441   virtual void visitVAStartInst(VAStartInst &I) = 0;
442
443   /// \brief Visit a va_copy call.
444   virtual void visitVACopyInst(VACopyInst &I) = 0;
445
446   /// \brief Finalize function instrumentation.
447   ///
448   /// This method is called after visiting all interesting (see above)
449   /// instructions in a function.
450   virtual void finalizeInstrumentation() = 0;
451
452   virtual ~VarArgHelper() {}
453 };
454
455 struct MemorySanitizerVisitor;
456
457 VarArgHelper*
458 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
459                    MemorySanitizerVisitor &Visitor);
460
461 /// This class does all the work for a given function. Store and Load
462 /// instructions store and load corresponding shadow and origin
463 /// values. Most instructions propagate shadow from arguments to their
464 /// return values. Certain instructions (most importantly, BranchInst)
465 /// test their argument shadow and print reports (with a runtime call) if it's
466 /// non-zero.
467 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
468   Function &F;
469   MemorySanitizer &MS;
470   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
471   ValueMap<Value*, Value*> ShadowMap, OriginMap;
472   bool InsertChecks;
473   bool LoadShadow;
474   bool PoisonStack;
475   bool PoisonUndef;
476   bool CheckReturnValue;
477   OwningPtr<VarArgHelper> VAHelper;
478
479   struct ShadowOriginAndInsertPoint {
480     Instruction *Shadow;
481     Instruction *Origin;
482     Instruction *OrigIns;
483     ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
484       : Shadow(S), Origin(O), OrigIns(I) { }
485     ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
486   };
487   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
488   SmallVector<Instruction*, 16> StoreList;
489
490   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
491       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
492     bool SanitizeFunction = !MS.BL->isIn(F) && F.getAttributes().hasAttribute(
493                                                    AttributeSet::FunctionIndex,
494                                                    Attribute::SanitizeMemory);
495     InsertChecks = SanitizeFunction;
496     LoadShadow = SanitizeFunction;
497     PoisonStack = SanitizeFunction && ClPoisonStack;
498     PoisonUndef = SanitizeFunction && ClPoisonUndef;
499     // FIXME: Consider using SpecialCaseList to specify a list of functions that
500     // must always return fully initialized values. For now, we hardcode "main".
501     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
502
503     DEBUG(if (!InsertChecks)
504           dbgs() << "MemorySanitizer is not inserting checks into '"
505                  << F.getName() << "'\n");
506   }
507
508   void materializeStores() {
509     for (size_t i = 0, n = StoreList.size(); i < n; i++) {
510       StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
511
512       IRBuilder<> IRB(&I);
513       Value *Val = I.getValueOperand();
514       Value *Addr = I.getPointerOperand();
515       Value *Shadow = I.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
516       Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
517
518       StoreInst *NewSI =
519         IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
520       DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
521       (void)NewSI;
522
523       if (ClCheckAccessAddress)
524         insertCheck(Addr, &I);
525
526       if (I.isAtomic())
527         I.setOrdering(addReleaseOrdering(I.getOrdering()));
528
529       if (MS.TrackOrigins) {
530         unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
531         if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
532           IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB),
533                                  Alignment);
534         } else {
535           Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
536
537           Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
538           // TODO(eugenis): handle non-zero constant shadow by inserting an
539           // unconditional check (can not simply fail compilation as this could
540           // be in the dead code).
541           if (Cst)
542             continue;
543
544           Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
545               getCleanShadow(ConvertedShadow), "_mscmp");
546           Instruction *CheckTerm =
547             SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
548                                       MS.OriginStoreWeights);
549           IRBuilder<> IRBNew(CheckTerm);
550           IRBNew.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRBNew),
551                                     Alignment);
552         }
553       }
554     }
555   }
556
557   void materializeChecks() {
558     for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
559       Instruction *Shadow = InstrumentationList[i].Shadow;
560       Instruction *OrigIns = InstrumentationList[i].OrigIns;
561       IRBuilder<> IRB(OrigIns);
562       DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
563       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
564       DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
565       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
566                                     getCleanShadow(ConvertedShadow), "_mscmp");
567       Instruction *CheckTerm =
568         SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
569                                   /* Unreachable */ !ClKeepGoing,
570                                   MS.ColdCallWeights);
571
572       IRB.SetInsertPoint(CheckTerm);
573       if (MS.TrackOrigins) {
574         Instruction *Origin = InstrumentationList[i].Origin;
575         IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
576                         MS.OriginTLS);
577       }
578       CallInst *Call = IRB.CreateCall(MS.WarningFn);
579       Call->setDebugLoc(OrigIns->getDebugLoc());
580       IRB.CreateCall(MS.EmptyAsm);
581       DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
582     }
583     DEBUG(dbgs() << "DONE:\n" << F);
584   }
585
586   /// \brief Add MemorySanitizer instrumentation to a function.
587   bool runOnFunction() {
588     MS.initializeCallbacks(*F.getParent());
589     if (!MS.TD) return false;
590
591     // In the presence of unreachable blocks, we may see Phi nodes with
592     // incoming nodes from such blocks. Since InstVisitor skips unreachable
593     // blocks, such nodes will not have any shadow value associated with them.
594     // It's easier to remove unreachable blocks than deal with missing shadow.
595     removeUnreachableBlocks(F);
596
597     // Iterate all BBs in depth-first order and create shadow instructions
598     // for all instructions (where applicable).
599     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
600     for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
601          DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
602       BasicBlock *BB = *DI;
603       visit(*BB);
604     }
605
606     // Finalize PHI nodes.
607     for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
608       PHINode *PN = ShadowPHINodes[i];
609       PHINode *PNS = cast<PHINode>(getShadow(PN));
610       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
611       size_t NumValues = PN->getNumIncomingValues();
612       for (size_t v = 0; v < NumValues; v++) {
613         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
614         if (PNO)
615           PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
616       }
617     }
618
619     VAHelper->finalizeInstrumentation();
620
621     // Delayed instrumentation of StoreInst.
622     // This may add new checks to be inserted later.
623     materializeStores();
624
625     // Insert shadow value checks.
626     materializeChecks();
627
628     return true;
629   }
630
631   /// \brief Compute the shadow type that corresponds to a given Value.
632   Type *getShadowTy(Value *V) {
633     return getShadowTy(V->getType());
634   }
635
636   /// \brief Compute the shadow type that corresponds to a given Type.
637   Type *getShadowTy(Type *OrigTy) {
638     if (!OrigTy->isSized()) {
639       return 0;
640     }
641     // For integer type, shadow is the same as the original type.
642     // This may return weird-sized types like i1.
643     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
644       return IT;
645     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
646       uint32_t EltSize = MS.TD->getTypeSizeInBits(VT->getElementType());
647       return VectorType::get(IntegerType::get(*MS.C, EltSize),
648                              VT->getNumElements());
649     }
650     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
651       SmallVector<Type*, 4> Elements;
652       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
653         Elements.push_back(getShadowTy(ST->getElementType(i)));
654       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
655       DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
656       return Res;
657     }
658     uint32_t TypeSize = MS.TD->getTypeSizeInBits(OrigTy);
659     return IntegerType::get(*MS.C, TypeSize);
660   }
661
662   /// \brief Flatten a vector type.
663   Type *getShadowTyNoVec(Type *ty) {
664     if (VectorType *vt = dyn_cast<VectorType>(ty))
665       return IntegerType::get(*MS.C, vt->getBitWidth());
666     return ty;
667   }
668
669   /// \brief Convert a shadow value to it's flattened variant.
670   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
671     Type *Ty = V->getType();
672     Type *NoVecTy = getShadowTyNoVec(Ty);
673     if (Ty == NoVecTy) return V;
674     return IRB.CreateBitCast(V, NoVecTy);
675   }
676
677   /// \brief Compute the shadow address that corresponds to a given application
678   /// address.
679   ///
680   /// Shadow = Addr & ~ShadowMask.
681   Value *getShadowPtr(Value *Addr, Type *ShadowTy,
682                       IRBuilder<> &IRB) {
683     Value *ShadowLong =
684       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
685                     ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
686     return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
687   }
688
689   /// \brief Compute the origin address that corresponds to a given application
690   /// address.
691   ///
692   /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
693   Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
694     Value *ShadowLong =
695       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
696                     ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
697     Value *Add =
698       IRB.CreateAdd(ShadowLong,
699                     ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
700     Value *SecondAnd =
701       IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
702     return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
703   }
704
705   /// \brief Compute the shadow address for a given function argument.
706   ///
707   /// Shadow = ParamTLS+ArgOffset.
708   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
709                                  int ArgOffset) {
710     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
711     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
712     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
713                               "_msarg");
714   }
715
716   /// \brief Compute the origin address for a given function argument.
717   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
718                                  int ArgOffset) {
719     if (!MS.TrackOrigins) return 0;
720     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
721     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
722     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
723                               "_msarg_o");
724   }
725
726   /// \brief Compute the shadow address for a retval.
727   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
728     Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
729     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
730                               "_msret");
731   }
732
733   /// \brief Compute the origin address for a retval.
734   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
735     // We keep a single origin for the entire retval. Might be too optimistic.
736     return MS.RetvalOriginTLS;
737   }
738
739   /// \brief Set SV to be the shadow value for V.
740   void setShadow(Value *V, Value *SV) {
741     assert(!ShadowMap.count(V) && "Values may only have one shadow");
742     ShadowMap[V] = SV;
743   }
744
745   /// \brief Set Origin to be the origin value for V.
746   void setOrigin(Value *V, Value *Origin) {
747     if (!MS.TrackOrigins) return;
748     assert(!OriginMap.count(V) && "Values may only have one origin");
749     DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
750     OriginMap[V] = Origin;
751   }
752
753   /// \brief Create a clean shadow value for a given value.
754   ///
755   /// Clean shadow (all zeroes) means all bits of the value are defined
756   /// (initialized).
757   Constant *getCleanShadow(Value *V) {
758     Type *ShadowTy = getShadowTy(V);
759     if (!ShadowTy)
760       return 0;
761     return Constant::getNullValue(ShadowTy);
762   }
763
764   /// \brief Create a dirty shadow of a given shadow type.
765   Constant *getPoisonedShadow(Type *ShadowTy) {
766     assert(ShadowTy);
767     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
768       return Constant::getAllOnesValue(ShadowTy);
769     StructType *ST = cast<StructType>(ShadowTy);
770     SmallVector<Constant *, 4> Vals;
771     for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
772       Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
773     return ConstantStruct::get(ST, Vals);
774   }
775
776   /// \brief Create a dirty shadow for a given value.
777   Constant *getPoisonedShadow(Value *V) {
778     Type *ShadowTy = getShadowTy(V);
779     if (!ShadowTy)
780       return 0;
781     return getPoisonedShadow(ShadowTy);
782   }
783
784   /// \brief Create a clean (zero) origin.
785   Value *getCleanOrigin() {
786     return Constant::getNullValue(MS.OriginTy);
787   }
788
789   /// \brief Get the shadow value for a given Value.
790   ///
791   /// This function either returns the value set earlier with setShadow,
792   /// or extracts if from ParamTLS (for function arguments).
793   Value *getShadow(Value *V) {
794     if (Instruction *I = dyn_cast<Instruction>(V)) {
795       // For instructions the shadow is already stored in the map.
796       Value *Shadow = ShadowMap[V];
797       if (!Shadow) {
798         DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
799         (void)I;
800         assert(Shadow && "No shadow for a value");
801       }
802       return Shadow;
803     }
804     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
805       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
806       DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
807       (void)U;
808       return AllOnes;
809     }
810     if (Argument *A = dyn_cast<Argument>(V)) {
811       // For arguments we compute the shadow on demand and store it in the map.
812       Value **ShadowPtr = &ShadowMap[V];
813       if (*ShadowPtr)
814         return *ShadowPtr;
815       Function *F = A->getParent();
816       IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
817       unsigned ArgOffset = 0;
818       for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
819            AI != AE; ++AI) {
820         if (!AI->getType()->isSized()) {
821           DEBUG(dbgs() << "Arg is not sized\n");
822           continue;
823         }
824         unsigned Size = AI->hasByValAttr()
825           ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
826           : MS.TD->getTypeAllocSize(AI->getType());
827         if (A == AI) {
828           Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
829           if (AI->hasByValAttr()) {
830             // ByVal pointer itself has clean shadow. We copy the actual
831             // argument shadow to the underlying memory.
832             // Figure out maximal valid memcpy alignment.
833             unsigned ArgAlign = AI->getParamAlignment();
834             if (ArgAlign == 0) {
835               Type *EltType = A->getType()->getPointerElementType();
836               ArgAlign = MS.TD->getABITypeAlignment(EltType);
837             }
838             unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
839             Value *Cpy = EntryIRB.CreateMemCpy(
840                 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
841                 CopyAlign);
842             DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
843             (void)Cpy;
844             *ShadowPtr = getCleanShadow(V);
845           } else {
846             *ShadowPtr = EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
847           }
848           DEBUG(dbgs() << "  ARG:    "  << *AI << " ==> " <<
849                 **ShadowPtr << "\n");
850           if (MS.TrackOrigins) {
851             Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
852             setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
853           }
854         }
855         ArgOffset += DataLayout::RoundUpAlignment(Size, kShadowTLSAlignment);
856       }
857       assert(*ShadowPtr && "Could not find shadow for an argument");
858       return *ShadowPtr;
859     }
860     // For everything else the shadow is zero.
861     return getCleanShadow(V);
862   }
863
864   /// \brief Get the shadow for i-th argument of the instruction I.
865   Value *getShadow(Instruction *I, int i) {
866     return getShadow(I->getOperand(i));
867   }
868
869   /// \brief Get the origin for a value.
870   Value *getOrigin(Value *V) {
871     if (!MS.TrackOrigins) return 0;
872     if (isa<Instruction>(V) || isa<Argument>(V)) {
873       Value *Origin = OriginMap[V];
874       if (!Origin) {
875         DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
876         Origin = getCleanOrigin();
877       }
878       return Origin;
879     }
880     return getCleanOrigin();
881   }
882
883   /// \brief Get the origin for i-th argument of the instruction I.
884   Value *getOrigin(Instruction *I, int i) {
885     return getOrigin(I->getOperand(i));
886   }
887
888   /// \brief Remember the place where a shadow check should be inserted.
889   ///
890   /// This location will be later instrumented with a check that will print a
891   /// UMR warning in runtime if the value is not fully defined.
892   void insertCheck(Value *Val, Instruction *OrigIns) {
893     assert(Val);
894     if (!InsertChecks) return;
895     Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
896     if (!Shadow) return;
897 #ifndef NDEBUG
898     Type *ShadowTy = Shadow->getType();
899     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
900            "Can only insert checks for integer and vector shadow types");
901 #endif
902     Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
903     InstrumentationList.push_back(
904       ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
905   }
906
907   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
908     switch (a) {
909       case NotAtomic:
910         return NotAtomic;
911       case Unordered:
912       case Monotonic:
913       case Release:
914         return Release;
915       case Acquire:
916       case AcquireRelease:
917         return AcquireRelease;
918       case SequentiallyConsistent:
919         return SequentiallyConsistent;
920     }
921   }
922
923   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
924     switch (a) {
925       case NotAtomic:
926         return NotAtomic;
927       case Unordered:
928       case Monotonic:
929       case Acquire:
930         return Acquire;
931       case Release:
932       case AcquireRelease:
933         return AcquireRelease;
934       case SequentiallyConsistent:
935         return SequentiallyConsistent;
936     }
937   }
938
939   // ------------------- Visitors.
940
941   /// \brief Instrument LoadInst
942   ///
943   /// Loads the corresponding shadow and (optionally) origin.
944   /// Optionally, checks that the load address is fully defined.
945   void visitLoadInst(LoadInst &I) {
946     assert(I.getType()->isSized() && "Load type must have size");
947     IRBuilder<> IRB(I.getNextNode());
948     Type *ShadowTy = getShadowTy(&I);
949     Value *Addr = I.getPointerOperand();
950     if (LoadShadow) {
951       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
952       setShadow(&I,
953                 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
954     } else {
955       setShadow(&I, getCleanShadow(&I));
956     }
957
958     if (ClCheckAccessAddress)
959       insertCheck(I.getPointerOperand(), &I);
960
961     if (I.isAtomic())
962       I.setOrdering(addAcquireOrdering(I.getOrdering()));
963
964     if (MS.TrackOrigins) {
965       if (LoadShadow) {
966         unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
967         setOrigin(&I,
968                   IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
969       } else {
970         setOrigin(&I, getCleanOrigin());
971       }
972     }
973   }
974
975   /// \brief Instrument StoreInst
976   ///
977   /// Stores the corresponding shadow and (optionally) origin.
978   /// Optionally, checks that the store address is fully defined.
979   void visitStoreInst(StoreInst &I) {
980     StoreList.push_back(&I);
981   }
982
983   void handleCASOrRMW(Instruction &I) {
984     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
985
986     IRBuilder<> IRB(&I);
987     Value *Addr = I.getOperand(0);
988     Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
989
990     if (ClCheckAccessAddress)
991       insertCheck(Addr, &I);
992
993     // Only test the conditional argument of cmpxchg instruction.
994     // The other argument can potentially be uninitialized, but we can not
995     // detect this situation reliably without possible false positives.
996     if (isa<AtomicCmpXchgInst>(I))
997       insertCheck(I.getOperand(1), &I);
998
999     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1000
1001     setShadow(&I, getCleanShadow(&I));
1002   }
1003
1004   void visitAtomicRMWInst(AtomicRMWInst &I) {
1005     handleCASOrRMW(I);
1006     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1007   }
1008
1009   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1010     handleCASOrRMW(I);
1011     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1012   }
1013
1014   // Vector manipulation.
1015   void visitExtractElementInst(ExtractElementInst &I) {
1016     insertCheck(I.getOperand(1), &I);
1017     IRBuilder<> IRB(&I);
1018     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1019               "_msprop"));
1020     setOrigin(&I, getOrigin(&I, 0));
1021   }
1022
1023   void visitInsertElementInst(InsertElementInst &I) {
1024     insertCheck(I.getOperand(2), &I);
1025     IRBuilder<> IRB(&I);
1026     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1027               I.getOperand(2), "_msprop"));
1028     setOriginForNaryOp(I);
1029   }
1030
1031   void visitShuffleVectorInst(ShuffleVectorInst &I) {
1032     insertCheck(I.getOperand(2), &I);
1033     IRBuilder<> IRB(&I);
1034     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1035               I.getOperand(2), "_msprop"));
1036     setOriginForNaryOp(I);
1037   }
1038
1039   // Casts.
1040   void visitSExtInst(SExtInst &I) {
1041     IRBuilder<> IRB(&I);
1042     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1043     setOrigin(&I, getOrigin(&I, 0));
1044   }
1045
1046   void visitZExtInst(ZExtInst &I) {
1047     IRBuilder<> IRB(&I);
1048     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1049     setOrigin(&I, getOrigin(&I, 0));
1050   }
1051
1052   void visitTruncInst(TruncInst &I) {
1053     IRBuilder<> IRB(&I);
1054     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1055     setOrigin(&I, getOrigin(&I, 0));
1056   }
1057
1058   void visitBitCastInst(BitCastInst &I) {
1059     IRBuilder<> IRB(&I);
1060     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1061     setOrigin(&I, getOrigin(&I, 0));
1062   }
1063
1064   void visitPtrToIntInst(PtrToIntInst &I) {
1065     IRBuilder<> IRB(&I);
1066     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1067              "_msprop_ptrtoint"));
1068     setOrigin(&I, getOrigin(&I, 0));
1069   }
1070
1071   void visitIntToPtrInst(IntToPtrInst &I) {
1072     IRBuilder<> IRB(&I);
1073     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1074              "_msprop_inttoptr"));
1075     setOrigin(&I, getOrigin(&I, 0));
1076   }
1077
1078   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1079   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1080   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1081   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1082   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1083   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1084
1085   /// \brief Propagate shadow for bitwise AND.
1086   ///
1087   /// This code is exact, i.e. if, for example, a bit in the left argument
1088   /// is defined and 0, then neither the value not definedness of the
1089   /// corresponding bit in B don't affect the resulting shadow.
1090   void visitAnd(BinaryOperator &I) {
1091     IRBuilder<> IRB(&I);
1092     //  "And" of 0 and a poisoned value results in unpoisoned value.
1093     //  1&1 => 1;     0&1 => 0;     p&1 => p;
1094     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
1095     //  1&p => p;     0&p => 0;     p&p => p;
1096     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1097     Value *S1 = getShadow(&I, 0);
1098     Value *S2 = getShadow(&I, 1);
1099     Value *V1 = I.getOperand(0);
1100     Value *V2 = I.getOperand(1);
1101     if (V1->getType() != S1->getType()) {
1102       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1103       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1104     }
1105     Value *S1S2 = IRB.CreateAnd(S1, S2);
1106     Value *V1S2 = IRB.CreateAnd(V1, S2);
1107     Value *S1V2 = IRB.CreateAnd(S1, V2);
1108     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1109     setOriginForNaryOp(I);
1110   }
1111
1112   void visitOr(BinaryOperator &I) {
1113     IRBuilder<> IRB(&I);
1114     //  "Or" of 1 and a poisoned value results in unpoisoned value.
1115     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
1116     //  1|0 => 1;     0|0 => 0;     p|0 => p;
1117     //  1|p => 1;     0|p => p;     p|p => p;
1118     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1119     Value *S1 = getShadow(&I, 0);
1120     Value *S2 = getShadow(&I, 1);
1121     Value *V1 = IRB.CreateNot(I.getOperand(0));
1122     Value *V2 = IRB.CreateNot(I.getOperand(1));
1123     if (V1->getType() != S1->getType()) {
1124       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1125       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1126     }
1127     Value *S1S2 = IRB.CreateAnd(S1, S2);
1128     Value *V1S2 = IRB.CreateAnd(V1, S2);
1129     Value *S1V2 = IRB.CreateAnd(S1, V2);
1130     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1131     setOriginForNaryOp(I);
1132   }
1133
1134   /// \brief Default propagation of shadow and/or origin.
1135   ///
1136   /// This class implements the general case of shadow propagation, used in all
1137   /// cases where we don't know and/or don't care about what the operation
1138   /// actually does. It converts all input shadow values to a common type
1139   /// (extending or truncating as necessary), and bitwise OR's them.
1140   ///
1141   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1142   /// fully initialized), and less prone to false positives.
1143   ///
1144   /// This class also implements the general case of origin propagation. For a
1145   /// Nary operation, result origin is set to the origin of an argument that is
1146   /// not entirely initialized. If there is more than one such arguments, the
1147   /// rightmost of them is picked. It does not matter which one is picked if all
1148   /// arguments are initialized.
1149   template <bool CombineShadow>
1150   class Combiner {
1151     Value *Shadow;
1152     Value *Origin;
1153     IRBuilder<> &IRB;
1154     MemorySanitizerVisitor *MSV;
1155
1156   public:
1157     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1158       Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
1159
1160     /// \brief Add a pair of shadow and origin values to the mix.
1161     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1162       if (CombineShadow) {
1163         assert(OpShadow);
1164         if (!Shadow)
1165           Shadow = OpShadow;
1166         else {
1167           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1168           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1169         }
1170       }
1171
1172       if (MSV->MS.TrackOrigins) {
1173         assert(OpOrigin);
1174         if (!Origin) {
1175           Origin = OpOrigin;
1176         } else {
1177           Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1178           Value *Cond = IRB.CreateICmpNE(FlatShadow,
1179                                          MSV->getCleanShadow(FlatShadow));
1180           Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1181         }
1182       }
1183       return *this;
1184     }
1185
1186     /// \brief Add an application value to the mix.
1187     Combiner &Add(Value *V) {
1188       Value *OpShadow = MSV->getShadow(V);
1189       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
1190       return Add(OpShadow, OpOrigin);
1191     }
1192
1193     /// \brief Set the current combined values as the given instruction's shadow
1194     /// and origin.
1195     void Done(Instruction *I) {
1196       if (CombineShadow) {
1197         assert(Shadow);
1198         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1199         MSV->setShadow(I, Shadow);
1200       }
1201       if (MSV->MS.TrackOrigins) {
1202         assert(Origin);
1203         MSV->setOrigin(I, Origin);
1204       }
1205     }
1206   };
1207
1208   typedef Combiner<true> ShadowAndOriginCombiner;
1209   typedef Combiner<false> OriginCombiner;
1210
1211   /// \brief Propagate origin for arbitrary operation.
1212   void setOriginForNaryOp(Instruction &I) {
1213     if (!MS.TrackOrigins) return;
1214     IRBuilder<> IRB(&I);
1215     OriginCombiner OC(this, IRB);
1216     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1217       OC.Add(OI->get());
1218     OC.Done(&I);
1219   }
1220
1221   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1222     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1223            "Vector of pointers is not a valid shadow type");
1224     return Ty->isVectorTy() ?
1225       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1226       Ty->getPrimitiveSizeInBits();
1227   }
1228
1229   /// \brief Cast between two shadow types, extending or truncating as
1230   /// necessary.
1231   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1232     Type *srcTy = V->getType();
1233     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1234       return IRB.CreateIntCast(V, dstTy, false);
1235     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1236         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1237       return IRB.CreateIntCast(V, dstTy, false);
1238     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1239     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1240     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1241     Value *V2 =
1242       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1243     return IRB.CreateBitCast(V2, dstTy);
1244     // TODO: handle struct types.
1245   }
1246
1247   /// \brief Propagate shadow for arbitrary operation.
1248   void handleShadowOr(Instruction &I) {
1249     IRBuilder<> IRB(&I);
1250     ShadowAndOriginCombiner SC(this, IRB);
1251     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1252       SC.Add(OI->get());
1253     SC.Done(&I);
1254   }
1255
1256   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1257   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1258   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1259   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1260   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1261   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1262   void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1263
1264   void handleDiv(Instruction &I) {
1265     IRBuilder<> IRB(&I);
1266     // Strict on the second argument.
1267     insertCheck(I.getOperand(1), &I);
1268     setShadow(&I, getShadow(&I, 0));
1269     setOrigin(&I, getOrigin(&I, 0));
1270   }
1271
1272   void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1273   void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1274   void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1275   void visitURem(BinaryOperator &I) { handleDiv(I); }
1276   void visitSRem(BinaryOperator &I) { handleDiv(I); }
1277   void visitFRem(BinaryOperator &I) { handleDiv(I); }
1278
1279   /// \brief Instrument == and != comparisons.
1280   ///
1281   /// Sometimes the comparison result is known even if some of the bits of the
1282   /// arguments are not.
1283   void handleEqualityComparison(ICmpInst &I) {
1284     IRBuilder<> IRB(&I);
1285     Value *A = I.getOperand(0);
1286     Value *B = I.getOperand(1);
1287     Value *Sa = getShadow(A);
1288     Value *Sb = getShadow(B);
1289
1290     // Get rid of pointers and vectors of pointers.
1291     // For ints (and vectors of ints), types of A and Sa match,
1292     // and this is a no-op.
1293     A = IRB.CreatePointerCast(A, Sa->getType());
1294     B = IRB.CreatePointerCast(B, Sb->getType());
1295
1296     // A == B  <==>  (C = A^B) == 0
1297     // A != B  <==>  (C = A^B) != 0
1298     // Sc = Sa | Sb
1299     Value *C = IRB.CreateXor(A, B);
1300     Value *Sc = IRB.CreateOr(Sa, Sb);
1301     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1302     // Result is defined if one of the following is true
1303     // * there is a defined 1 bit in C
1304     // * C is fully defined
1305     // Si = !(C & ~Sc) && Sc
1306     Value *Zero = Constant::getNullValue(Sc->getType());
1307     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1308     Value *Si =
1309       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1310                     IRB.CreateICmpEQ(
1311                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1312     Si->setName("_msprop_icmp");
1313     setShadow(&I, Si);
1314     setOriginForNaryOp(I);
1315   }
1316
1317   /// \brief Build the lowest possible value of V, taking into account V's
1318   ///        uninitialized bits.
1319   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1320                                 bool isSigned) {
1321     if (isSigned) {
1322       // Split shadow into sign bit and other bits.
1323       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1324       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1325       // Maximise the undefined shadow bit, minimize other undefined bits.
1326       return
1327         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1328     } else {
1329       // Minimize undefined bits.
1330       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1331     }
1332   }
1333
1334   /// \brief Build the highest possible value of V, taking into account V's
1335   ///        uninitialized bits.
1336   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1337                                 bool isSigned) {
1338     if (isSigned) {
1339       // Split shadow into sign bit and other bits.
1340       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1341       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1342       // Minimise the undefined shadow bit, maximise other undefined bits.
1343       return
1344         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1345     } else {
1346       // Maximize undefined bits.
1347       return IRB.CreateOr(A, Sa);
1348     }
1349   }
1350
1351   /// \brief Instrument relational comparisons.
1352   ///
1353   /// This function does exact shadow propagation for all relational
1354   /// comparisons of integers, pointers and vectors of those.
1355   /// FIXME: output seems suboptimal when one of the operands is a constant
1356   void handleRelationalComparisonExact(ICmpInst &I) {
1357     IRBuilder<> IRB(&I);
1358     Value *A = I.getOperand(0);
1359     Value *B = I.getOperand(1);
1360     Value *Sa = getShadow(A);
1361     Value *Sb = getShadow(B);
1362
1363     // Get rid of pointers and vectors of pointers.
1364     // For ints (and vectors of ints), types of A and Sa match,
1365     // and this is a no-op.
1366     A = IRB.CreatePointerCast(A, Sa->getType());
1367     B = IRB.CreatePointerCast(B, Sb->getType());
1368
1369     // Let [a0, a1] be the interval of possible values of A, taking into account
1370     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1371     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1372     bool IsSigned = I.isSigned();
1373     Value *S1 = IRB.CreateICmp(I.getPredicate(),
1374                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
1375                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
1376     Value *S2 = IRB.CreateICmp(I.getPredicate(),
1377                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
1378                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
1379     Value *Si = IRB.CreateXor(S1, S2);
1380     setShadow(&I, Si);
1381     setOriginForNaryOp(I);
1382   }
1383
1384   /// \brief Instrument signed relational comparisons.
1385   ///
1386   /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1387   /// propagating the highest bit of the shadow. Everything else is delegated
1388   /// to handleShadowOr().
1389   void handleSignedRelationalComparison(ICmpInst &I) {
1390     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1391     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1392     Value* op = NULL;
1393     CmpInst::Predicate pre = I.getPredicate();
1394     if (constOp0 && constOp0->isNullValue() &&
1395         (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1396       op = I.getOperand(1);
1397     } else if (constOp1 && constOp1->isNullValue() &&
1398                (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1399       op = I.getOperand(0);
1400     }
1401     if (op) {
1402       IRBuilder<> IRB(&I);
1403       Value* Shadow =
1404         IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1405       setShadow(&I, Shadow);
1406       setOrigin(&I, getOrigin(op));
1407     } else {
1408       handleShadowOr(I);
1409     }
1410   }
1411
1412   void visitICmpInst(ICmpInst &I) {
1413     if (!ClHandleICmp) {
1414       handleShadowOr(I);
1415       return;
1416     }
1417     if (I.isEquality()) {
1418       handleEqualityComparison(I);
1419       return;
1420     }
1421
1422     assert(I.isRelational());
1423     if (ClHandleICmpExact) {
1424       handleRelationalComparisonExact(I);
1425       return;
1426     }
1427     if (I.isSigned()) {
1428       handleSignedRelationalComparison(I);
1429       return;
1430     }
1431
1432     assert(I.isUnsigned());
1433     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1434       handleRelationalComparisonExact(I);
1435       return;
1436     }
1437
1438     handleShadowOr(I);
1439   }
1440
1441   void visitFCmpInst(FCmpInst &I) {
1442     handleShadowOr(I);
1443   }
1444
1445   void handleShift(BinaryOperator &I) {
1446     IRBuilder<> IRB(&I);
1447     // If any of the S2 bits are poisoned, the whole thing is poisoned.
1448     // Otherwise perform the same shift on S1.
1449     Value *S1 = getShadow(&I, 0);
1450     Value *S2 = getShadow(&I, 1);
1451     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1452                                    S2->getType());
1453     Value *V2 = I.getOperand(1);
1454     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1455     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1456     setOriginForNaryOp(I);
1457   }
1458
1459   void visitShl(BinaryOperator &I) { handleShift(I); }
1460   void visitAShr(BinaryOperator &I) { handleShift(I); }
1461   void visitLShr(BinaryOperator &I) { handleShift(I); }
1462
1463   /// \brief Instrument llvm.memmove
1464   ///
1465   /// At this point we don't know if llvm.memmove will be inlined or not.
1466   /// If we don't instrument it and it gets inlined,
1467   /// our interceptor will not kick in and we will lose the memmove.
1468   /// If we instrument the call here, but it does not get inlined,
1469   /// we will memove the shadow twice: which is bad in case
1470   /// of overlapping regions. So, we simply lower the intrinsic to a call.
1471   ///
1472   /// Similar situation exists for memcpy and memset.
1473   void visitMemMoveInst(MemMoveInst &I) {
1474     IRBuilder<> IRB(&I);
1475     IRB.CreateCall3(
1476       MS.MemmoveFn,
1477       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1478       IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1479       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1480     I.eraseFromParent();
1481   }
1482
1483   // Similar to memmove: avoid copying shadow twice.
1484   // This is somewhat unfortunate as it may slowdown small constant memcpys.
1485   // FIXME: consider doing manual inline for small constant sizes and proper
1486   // alignment.
1487   void visitMemCpyInst(MemCpyInst &I) {
1488     IRBuilder<> IRB(&I);
1489     IRB.CreateCall3(
1490       MS.MemcpyFn,
1491       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1492       IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1493       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1494     I.eraseFromParent();
1495   }
1496
1497   // Same as memcpy.
1498   void visitMemSetInst(MemSetInst &I) {
1499     IRBuilder<> IRB(&I);
1500     IRB.CreateCall3(
1501       MS.MemsetFn,
1502       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1503       IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1504       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1505     I.eraseFromParent();
1506   }
1507
1508   void visitVAStartInst(VAStartInst &I) {
1509     VAHelper->visitVAStartInst(I);
1510   }
1511
1512   void visitVACopyInst(VACopyInst &I) {
1513     VAHelper->visitVACopyInst(I);
1514   }
1515
1516   enum IntrinsicKind {
1517     IK_DoesNotAccessMemory,
1518     IK_OnlyReadsMemory,
1519     IK_WritesMemory
1520   };
1521
1522   static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1523     const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1524     const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1525     const int OnlyReadsMemory = IK_OnlyReadsMemory;
1526     const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1527     const int UnknownModRefBehavior = IK_WritesMemory;
1528 #define GET_INTRINSIC_MODREF_BEHAVIOR
1529 #define ModRefBehavior IntrinsicKind
1530 #include "llvm/IR/Intrinsics.gen"
1531 #undef ModRefBehavior
1532 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1533   }
1534
1535   /// \brief Handle vector store-like intrinsics.
1536   ///
1537   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1538   /// has 1 pointer argument and 1 vector argument, returns void.
1539   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1540     IRBuilder<> IRB(&I);
1541     Value* Addr = I.getArgOperand(0);
1542     Value *Shadow = getShadow(&I, 1);
1543     Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1544
1545     // We don't know the pointer alignment (could be unaligned SSE store!).
1546     // Have to assume to worst case.
1547     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1548
1549     if (ClCheckAccessAddress)
1550       insertCheck(Addr, &I);
1551
1552     // FIXME: use ClStoreCleanOrigin
1553     // FIXME: factor out common code from materializeStores
1554     if (MS.TrackOrigins)
1555       IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1556     return true;
1557   }
1558
1559   /// \brief Handle vector load-like intrinsics.
1560   ///
1561   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1562   /// has 1 pointer argument, returns a vector.
1563   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1564     IRBuilder<> IRB(&I);
1565     Value *Addr = I.getArgOperand(0);
1566
1567     Type *ShadowTy = getShadowTy(&I);
1568     if (LoadShadow) {
1569       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1570       // We don't know the pointer alignment (could be unaligned SSE load!).
1571       // Have to assume to worst case.
1572       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1573     } else {
1574       setShadow(&I, getCleanShadow(&I));
1575     }
1576
1577
1578     if (ClCheckAccessAddress)
1579       insertCheck(Addr, &I);
1580
1581     if (MS.TrackOrigins) {
1582       if (LoadShadow)
1583         setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1584       else
1585         setOrigin(&I, getCleanOrigin());
1586     }
1587     return true;
1588   }
1589
1590   /// \brief Handle (SIMD arithmetic)-like intrinsics.
1591   ///
1592   /// Instrument intrinsics with any number of arguments of the same type,
1593   /// equal to the return type. The type should be simple (no aggregates or
1594   /// pointers; vectors are fine).
1595   /// Caller guarantees that this intrinsic does not access memory.
1596   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1597     Type *RetTy = I.getType();
1598     if (!(RetTy->isIntOrIntVectorTy() ||
1599           RetTy->isFPOrFPVectorTy() ||
1600           RetTy->isX86_MMXTy()))
1601       return false;
1602
1603     unsigned NumArgOperands = I.getNumArgOperands();
1604
1605     for (unsigned i = 0; i < NumArgOperands; ++i) {
1606       Type *Ty = I.getArgOperand(i)->getType();
1607       if (Ty != RetTy)
1608         return false;
1609     }
1610
1611     IRBuilder<> IRB(&I);
1612     ShadowAndOriginCombiner SC(this, IRB);
1613     for (unsigned i = 0; i < NumArgOperands; ++i)
1614       SC.Add(I.getArgOperand(i));
1615     SC.Done(&I);
1616
1617     return true;
1618   }
1619
1620   /// \brief Heuristically instrument unknown intrinsics.
1621   ///
1622   /// The main purpose of this code is to do something reasonable with all
1623   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1624   /// We recognize several classes of intrinsics by their argument types and
1625   /// ModRefBehaviour and apply special intrumentation when we are reasonably
1626   /// sure that we know what the intrinsic does.
1627   ///
1628   /// We special-case intrinsics where this approach fails. See llvm.bswap
1629   /// handling as an example of that.
1630   bool handleUnknownIntrinsic(IntrinsicInst &I) {
1631     unsigned NumArgOperands = I.getNumArgOperands();
1632     if (NumArgOperands == 0)
1633       return false;
1634
1635     Intrinsic::ID iid = I.getIntrinsicID();
1636     IntrinsicKind IK = getIntrinsicKind(iid);
1637     bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1638     bool WritesMemory = IK == IK_WritesMemory;
1639     assert(!(OnlyReadsMemory && WritesMemory));
1640
1641     if (NumArgOperands == 2 &&
1642         I.getArgOperand(0)->getType()->isPointerTy() &&
1643         I.getArgOperand(1)->getType()->isVectorTy() &&
1644         I.getType()->isVoidTy() &&
1645         WritesMemory) {
1646       // This looks like a vector store.
1647       return handleVectorStoreIntrinsic(I);
1648     }
1649
1650     if (NumArgOperands == 1 &&
1651         I.getArgOperand(0)->getType()->isPointerTy() &&
1652         I.getType()->isVectorTy() &&
1653         OnlyReadsMemory) {
1654       // This looks like a vector load.
1655       return handleVectorLoadIntrinsic(I);
1656     }
1657
1658     if (!OnlyReadsMemory && !WritesMemory)
1659       if (maybeHandleSimpleNomemIntrinsic(I))
1660         return true;
1661
1662     // FIXME: detect and handle SSE maskstore/maskload
1663     return false;
1664   }
1665
1666   void handleBswap(IntrinsicInst &I) {
1667     IRBuilder<> IRB(&I);
1668     Value *Op = I.getArgOperand(0);
1669     Type *OpType = Op->getType();
1670     Function *BswapFunc = Intrinsic::getDeclaration(
1671       F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1672     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1673     setOrigin(&I, getOrigin(Op));
1674   }
1675
1676   void visitIntrinsicInst(IntrinsicInst &I) {
1677     switch (I.getIntrinsicID()) {
1678     case llvm::Intrinsic::bswap:
1679       handleBswap(I);
1680       break;
1681     default:
1682       if (!handleUnknownIntrinsic(I))
1683         visitInstruction(I);
1684       break;
1685     }
1686   }
1687
1688   // Replace call to (*Fn) with a call to (*IndirectCallWrapperFn(Fn)).
1689   void wrapIndirectCall(IRBuilder<> &IRB, CallSite CS) {
1690     Value *Fn = CS.getCalledValue();
1691     Value *NewFn = IRB.CreateBitCast(
1692         IRB.CreateCall(MS.IndirectCallWrapperFn,
1693                        IRB.CreateBitCast(Fn, MS.AnyFunctionPtrTy)),
1694         Fn->getType());
1695     setShadow(NewFn, getShadow(Fn));
1696     CS.setCalledFunction(NewFn);
1697   }
1698
1699   void visitCallSite(CallSite CS) {
1700     Instruction &I = *CS.getInstruction();
1701     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1702     if (CS.isCall()) {
1703       CallInst *Call = cast<CallInst>(&I);
1704
1705       // For inline asm, do the usual thing: check argument shadow and mark all
1706       // outputs as clean. Note that any side effects of the inline asm that are
1707       // not immediately visible in its constraints are not handled.
1708       if (Call->isInlineAsm()) {
1709         visitInstruction(I);
1710         return;
1711       }
1712
1713       // Allow only tail calls with the same types, otherwise
1714       // we may have a false positive: shadow for a non-void RetVal
1715       // will get propagated to a void RetVal.
1716       if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1717         Call->setTailCall(false);
1718
1719       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1720
1721       // We are going to insert code that relies on the fact that the callee
1722       // will become a non-readonly function after it is instrumented by us. To
1723       // prevent this code from being optimized out, mark that function
1724       // non-readonly in advance.
1725       if (Function *Func = Call->getCalledFunction()) {
1726         // Clear out readonly/readnone attributes.
1727         AttrBuilder B;
1728         B.addAttribute(Attribute::ReadOnly)
1729           .addAttribute(Attribute::ReadNone);
1730         Func->removeAttributes(AttributeSet::FunctionIndex,
1731                                AttributeSet::get(Func->getContext(),
1732                                                  AttributeSet::FunctionIndex,
1733                                                  B));
1734       }
1735     }
1736     IRBuilder<> IRB(&I);
1737
1738     if (MS.WrapIndirectCalls && !CS.getCalledFunction())
1739       wrapIndirectCall(IRB, CS);
1740
1741     unsigned ArgOffset = 0;
1742     DEBUG(dbgs() << "  CallSite: " << I << "\n");
1743     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1744          ArgIt != End; ++ArgIt) {
1745       Value *A = *ArgIt;
1746       unsigned i = ArgIt - CS.arg_begin();
1747       if (!A->getType()->isSized()) {
1748         DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1749         continue;
1750       }
1751       unsigned Size = 0;
1752       Value *Store = 0;
1753       // Compute the Shadow for arg even if it is ByVal, because
1754       // in that case getShadow() will copy the actual arg shadow to
1755       // __msan_param_tls.
1756       Value *ArgShadow = getShadow(A);
1757       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1758       DEBUG(dbgs() << "  Arg#" << i << ": " << *A <<
1759             " Shadow: " << *ArgShadow << "\n");
1760       if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
1761         assert(A->getType()->isPointerTy() &&
1762                "ByVal argument is not a pointer!");
1763         Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1764         unsigned Alignment = CS.getParamAlignment(i + 1);
1765         Store = IRB.CreateMemCpy(ArgShadowBase,
1766                                  getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1767                                  Size, Alignment);
1768       } else {
1769         Size = MS.TD->getTypeAllocSize(A->getType());
1770         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1771                                        kShadowTLSAlignment);
1772       }
1773       if (MS.TrackOrigins)
1774         IRB.CreateStore(getOrigin(A),
1775                         getOriginPtrForArgument(A, IRB, ArgOffset));
1776       (void)Store;
1777       assert(Size != 0 && Store != 0);
1778       DEBUG(dbgs() << "  Param:" << *Store << "\n");
1779       ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1780     }
1781     DEBUG(dbgs() << "  done with call args\n");
1782
1783     FunctionType *FT =
1784       cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
1785     if (FT->isVarArg()) {
1786       VAHelper->visitCallSite(CS, IRB);
1787     }
1788
1789     // Now, get the shadow for the RetVal.
1790     if (!I.getType()->isSized()) return;
1791     IRBuilder<> IRBBefore(&I);
1792     // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1793     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1794     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
1795     Instruction *NextInsn = 0;
1796     if (CS.isCall()) {
1797       NextInsn = I.getNextNode();
1798     } else {
1799       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1800       if (!NormalDest->getSinglePredecessor()) {
1801         // FIXME: this case is tricky, so we are just conservative here.
1802         // Perhaps we need to split the edge between this BB and NormalDest,
1803         // but a naive attempt to use SplitEdge leads to a crash.
1804         setShadow(&I, getCleanShadow(&I));
1805         setOrigin(&I, getCleanOrigin());
1806         return;
1807       }
1808       NextInsn = NormalDest->getFirstInsertionPt();
1809       assert(NextInsn &&
1810              "Could not find insertion point for retval shadow load");
1811     }
1812     IRBuilder<> IRBAfter(NextInsn);
1813     Value *RetvalShadow =
1814       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1815                                  kShadowTLSAlignment, "_msret");
1816     setShadow(&I, RetvalShadow);
1817     if (MS.TrackOrigins)
1818       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1819   }
1820
1821   void visitReturnInst(ReturnInst &I) {
1822     IRBuilder<> IRB(&I);
1823     Value *RetVal = I.getReturnValue();
1824     if (!RetVal) return;
1825     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1826     if (CheckReturnValue) {
1827       insertCheck(RetVal, &I);
1828       Value *Shadow = getCleanShadow(RetVal);
1829       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1830     } else {
1831       Value *Shadow = getShadow(RetVal);
1832       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1833       // FIXME: make it conditional if ClStoreCleanOrigin==0
1834       if (MS.TrackOrigins)
1835         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1836     }
1837   }
1838
1839   void visitPHINode(PHINode &I) {
1840     IRBuilder<> IRB(&I);
1841     ShadowPHINodes.push_back(&I);
1842     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1843                                 "_msphi_s"));
1844     if (MS.TrackOrigins)
1845       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1846                                   "_msphi_o"));
1847   }
1848
1849   void visitAllocaInst(AllocaInst &I) {
1850     setShadow(&I, getCleanShadow(&I));
1851     IRBuilder<> IRB(I.getNextNode());
1852     uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1853     if (PoisonStack && ClPoisonStackWithCall) {
1854       IRB.CreateCall2(MS.MsanPoisonStackFn,
1855                       IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1856                       ConstantInt::get(MS.IntptrTy, Size));
1857     } else {
1858       Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1859       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
1860       IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
1861     }
1862
1863     if (PoisonStack && MS.TrackOrigins) {
1864       setOrigin(&I, getCleanOrigin());
1865       SmallString<2048> StackDescriptionStorage;
1866       raw_svector_ostream StackDescription(StackDescriptionStorage);
1867       // We create a string with a description of the stack allocation and
1868       // pass it into __msan_set_alloca_origin.
1869       // It will be printed by the run-time if stack-originated UMR is found.
1870       // The first 4 bytes of the string are set to '----' and will be replaced
1871       // by __msan_va_arg_overflow_size_tls at the first call.
1872       StackDescription << "----" << I.getName() << "@" << F.getName();
1873       Value *Descr =
1874           createPrivateNonConstGlobalForString(*F.getParent(),
1875                                                StackDescription.str());
1876
1877       IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
1878                       IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1879                       ConstantInt::get(MS.IntptrTy, Size),
1880                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
1881                       IRB.CreatePointerCast(&F, MS.IntptrTy));
1882     }
1883   }
1884
1885   void visitSelectInst(SelectInst& I) {
1886     IRBuilder<> IRB(&I);
1887     // a = select b, c, d
1888     Value *S = IRB.CreateSelect(I.getCondition(), getShadow(I.getTrueValue()),
1889                                 getShadow(I.getFalseValue()));
1890     if (I.getType()->isAggregateType()) {
1891       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
1892       // an extra "select". This results in much more compact IR.
1893       // Sa = select Sb, poisoned, (select b, Sc, Sd)
1894       S = IRB.CreateSelect(getShadow(I.getCondition()),
1895                            getPoisonedShadow(getShadowTy(I.getType())), S,
1896                            "_msprop_select_agg");
1897     } else {
1898       // Sa = (sext Sb) | (select b, Sc, Sd)
1899       S = IRB.CreateOr(
1900           S, IRB.CreateSExt(getShadow(I.getCondition()), S->getType()),
1901           "_msprop_select");
1902     }
1903     setShadow(&I, S);
1904     if (MS.TrackOrigins) {
1905       // Origins are always i32, so any vector conditions must be flattened.
1906       // FIXME: consider tracking vector origins for app vectors?
1907       Value *Cond = I.getCondition();
1908       if (Cond->getType()->isVectorTy()) {
1909         Value *ConvertedShadow = convertToShadowTyNoVec(Cond, IRB);
1910         Cond = IRB.CreateICmpNE(ConvertedShadow,
1911                                 getCleanShadow(ConvertedShadow), "_mso_select");
1912       }
1913       setOrigin(&I, IRB.CreateSelect(Cond,
1914                 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1915     }
1916   }
1917
1918   void visitLandingPadInst(LandingPadInst &I) {
1919     // Do nothing.
1920     // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1921     setShadow(&I, getCleanShadow(&I));
1922     setOrigin(&I, getCleanOrigin());
1923   }
1924
1925   void visitGetElementPtrInst(GetElementPtrInst &I) {
1926     handleShadowOr(I);
1927   }
1928
1929   void visitExtractValueInst(ExtractValueInst &I) {
1930     IRBuilder<> IRB(&I);
1931     Value *Agg = I.getAggregateOperand();
1932     DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
1933     Value *AggShadow = getShadow(Agg);
1934     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
1935     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1936     DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
1937     setShadow(&I, ResShadow);
1938     setOrigin(&I, getCleanOrigin());
1939   }
1940
1941   void visitInsertValueInst(InsertValueInst &I) {
1942     IRBuilder<> IRB(&I);
1943     DEBUG(dbgs() << "InsertValue:  " << I << "\n");
1944     Value *AggShadow = getShadow(I.getAggregateOperand());
1945     Value *InsShadow = getShadow(I.getInsertedValueOperand());
1946     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
1947     DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
1948     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1949     DEBUG(dbgs() << "   Res:        " << *Res << "\n");
1950     setShadow(&I, Res);
1951     setOrigin(&I, getCleanOrigin());
1952   }
1953
1954   void dumpInst(Instruction &I) {
1955     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1956       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1957     } else {
1958       errs() << "ZZZ " << I.getOpcodeName() << "\n";
1959     }
1960     errs() << "QQQ " << I << "\n";
1961   }
1962
1963   void visitResumeInst(ResumeInst &I) {
1964     DEBUG(dbgs() << "Resume: " << I << "\n");
1965     // Nothing to do here.
1966   }
1967
1968   void visitInstruction(Instruction &I) {
1969     // Everything else: stop propagating and check for poisoned shadow.
1970     if (ClDumpStrictInstructions)
1971       dumpInst(I);
1972     DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1973     for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1974       insertCheck(I.getOperand(i), &I);
1975     setShadow(&I, getCleanShadow(&I));
1976     setOrigin(&I, getCleanOrigin());
1977   }
1978 };
1979
1980 /// \brief AMD64-specific implementation of VarArgHelper.
1981 struct VarArgAMD64Helper : public VarArgHelper {
1982   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1983   // See a comment in visitCallSite for more details.
1984   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
1985   static const unsigned AMD64FpEndOffset = 176;
1986
1987   Function &F;
1988   MemorySanitizer &MS;
1989   MemorySanitizerVisitor &MSV;
1990   Value *VAArgTLSCopy;
1991   Value *VAArgOverflowSize;
1992
1993   SmallVector<CallInst*, 16> VAStartInstrumentationList;
1994
1995   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1996                     MemorySanitizerVisitor &MSV)
1997     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1998
1999   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2000
2001   ArgKind classifyArgument(Value* arg) {
2002     // A very rough approximation of X86_64 argument classification rules.
2003     Type *T = arg->getType();
2004     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2005       return AK_FloatingPoint;
2006     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2007       return AK_GeneralPurpose;
2008     if (T->isPointerTy())
2009       return AK_GeneralPurpose;
2010     return AK_Memory;
2011   }
2012
2013   // For VarArg functions, store the argument shadow in an ABI-specific format
2014   // that corresponds to va_list layout.
2015   // We do this because Clang lowers va_arg in the frontend, and this pass
2016   // only sees the low level code that deals with va_list internals.
2017   // A much easier alternative (provided that Clang emits va_arg instructions)
2018   // would have been to associate each live instance of va_list with a copy of
2019   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2020   // order.
2021   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
2022     unsigned GpOffset = 0;
2023     unsigned FpOffset = AMD64GpEndOffset;
2024     unsigned OverflowOffset = AMD64FpEndOffset;
2025     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2026          ArgIt != End; ++ArgIt) {
2027       Value *A = *ArgIt;
2028       ArgKind AK = classifyArgument(A);
2029       if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2030         AK = AK_Memory;
2031       if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2032         AK = AK_Memory;
2033       Value *Base;
2034       switch (AK) {
2035       case AK_GeneralPurpose:
2036         Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
2037         GpOffset += 8;
2038         break;
2039       case AK_FloatingPoint:
2040         Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
2041         FpOffset += 16;
2042         break;
2043       case AK_Memory:
2044         uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
2045         Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
2046         OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
2047       }
2048       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2049     }
2050     Constant *OverflowSize =
2051       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2052     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2053   }
2054
2055   /// \brief Compute the shadow address for a given va_arg.
2056   Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
2057                                    int ArgOffset) {
2058     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2059     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2060     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
2061                               "_msarg");
2062   }
2063
2064   void visitVAStartInst(VAStartInst &I) {
2065     IRBuilder<> IRB(&I);
2066     VAStartInstrumentationList.push_back(&I);
2067     Value *VAListTag = I.getArgOperand(0);
2068     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2069
2070     // Unpoison the whole __va_list_tag.
2071     // FIXME: magic ABI constants.
2072     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2073                      /* size */24, /* alignment */8, false);
2074   }
2075
2076   void visitVACopyInst(VACopyInst &I) {
2077     IRBuilder<> IRB(&I);
2078     Value *VAListTag = I.getArgOperand(0);
2079     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2080
2081     // Unpoison the whole __va_list_tag.
2082     // FIXME: magic ABI constants.
2083     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2084                      /* size */24, /* alignment */8, false);
2085   }
2086
2087   void finalizeInstrumentation() {
2088     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2089            "finalizeInstrumentation called twice");
2090     if (!VAStartInstrumentationList.empty()) {
2091       // If there is a va_start in this function, make a backup copy of
2092       // va_arg_tls somewhere in the function entry block.
2093       IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2094       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2095       Value *CopySize =
2096         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2097                       VAArgOverflowSize);
2098       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2099       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2100     }
2101
2102     // Instrument va_start.
2103     // Copy va_list shadow from the backup copy of the TLS contents.
2104     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2105       CallInst *OrigInst = VAStartInstrumentationList[i];
2106       IRBuilder<> IRB(OrigInst->getNextNode());
2107       Value *VAListTag = OrigInst->getArgOperand(0);
2108
2109       Value *RegSaveAreaPtrPtr =
2110         IRB.CreateIntToPtr(
2111           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2112                         ConstantInt::get(MS.IntptrTy, 16)),
2113           Type::getInt64PtrTy(*MS.C));
2114       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2115       Value *RegSaveAreaShadowPtr =
2116         MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2117       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2118                        AMD64FpEndOffset, 16);
2119
2120       Value *OverflowArgAreaPtrPtr =
2121         IRB.CreateIntToPtr(
2122           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2123                         ConstantInt::get(MS.IntptrTy, 8)),
2124           Type::getInt64PtrTy(*MS.C));
2125       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2126       Value *OverflowArgAreaShadowPtr =
2127         MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2128       Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
2129       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2130     }
2131   }
2132 };
2133
2134 /// \brief A no-op implementation of VarArgHelper.
2135 struct VarArgNoOpHelper : public VarArgHelper {
2136   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2137                    MemorySanitizerVisitor &MSV) {}
2138
2139   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {}
2140
2141   void visitVAStartInst(VAStartInst &I) {}
2142
2143   void visitVACopyInst(VACopyInst &I) {}
2144
2145   void finalizeInstrumentation() {}
2146 };
2147
2148 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
2149                                  MemorySanitizerVisitor &Visitor) {
2150   // VarArg handling is only implemented on AMD64. False positives are possible
2151   // on other platforms.
2152   llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2153   if (TargetTriple.getArch() == llvm::Triple::x86_64)
2154     return new VarArgAMD64Helper(Func, Msan, Visitor);
2155   else
2156     return new VarArgNoOpHelper(Func, Msan, Visitor);
2157 }
2158
2159 }  // namespace
2160
2161 bool MemorySanitizer::runOnFunction(Function &F) {
2162   MemorySanitizerVisitor Visitor(F, *this);
2163
2164   // Clear out readonly/readnone attributes.
2165   AttrBuilder B;
2166   B.addAttribute(Attribute::ReadOnly)
2167     .addAttribute(Attribute::ReadNone);
2168   F.removeAttributes(AttributeSet::FunctionIndex,
2169                      AttributeSet::get(F.getContext(),
2170                                        AttributeSet::FunctionIndex, B));
2171
2172   return Visitor.runOnFunction();
2173 }