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