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