41e250b7e7316f368229f557660382de48b6bac7
[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       uint32_t EltSize = MS.TD->getTypeStoreSizeInBits(VT->getElementType());
546       return VectorType::get(IntegerType::get(*MS.C, EltSize),
547                              VT->getNumElements());
548     }
549     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
550       SmallVector<Type*, 4> Elements;
551       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
552         Elements.push_back(getShadowTy(ST->getElementType(i)));
553       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
554       DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
555       return Res;
556     }
557     uint32_t TypeSize = MS.TD->getTypeStoreSizeInBits(OrigTy);
558     return IntegerType::get(*MS.C, TypeSize);
559   }
560
561   /// \brief Flatten a vector type.
562   Type *getShadowTyNoVec(Type *ty) {
563     if (VectorType *vt = dyn_cast<VectorType>(ty))
564       return IntegerType::get(*MS.C, vt->getBitWidth());
565     return ty;
566   }
567
568   /// \brief Convert a shadow value to it's flattened variant.
569   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
570     Type *Ty = V->getType();
571     Type *NoVecTy = getShadowTyNoVec(Ty);
572     if (Ty == NoVecTy) return V;
573     return IRB.CreateBitCast(V, NoVecTy);
574   }
575
576   /// \brief Compute the shadow address that corresponds to a given application
577   /// address.
578   ///
579   /// Shadow = Addr & ~ShadowMask.
580   Value *getShadowPtr(Value *Addr, Type *ShadowTy,
581                       IRBuilder<> &IRB) {
582     Value *ShadowLong =
583       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
584                     ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
585     return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
586   }
587
588   /// \brief Compute the origin address that corresponds to a given application
589   /// address.
590   ///
591   /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
592   Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
593     Value *ShadowLong =
594       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
595                     ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
596     Value *Add =
597       IRB.CreateAdd(ShadowLong,
598                     ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
599     Value *SecondAnd =
600       IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
601     return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
602   }
603
604   /// \brief Compute the shadow address for a given function argument.
605   ///
606   /// Shadow = ParamTLS+ArgOffset.
607   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
608                                  int ArgOffset) {
609     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
610     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
611     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
612                               "_msarg");
613   }
614
615   /// \brief Compute the origin address for a given function argument.
616   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
617                                  int ArgOffset) {
618     if (!MS.TrackOrigins) return 0;
619     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
620     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
621     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
622                               "_msarg_o");
623   }
624
625   /// \brief Compute the shadow address for a retval.
626   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
627     Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
628     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
629                               "_msret");
630   }
631
632   /// \brief Compute the origin address for a retval.
633   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
634     // We keep a single origin for the entire retval. Might be too optimistic.
635     return MS.RetvalOriginTLS;
636   }
637
638   /// \brief Set SV to be the shadow value for V.
639   void setShadow(Value *V, Value *SV) {
640     assert(!ShadowMap.count(V) && "Values may only have one shadow");
641     ShadowMap[V] = SV;
642   }
643
644   /// \brief Set Origin to be the origin value for V.
645   void setOrigin(Value *V, Value *Origin) {
646     if (!MS.TrackOrigins) return;
647     assert(!OriginMap.count(V) && "Values may only have one origin");
648     DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
649     OriginMap[V] = Origin;
650   }
651
652   /// \brief Create a clean shadow value for a given value.
653   ///
654   /// Clean shadow (all zeroes) means all bits of the value are defined
655   /// (initialized).
656   Value *getCleanShadow(Value *V) {
657     Type *ShadowTy = getShadowTy(V);
658     if (!ShadowTy)
659       return 0;
660     return Constant::getNullValue(ShadowTy);
661   }
662
663   /// \brief Create a dirty shadow of a given shadow type.
664   Constant *getPoisonedShadow(Type *ShadowTy) {
665     assert(ShadowTy);
666     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
667       return Constant::getAllOnesValue(ShadowTy);
668     StructType *ST = cast<StructType>(ShadowTy);
669     SmallVector<Constant *, 4> Vals;
670     for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
671       Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
672     return ConstantStruct::get(ST, Vals);
673   }
674
675   /// \brief Create a clean (zero) origin.
676   Value *getCleanOrigin() {
677     return Constant::getNullValue(MS.OriginTy);
678   }
679
680   /// \brief Get the shadow value for a given Value.
681   ///
682   /// This function either returns the value set earlier with setShadow,
683   /// or extracts if from ParamTLS (for function arguments).
684   Value *getShadow(Value *V) {
685     if (Instruction *I = dyn_cast<Instruction>(V)) {
686       // For instructions the shadow is already stored in the map.
687       Value *Shadow = ShadowMap[V];
688       if (!Shadow) {
689         DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
690         (void)I;
691         assert(Shadow && "No shadow for a value");
692       }
693       return Shadow;
694     }
695     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
696       Value *AllOnes = getPoisonedShadow(getShadowTy(V));
697       DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
698       (void)U;
699       return AllOnes;
700     }
701     if (Argument *A = dyn_cast<Argument>(V)) {
702       // For arguments we compute the shadow on demand and store it in the map.
703       Value **ShadowPtr = &ShadowMap[V];
704       if (*ShadowPtr)
705         return *ShadowPtr;
706       Function *F = A->getParent();
707       IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
708       unsigned ArgOffset = 0;
709       for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
710            AI != AE; ++AI) {
711         if (!AI->getType()->isSized()) {
712           DEBUG(dbgs() << "Arg is not sized\n");
713           continue;
714         }
715         unsigned Size = AI->hasByValAttr()
716           ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
717           : MS.TD->getTypeAllocSize(AI->getType());
718         if (A == AI) {
719           Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
720           if (AI->hasByValAttr()) {
721             // ByVal pointer itself has clean shadow. We copy the actual
722             // argument shadow to the underlying memory.
723             Value *Cpy = EntryIRB.CreateMemCpy(
724               getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
725               Base, Size, AI->getParamAlignment());
726             DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
727             (void)Cpy;
728             *ShadowPtr = getCleanShadow(V);
729           } else {
730             *ShadowPtr = EntryIRB.CreateLoad(Base);
731           }
732           DEBUG(dbgs() << "  ARG:    "  << *AI << " ==> " <<
733                 **ShadowPtr << "\n");
734           if (MS.TrackOrigins) {
735             Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
736             setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
737           }
738         }
739         ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
740       }
741       assert(*ShadowPtr && "Could not find shadow for an argument");
742       return *ShadowPtr;
743     }
744     // For everything else the shadow is zero.
745     return getCleanShadow(V);
746   }
747
748   /// \brief Get the shadow for i-th argument of the instruction I.
749   Value *getShadow(Instruction *I, int i) {
750     return getShadow(I->getOperand(i));
751   }
752
753   /// \brief Get the origin for a value.
754   Value *getOrigin(Value *V) {
755     if (!MS.TrackOrigins) return 0;
756     if (isa<Instruction>(V) || isa<Argument>(V)) {
757       Value *Origin = OriginMap[V];
758       if (!Origin) {
759         DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
760         Origin = getCleanOrigin();
761       }
762       return Origin;
763     }
764     return getCleanOrigin();
765   }
766
767   /// \brief Get the origin for i-th argument of the instruction I.
768   Value *getOrigin(Instruction *I, int i) {
769     return getOrigin(I->getOperand(i));
770   }
771
772   /// \brief Remember the place where a shadow check should be inserted.
773   ///
774   /// This location will be later instrumented with a check that will print a
775   /// UMR warning in runtime if the value is not fully defined.
776   void insertCheck(Value *Val, Instruction *OrigIns) {
777     assert(Val);
778     if (!InsertChecks) return;
779     Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
780     if (!Shadow) return;
781 #ifndef NDEBUG
782     Type *ShadowTy = Shadow->getType();
783     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
784            "Can only insert checks for integer and vector shadow types");
785 #endif
786     Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
787     InstrumentationList.push_back(
788       ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
789   }
790
791   // ------------------- Visitors.
792
793   /// \brief Instrument LoadInst
794   ///
795   /// Loads the corresponding shadow and (optionally) origin.
796   /// Optionally, checks that the load address is fully defined.
797   void visitLoadInst(LoadInst &I) {
798     assert(I.getType()->isSized() && "Load type must have size");
799     IRBuilder<> IRB(&I);
800     Type *ShadowTy = getShadowTy(&I);
801     Value *Addr = I.getPointerOperand();
802     Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
803     setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
804
805     if (ClCheckAccessAddress)
806       insertCheck(I.getPointerOperand(), &I);
807
808     if (MS.TrackOrigins)
809       setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
810   }
811
812   /// \brief Instrument StoreInst
813   ///
814   /// Stores the corresponding shadow and (optionally) origin.
815   /// Optionally, checks that the store address is fully defined.
816   /// Volatile stores check that the value being stored is fully defined.
817   void visitStoreInst(StoreInst &I) {
818     StoreList.push_back(&I);
819   }
820
821   // Vector manipulation.
822   void visitExtractElementInst(ExtractElementInst &I) {
823     insertCheck(I.getOperand(1), &I);
824     IRBuilder<> IRB(&I);
825     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
826               "_msprop"));
827     setOrigin(&I, getOrigin(&I, 0));
828   }
829
830   void visitInsertElementInst(InsertElementInst &I) {
831     insertCheck(I.getOperand(2), &I);
832     IRBuilder<> IRB(&I);
833     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
834               I.getOperand(2), "_msprop"));
835     setOriginForNaryOp(I);
836   }
837
838   void visitShuffleVectorInst(ShuffleVectorInst &I) {
839     insertCheck(I.getOperand(2), &I);
840     IRBuilder<> IRB(&I);
841     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
842               I.getOperand(2), "_msprop"));
843     setOriginForNaryOp(I);
844   }
845
846   // Casts.
847   void visitSExtInst(SExtInst &I) {
848     IRBuilder<> IRB(&I);
849     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
850     setOrigin(&I, getOrigin(&I, 0));
851   }
852
853   void visitZExtInst(ZExtInst &I) {
854     IRBuilder<> IRB(&I);
855     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
856     setOrigin(&I, getOrigin(&I, 0));
857   }
858
859   void visitTruncInst(TruncInst &I) {
860     IRBuilder<> IRB(&I);
861     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
862     setOrigin(&I, getOrigin(&I, 0));
863   }
864
865   void visitBitCastInst(BitCastInst &I) {
866     IRBuilder<> IRB(&I);
867     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
868     setOrigin(&I, getOrigin(&I, 0));
869   }
870
871   void visitPtrToIntInst(PtrToIntInst &I) {
872     IRBuilder<> IRB(&I);
873     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
874              "_msprop_ptrtoint"));
875     setOrigin(&I, getOrigin(&I, 0));
876   }
877
878   void visitIntToPtrInst(IntToPtrInst &I) {
879     IRBuilder<> IRB(&I);
880     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
881              "_msprop_inttoptr"));
882     setOrigin(&I, getOrigin(&I, 0));
883   }
884
885   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
886   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
887   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
888   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
889   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
890   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
891
892   /// \brief Propagate shadow for bitwise AND.
893   ///
894   /// This code is exact, i.e. if, for example, a bit in the left argument
895   /// is defined and 0, then neither the value not definedness of the
896   /// corresponding bit in B don't affect the resulting shadow.
897   void visitAnd(BinaryOperator &I) {
898     IRBuilder<> IRB(&I);
899     //  "And" of 0 and a poisoned value results in unpoisoned value.
900     //  1&1 => 1;     0&1 => 0;     p&1 => p;
901     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
902     //  1&p => p;     0&p => 0;     p&p => p;
903     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
904     Value *S1 = getShadow(&I, 0);
905     Value *S2 = getShadow(&I, 1);
906     Value *V1 = I.getOperand(0);
907     Value *V2 = I.getOperand(1);
908     if (V1->getType() != S1->getType()) {
909       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
910       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
911     }
912     Value *S1S2 = IRB.CreateAnd(S1, S2);
913     Value *V1S2 = IRB.CreateAnd(V1, S2);
914     Value *S1V2 = IRB.CreateAnd(S1, V2);
915     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
916     setOriginForNaryOp(I);
917   }
918
919   void visitOr(BinaryOperator &I) {
920     IRBuilder<> IRB(&I);
921     //  "Or" of 1 and a poisoned value results in unpoisoned value.
922     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
923     //  1|0 => 1;     0|0 => 0;     p|0 => p;
924     //  1|p => 1;     0|p => p;     p|p => p;
925     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
926     Value *S1 = getShadow(&I, 0);
927     Value *S2 = getShadow(&I, 1);
928     Value *V1 = IRB.CreateNot(I.getOperand(0));
929     Value *V2 = IRB.CreateNot(I.getOperand(1));
930     if (V1->getType() != S1->getType()) {
931       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
932       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
933     }
934     Value *S1S2 = IRB.CreateAnd(S1, S2);
935     Value *V1S2 = IRB.CreateAnd(V1, S2);
936     Value *S1V2 = IRB.CreateAnd(S1, V2);
937     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
938     setOriginForNaryOp(I);
939   }
940
941   /// \brief Default propagation of shadow and/or origin.
942   ///
943   /// This class implements the general case of shadow propagation, used in all
944   /// cases where we don't know and/or don't care about what the operation
945   /// actually does. It converts all input shadow values to a common type
946   /// (extending or truncating as necessary), and bitwise OR's them.
947   ///
948   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
949   /// fully initialized), and less prone to false positives.
950   ///
951   /// This class also implements the general case of origin propagation. For a
952   /// Nary operation, result origin is set to the origin of an argument that is
953   /// not entirely initialized. If there is more than one such arguments, the
954   /// rightmost of them is picked. It does not matter which one is picked if all
955   /// arguments are initialized.
956   template <bool CombineShadow>
957   class Combiner {
958     Value *Shadow;
959     Value *Origin;
960     IRBuilder<> &IRB;
961     MemorySanitizerVisitor *MSV;
962
963   public:
964     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
965       Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
966
967     /// \brief Add a pair of shadow and origin values to the mix.
968     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
969       if (CombineShadow) {
970         assert(OpShadow);
971         if (!Shadow)
972           Shadow = OpShadow;
973         else {
974           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
975           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
976         }
977       }
978
979       if (MSV->MS.TrackOrigins) {
980         assert(OpOrigin);
981         if (!Origin) {
982           Origin = OpOrigin;
983         } else {
984           Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
985           Value *Cond = IRB.CreateICmpNE(FlatShadow,
986                                          MSV->getCleanShadow(FlatShadow));
987           Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
988         }
989       }
990       return *this;
991     }
992
993     /// \brief Add an application value to the mix.
994     Combiner &Add(Value *V) {
995       Value *OpShadow = MSV->getShadow(V);
996       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
997       return Add(OpShadow, OpOrigin);
998     }
999
1000     /// \brief Set the current combined values as the given instruction's shadow
1001     /// and origin.
1002     void Done(Instruction *I) {
1003       if (CombineShadow) {
1004         assert(Shadow);
1005         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1006         MSV->setShadow(I, Shadow);
1007       }
1008       if (MSV->MS.TrackOrigins) {
1009         assert(Origin);
1010         MSV->setOrigin(I, Origin);
1011       }
1012     }
1013   };
1014
1015   typedef Combiner<true> ShadowAndOriginCombiner;
1016   typedef Combiner<false> OriginCombiner;
1017
1018   /// \brief Propagate origin for arbitrary operation.
1019   void setOriginForNaryOp(Instruction &I) {
1020     if (!MS.TrackOrigins) return;
1021     IRBuilder<> IRB(&I);
1022     OriginCombiner OC(this, IRB);
1023     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1024       OC.Add(OI->get());
1025     OC.Done(&I);
1026   }
1027
1028   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1029     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1030            "Vector of pointers is not a valid shadow type");
1031     return Ty->isVectorTy() ?
1032       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1033       Ty->getPrimitiveSizeInBits();
1034   }
1035
1036   /// \brief Cast between two shadow types, extending or truncating as
1037   /// necessary.
1038   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1039     Type *srcTy = V->getType();
1040     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1041       return IRB.CreateIntCast(V, dstTy, false);
1042     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1043         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1044       return IRB.CreateIntCast(V, dstTy, false);
1045     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1046     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1047     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1048     Value *V2 =
1049       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1050     return IRB.CreateBitCast(V2, dstTy);
1051     // TODO: handle struct types.
1052   }
1053
1054   /// \brief Propagate shadow for arbitrary operation.
1055   void handleShadowOr(Instruction &I) {
1056     IRBuilder<> IRB(&I);
1057     ShadowAndOriginCombiner SC(this, IRB);
1058     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1059       SC.Add(OI->get());
1060     SC.Done(&I);
1061   }
1062
1063   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1064   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1065   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1066   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1067   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1068   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1069   void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1070
1071   void handleDiv(Instruction &I) {
1072     IRBuilder<> IRB(&I);
1073     // Strict on the second argument.
1074     insertCheck(I.getOperand(1), &I);
1075     setShadow(&I, getShadow(&I, 0));
1076     setOrigin(&I, getOrigin(&I, 0));
1077   }
1078
1079   void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1080   void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1081   void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1082   void visitURem(BinaryOperator &I) { handleDiv(I); }
1083   void visitSRem(BinaryOperator &I) { handleDiv(I); }
1084   void visitFRem(BinaryOperator &I) { handleDiv(I); }
1085
1086   /// \brief Instrument == and != comparisons.
1087   ///
1088   /// Sometimes the comparison result is known even if some of the bits of the
1089   /// arguments are not.
1090   void handleEqualityComparison(ICmpInst &I) {
1091     IRBuilder<> IRB(&I);
1092     Value *A = I.getOperand(0);
1093     Value *B = I.getOperand(1);
1094     Value *Sa = getShadow(A);
1095     Value *Sb = getShadow(B);
1096     if (A->getType()->isPointerTy())
1097       A = IRB.CreatePointerCast(A, MS.IntptrTy);
1098     if (B->getType()->isPointerTy())
1099       B = IRB.CreatePointerCast(B, MS.IntptrTy);
1100     // A == B  <==>  (C = A^B) == 0
1101     // A != B  <==>  (C = A^B) != 0
1102     // Sc = Sa | Sb
1103     Value *C = IRB.CreateXor(A, B);
1104     Value *Sc = IRB.CreateOr(Sa, Sb);
1105     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1106     // Result is defined if one of the following is true
1107     // * there is a defined 1 bit in C
1108     // * C is fully defined
1109     // Si = !(C & ~Sc) && Sc
1110     Value *Zero = Constant::getNullValue(Sc->getType());
1111     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1112     Value *Si =
1113       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1114                     IRB.CreateICmpEQ(
1115                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1116     Si->setName("_msprop_icmp");
1117     setShadow(&I, Si);
1118     setOriginForNaryOp(I);
1119   }
1120
1121   /// \brief Instrument signed relational comparisons.
1122   ///
1123   /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1124   /// propagating the highest bit of the shadow. Everything else is delegated
1125   /// to handleShadowOr().
1126   void handleSignedRelationalComparison(ICmpInst &I) {
1127     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1128     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1129     Value* op = NULL;
1130     CmpInst::Predicate pre = I.getPredicate();
1131     if (constOp0 && constOp0->isNullValue() &&
1132         (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1133       op = I.getOperand(1);
1134     } else if (constOp1 && constOp1->isNullValue() &&
1135                (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1136       op = I.getOperand(0);
1137     }
1138     if (op) {
1139       IRBuilder<> IRB(&I);
1140       Value* Shadow =
1141         IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1142       setShadow(&I, Shadow);
1143       setOrigin(&I, getOrigin(op));
1144     } else {
1145       handleShadowOr(I);
1146     }
1147   }
1148
1149   void visitICmpInst(ICmpInst &I) {
1150     if (ClHandleICmp && I.isEquality())
1151       handleEqualityComparison(I);
1152     else if (ClHandleICmp && I.isSigned() && I.isRelational())
1153       handleSignedRelationalComparison(I);
1154     else
1155       handleShadowOr(I);
1156   }
1157
1158   void visitFCmpInst(FCmpInst &I) {
1159     handleShadowOr(I);
1160   }
1161
1162   void handleShift(BinaryOperator &I) {
1163     IRBuilder<> IRB(&I);
1164     // If any of the S2 bits are poisoned, the whole thing is poisoned.
1165     // Otherwise perform the same shift on S1.
1166     Value *S1 = getShadow(&I, 0);
1167     Value *S2 = getShadow(&I, 1);
1168     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1169                                    S2->getType());
1170     Value *V2 = I.getOperand(1);
1171     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1172     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1173     setOriginForNaryOp(I);
1174   }
1175
1176   void visitShl(BinaryOperator &I) { handleShift(I); }
1177   void visitAShr(BinaryOperator &I) { handleShift(I); }
1178   void visitLShr(BinaryOperator &I) { handleShift(I); }
1179
1180   /// \brief Instrument llvm.memmove
1181   ///
1182   /// At this point we don't know if llvm.memmove will be inlined or not.
1183   /// If we don't instrument it and it gets inlined,
1184   /// our interceptor will not kick in and we will lose the memmove.
1185   /// If we instrument the call here, but it does not get inlined,
1186   /// we will memove the shadow twice: which is bad in case
1187   /// of overlapping regions. So, we simply lower the intrinsic to a call.
1188   ///
1189   /// Similar situation exists for memcpy and memset.
1190   void visitMemMoveInst(MemMoveInst &I) {
1191     IRBuilder<> IRB(&I);
1192     IRB.CreateCall3(
1193       MS.MemmoveFn,
1194       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1195       IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1196       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1197     I.eraseFromParent();
1198   }
1199
1200   // Similar to memmove: avoid copying shadow twice.
1201   // This is somewhat unfortunate as it may slowdown small constant memcpys.
1202   // FIXME: consider doing manual inline for small constant sizes and proper
1203   // alignment.
1204   void visitMemCpyInst(MemCpyInst &I) {
1205     IRBuilder<> IRB(&I);
1206     IRB.CreateCall3(
1207       MS.MemcpyFn,
1208       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1209       IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1210       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1211     I.eraseFromParent();
1212   }
1213
1214   // Same as memcpy.
1215   void visitMemSetInst(MemSetInst &I) {
1216     IRBuilder<> IRB(&I);
1217     IRB.CreateCall3(
1218       MS.MemsetFn,
1219       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1220       IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1221       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1222     I.eraseFromParent();
1223   }
1224
1225   void visitVAStartInst(VAStartInst &I) {
1226     VAHelper->visitVAStartInst(I);
1227   }
1228
1229   void visitVACopyInst(VACopyInst &I) {
1230     VAHelper->visitVACopyInst(I);
1231   }
1232
1233   enum IntrinsicKind {
1234     IK_DoesNotAccessMemory,
1235     IK_OnlyReadsMemory,
1236     IK_WritesMemory
1237   };
1238
1239   static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1240     const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1241     const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1242     const int OnlyReadsMemory = IK_OnlyReadsMemory;
1243     const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1244     const int UnknownModRefBehavior = IK_WritesMemory;
1245 #define GET_INTRINSIC_MODREF_BEHAVIOR
1246 #define ModRefBehavior IntrinsicKind
1247 #include "llvm/Intrinsics.gen"
1248 #undef ModRefBehavior
1249 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1250   }
1251
1252   /// \brief Handle vector store-like intrinsics.
1253   ///
1254   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1255   /// has 1 pointer argument and 1 vector argument, returns void.
1256   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1257     IRBuilder<> IRB(&I);
1258     Value* Addr = I.getArgOperand(0);
1259     Value *Shadow = getShadow(&I, 1);
1260     Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1261
1262     // We don't know the pointer alignment (could be unaligned SSE store!).
1263     // Have to assume to worst case.
1264     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1265
1266     if (ClCheckAccessAddress)
1267       insertCheck(Addr, &I);
1268
1269     // FIXME: use ClStoreCleanOrigin
1270     // FIXME: factor out common code from materializeStores
1271     if (MS.TrackOrigins)
1272       IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1273     return true;
1274   }
1275
1276   /// \brief Handle vector load-like intrinsics.
1277   ///
1278   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1279   /// has 1 pointer argument, returns a vector.
1280   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1281     IRBuilder<> IRB(&I);
1282     Value *Addr = I.getArgOperand(0);
1283
1284     Type *ShadowTy = getShadowTy(&I);
1285     Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1286     // We don't know the pointer alignment (could be unaligned SSE load!).
1287     // Have to assume to worst case.
1288     setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1289
1290     if (ClCheckAccessAddress)
1291       insertCheck(Addr, &I);
1292
1293     if (MS.TrackOrigins)
1294       setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1295     return true;
1296   }
1297
1298   /// \brief Handle (SIMD arithmetic)-like intrinsics.
1299   ///
1300   /// Instrument intrinsics with any number of arguments of the same type,
1301   /// equal to the return type. The type should be simple (no aggregates or
1302   /// pointers; vectors are fine).
1303   /// Caller guarantees that this intrinsic does not access memory.
1304   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1305     Type *RetTy = I.getType();
1306     if (!(RetTy->isIntOrIntVectorTy() ||
1307           RetTy->isFPOrFPVectorTy() ||
1308           RetTy->isX86_MMXTy()))
1309       return false;
1310
1311     unsigned NumArgOperands = I.getNumArgOperands();
1312
1313     for (unsigned i = 0; i < NumArgOperands; ++i) {
1314       Type *Ty = I.getArgOperand(i)->getType();
1315       if (Ty != RetTy)
1316         return false;
1317     }
1318
1319     IRBuilder<> IRB(&I);
1320     ShadowAndOriginCombiner SC(this, IRB);
1321     for (unsigned i = 0; i < NumArgOperands; ++i)
1322       SC.Add(I.getArgOperand(i));
1323     SC.Done(&I);
1324
1325     return true;
1326   }
1327
1328   /// \brief Heuristically instrument unknown intrinsics.
1329   ///
1330   /// The main purpose of this code is to do something reasonable with all
1331   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1332   /// We recognize several classes of intrinsics by their argument types and
1333   /// ModRefBehaviour and apply special intrumentation when we are reasonably
1334   /// sure that we know what the intrinsic does.
1335   ///
1336   /// We special-case intrinsics where this approach fails. See llvm.bswap
1337   /// handling as an example of that.
1338   bool handleUnknownIntrinsic(IntrinsicInst &I) {
1339     unsigned NumArgOperands = I.getNumArgOperands();
1340     if (NumArgOperands == 0)
1341       return false;
1342
1343     Intrinsic::ID iid = I.getIntrinsicID();
1344     IntrinsicKind IK = getIntrinsicKind(iid);
1345     bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1346     bool WritesMemory = IK == IK_WritesMemory;
1347     assert(!(OnlyReadsMemory && WritesMemory));
1348
1349     if (NumArgOperands == 2 &&
1350         I.getArgOperand(0)->getType()->isPointerTy() &&
1351         I.getArgOperand(1)->getType()->isVectorTy() &&
1352         I.getType()->isVoidTy() &&
1353         WritesMemory) {
1354       // This looks like a vector store.
1355       return handleVectorStoreIntrinsic(I);
1356     }
1357
1358     if (NumArgOperands == 1 &&
1359         I.getArgOperand(0)->getType()->isPointerTy() &&
1360         I.getType()->isVectorTy() &&
1361         OnlyReadsMemory) {
1362       // This looks like a vector load.
1363       return handleVectorLoadIntrinsic(I);
1364     }
1365
1366     if (!OnlyReadsMemory && !WritesMemory)
1367       if (maybeHandleSimpleNomemIntrinsic(I))
1368         return true;
1369
1370     // FIXME: detect and handle SSE maskstore/maskload
1371     return false;
1372   }
1373
1374   void handleBswap(IntrinsicInst &I) {
1375     IRBuilder<> IRB(&I);
1376     Value *Op = I.getArgOperand(0);
1377     Type *OpType = Op->getType();
1378     Function *BswapFunc = Intrinsic::getDeclaration(
1379       F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1380     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1381     setOrigin(&I, getOrigin(Op));
1382   }
1383
1384   void visitIntrinsicInst(IntrinsicInst &I) {
1385     switch (I.getIntrinsicID()) {
1386     case llvm::Intrinsic::bswap:
1387       handleBswap(I);
1388       break;
1389     default:
1390       if (!handleUnknownIntrinsic(I))
1391         visitInstruction(I);
1392       break;
1393     }
1394   }
1395
1396   void visitCallSite(CallSite CS) {
1397     Instruction &I = *CS.getInstruction();
1398     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1399     if (CS.isCall()) {
1400       CallInst *Call = cast<CallInst>(&I);
1401
1402       // For inline asm, do the usual thing: check argument shadow and mark all
1403       // outputs as clean. Note that any side effects of the inline asm that are
1404       // not immediately visible in its constraints are not handled.
1405       if (Call->isInlineAsm()) {
1406         visitInstruction(I);
1407         return;
1408       }
1409
1410       // Allow only tail calls with the same types, otherwise
1411       // we may have a false positive: shadow for a non-void RetVal
1412       // will get propagated to a void RetVal.
1413       if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1414         Call->setTailCall(false);
1415
1416       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1417
1418       // We are going to insert code that relies on the fact that the callee
1419       // will become a non-readonly function after it is instrumented by us. To
1420       // prevent this code from being optimized out, mark that function
1421       // non-readonly in advance.
1422       if (Function *Func = Call->getCalledFunction()) {
1423         // Clear out readonly/readnone attributes.
1424         AttrBuilder B;
1425         B.addAttribute(Attribute::ReadOnly)
1426           .addAttribute(Attribute::ReadNone);
1427         Func->removeAttribute(AttributeSet::FunctionIndex,
1428                               Attribute::get(Func->getContext(), B));
1429       }
1430     }
1431     IRBuilder<> IRB(&I);
1432     unsigned ArgOffset = 0;
1433     DEBUG(dbgs() << "  CallSite: " << I << "\n");
1434     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1435          ArgIt != End; ++ArgIt) {
1436       Value *A = *ArgIt;
1437       unsigned i = ArgIt - CS.arg_begin();
1438       if (!A->getType()->isSized()) {
1439         DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1440         continue;
1441       }
1442       unsigned Size = 0;
1443       Value *Store = 0;
1444       // Compute the Shadow for arg even if it is ByVal, because
1445       // in that case getShadow() will copy the actual arg shadow to
1446       // __msan_param_tls.
1447       Value *ArgShadow = getShadow(A);
1448       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1449       DEBUG(dbgs() << "  Arg#" << i << ": " << *A <<
1450             " Shadow: " << *ArgShadow << "\n");
1451       if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
1452         assert(A->getType()->isPointerTy() &&
1453                "ByVal argument is not a pointer!");
1454         Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1455         unsigned Alignment = CS.getParamAlignment(i + 1);
1456         Store = IRB.CreateMemCpy(ArgShadowBase,
1457                                  getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1458                                  Size, Alignment);
1459       } else {
1460         Size = MS.TD->getTypeAllocSize(A->getType());
1461         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1462                                        kShadowTLSAlignment);
1463       }
1464       if (MS.TrackOrigins)
1465         IRB.CreateStore(getOrigin(A),
1466                         getOriginPtrForArgument(A, IRB, ArgOffset));
1467       assert(Size != 0 && Store != 0);
1468       DEBUG(dbgs() << "  Param:" << *Store << "\n");
1469       ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1470     }
1471     DEBUG(dbgs() << "  done with call args\n");
1472
1473     FunctionType *FT =
1474       cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1475     if (FT->isVarArg()) {
1476       VAHelper->visitCallSite(CS, IRB);
1477     }
1478
1479     // Now, get the shadow for the RetVal.
1480     if (!I.getType()->isSized()) return;
1481     IRBuilder<> IRBBefore(&I);
1482     // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1483     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1484     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
1485     Instruction *NextInsn = 0;
1486     if (CS.isCall()) {
1487       NextInsn = I.getNextNode();
1488     } else {
1489       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1490       if (!NormalDest->getSinglePredecessor()) {
1491         // FIXME: this case is tricky, so we are just conservative here.
1492         // Perhaps we need to split the edge between this BB and NormalDest,
1493         // but a naive attempt to use SplitEdge leads to a crash.
1494         setShadow(&I, getCleanShadow(&I));
1495         setOrigin(&I, getCleanOrigin());
1496         return;
1497       }
1498       NextInsn = NormalDest->getFirstInsertionPt();
1499       assert(NextInsn &&
1500              "Could not find insertion point for retval shadow load");
1501     }
1502     IRBuilder<> IRBAfter(NextInsn);
1503     Value *RetvalShadow =
1504       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1505                                  kShadowTLSAlignment, "_msret");
1506     setShadow(&I, RetvalShadow);
1507     if (MS.TrackOrigins)
1508       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1509   }
1510
1511   void visitReturnInst(ReturnInst &I) {
1512     IRBuilder<> IRB(&I);
1513     if (Value *RetVal = I.getReturnValue()) {
1514       // Set the shadow for the RetVal.
1515       Value *Shadow = getShadow(RetVal);
1516       Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1517       DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
1518       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1519       if (MS.TrackOrigins)
1520         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1521     }
1522   }
1523
1524   void visitPHINode(PHINode &I) {
1525     IRBuilder<> IRB(&I);
1526     ShadowPHINodes.push_back(&I);
1527     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1528                                 "_msphi_s"));
1529     if (MS.TrackOrigins)
1530       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1531                                   "_msphi_o"));
1532   }
1533
1534   void visitAllocaInst(AllocaInst &I) {
1535     setShadow(&I, getCleanShadow(&I));
1536     if (!ClPoisonStack) return;
1537     IRBuilder<> IRB(I.getNextNode());
1538     uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1539     if (ClPoisonStackWithCall) {
1540       IRB.CreateCall2(MS.MsanPoisonStackFn,
1541                       IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1542                       ConstantInt::get(MS.IntptrTy, Size));
1543     } else {
1544       Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1545       IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1546                        Size, I.getAlignment());
1547     }
1548
1549     if (MS.TrackOrigins) {
1550       setOrigin(&I, getCleanOrigin());
1551       SmallString<2048> StackDescriptionStorage;
1552       raw_svector_ostream StackDescription(StackDescriptionStorage);
1553       // We create a string with a description of the stack allocation and
1554       // pass it into __msan_set_alloca_origin.
1555       // It will be printed by the run-time if stack-originated UMR is found.
1556       // The first 4 bytes of the string are set to '----' and will be replaced
1557       // by __msan_va_arg_overflow_size_tls at the first call.
1558       StackDescription << "----" << I.getName() << "@" << F.getName();
1559       Value *Descr =
1560           createPrivateNonConstGlobalForString(*F.getParent(),
1561                                                StackDescription.str());
1562       IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1563                       IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1564                       ConstantInt::get(MS.IntptrTy, Size),
1565                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1566     }
1567   }
1568
1569   void visitSelectInst(SelectInst& I) {
1570     IRBuilder<> IRB(&I);
1571     setShadow(&I,  IRB.CreateSelect(I.getCondition(),
1572               getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1573               "_msprop"));
1574     if (MS.TrackOrigins) {
1575       // Origins are always i32, so any vector conditions must be flattened.
1576       // FIXME: consider tracking vector origins for app vectors?
1577       Value *Cond = I.getCondition();
1578       if (Cond->getType()->isVectorTy()) {
1579         Value *ConvertedShadow = convertToShadowTyNoVec(Cond, IRB);
1580         Cond = IRB.CreateICmpNE(ConvertedShadow,
1581                                 getCleanShadow(ConvertedShadow), "_mso_select");
1582       }
1583       setOrigin(&I, IRB.CreateSelect(Cond,
1584                 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1585     }
1586   }
1587
1588   void visitLandingPadInst(LandingPadInst &I) {
1589     // Do nothing.
1590     // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1591     setShadow(&I, getCleanShadow(&I));
1592     setOrigin(&I, getCleanOrigin());
1593   }
1594
1595   void visitGetElementPtrInst(GetElementPtrInst &I) {
1596     handleShadowOr(I);
1597   }
1598
1599   void visitExtractValueInst(ExtractValueInst &I) {
1600     IRBuilder<> IRB(&I);
1601     Value *Agg = I.getAggregateOperand();
1602     DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
1603     Value *AggShadow = getShadow(Agg);
1604     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
1605     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1606     DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
1607     setShadow(&I, ResShadow);
1608     setOrigin(&I, getCleanOrigin());
1609   }
1610
1611   void visitInsertValueInst(InsertValueInst &I) {
1612     IRBuilder<> IRB(&I);
1613     DEBUG(dbgs() << "InsertValue:  " << I << "\n");
1614     Value *AggShadow = getShadow(I.getAggregateOperand());
1615     Value *InsShadow = getShadow(I.getInsertedValueOperand());
1616     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
1617     DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
1618     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1619     DEBUG(dbgs() << "   Res:        " << *Res << "\n");
1620     setShadow(&I, Res);
1621     setOrigin(&I, getCleanOrigin());
1622   }
1623
1624   void dumpInst(Instruction &I) {
1625     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1626       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1627     } else {
1628       errs() << "ZZZ " << I.getOpcodeName() << "\n";
1629     }
1630     errs() << "QQQ " << I << "\n";
1631   }
1632
1633   void visitResumeInst(ResumeInst &I) {
1634     DEBUG(dbgs() << "Resume: " << I << "\n");
1635     // Nothing to do here.
1636   }
1637
1638   void visitInstruction(Instruction &I) {
1639     // Everything else: stop propagating and check for poisoned shadow.
1640     if (ClDumpStrictInstructions)
1641       dumpInst(I);
1642     DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1643     for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1644       insertCheck(I.getOperand(i), &I);
1645     setShadow(&I, getCleanShadow(&I));
1646     setOrigin(&I, getCleanOrigin());
1647   }
1648 };
1649
1650 /// \brief AMD64-specific implementation of VarArgHelper.
1651 struct VarArgAMD64Helper : public VarArgHelper {
1652   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1653   // See a comment in visitCallSite for more details.
1654   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
1655   static const unsigned AMD64FpEndOffset = 176;
1656
1657   Function &F;
1658   MemorySanitizer &MS;
1659   MemorySanitizerVisitor &MSV;
1660   Value *VAArgTLSCopy;
1661   Value *VAArgOverflowSize;
1662
1663   SmallVector<CallInst*, 16> VAStartInstrumentationList;
1664
1665   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1666                     MemorySanitizerVisitor &MSV)
1667     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1668
1669   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1670
1671   ArgKind classifyArgument(Value* arg) {
1672     // A very rough approximation of X86_64 argument classification rules.
1673     Type *T = arg->getType();
1674     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1675       return AK_FloatingPoint;
1676     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1677       return AK_GeneralPurpose;
1678     if (T->isPointerTy())
1679       return AK_GeneralPurpose;
1680     return AK_Memory;
1681   }
1682
1683   // For VarArg functions, store the argument shadow in an ABI-specific format
1684   // that corresponds to va_list layout.
1685   // We do this because Clang lowers va_arg in the frontend, and this pass
1686   // only sees the low level code that deals with va_list internals.
1687   // A much easier alternative (provided that Clang emits va_arg instructions)
1688   // would have been to associate each live instance of va_list with a copy of
1689   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1690   // order.
1691   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1692     unsigned GpOffset = 0;
1693     unsigned FpOffset = AMD64GpEndOffset;
1694     unsigned OverflowOffset = AMD64FpEndOffset;
1695     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1696          ArgIt != End; ++ArgIt) {
1697       Value *A = *ArgIt;
1698       ArgKind AK = classifyArgument(A);
1699       if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1700         AK = AK_Memory;
1701       if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1702         AK = AK_Memory;
1703       Value *Base;
1704       switch (AK) {
1705       case AK_GeneralPurpose:
1706         Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1707         GpOffset += 8;
1708         break;
1709       case AK_FloatingPoint:
1710         Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1711         FpOffset += 16;
1712         break;
1713       case AK_Memory:
1714         uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1715         Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1716         OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1717       }
1718       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
1719     }
1720     Constant *OverflowSize =
1721       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1722     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1723   }
1724
1725   /// \brief Compute the shadow address for a given va_arg.
1726   Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1727                                    int ArgOffset) {
1728     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1729     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1730     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1731                               "_msarg");
1732   }
1733
1734   void visitVAStartInst(VAStartInst &I) {
1735     IRBuilder<> IRB(&I);
1736     VAStartInstrumentationList.push_back(&I);
1737     Value *VAListTag = I.getArgOperand(0);
1738     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1739
1740     // Unpoison the whole __va_list_tag.
1741     // FIXME: magic ABI constants.
1742     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1743                      /* size */24, /* alignment */16, false);
1744   }
1745
1746   void visitVACopyInst(VACopyInst &I) {
1747     IRBuilder<> IRB(&I);
1748     Value *VAListTag = I.getArgOperand(0);
1749     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1750
1751     // Unpoison the whole __va_list_tag.
1752     // FIXME: magic ABI constants.
1753     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1754                      /* size */ 24, /* alignment */ 16, false);
1755   }
1756
1757   void finalizeInstrumentation() {
1758     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1759            "finalizeInstrumentation called twice");
1760     if (!VAStartInstrumentationList.empty()) {
1761       // If there is a va_start in this function, make a backup copy of
1762       // va_arg_tls somewhere in the function entry block.
1763       IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1764       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1765       Value *CopySize =
1766         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1767                       VAArgOverflowSize);
1768       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1769       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1770     }
1771
1772     // Instrument va_start.
1773     // Copy va_list shadow from the backup copy of the TLS contents.
1774     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1775       CallInst *OrigInst = VAStartInstrumentationList[i];
1776       IRBuilder<> IRB(OrigInst->getNextNode());
1777       Value *VAListTag = OrigInst->getArgOperand(0);
1778
1779       Value *RegSaveAreaPtrPtr =
1780         IRB.CreateIntToPtr(
1781           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1782                         ConstantInt::get(MS.IntptrTy, 16)),
1783           Type::getInt64PtrTy(*MS.C));
1784       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1785       Value *RegSaveAreaShadowPtr =
1786         MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1787       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1788                        AMD64FpEndOffset, 16);
1789
1790       Value *OverflowArgAreaPtrPtr =
1791         IRB.CreateIntToPtr(
1792           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1793                         ConstantInt::get(MS.IntptrTy, 8)),
1794           Type::getInt64PtrTy(*MS.C));
1795       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1796       Value *OverflowArgAreaShadowPtr =
1797         MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1798       Value *SrcPtr =
1799         getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1800       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1801     }
1802   }
1803 };
1804
1805 VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1806                                  MemorySanitizerVisitor &Visitor) {
1807   return new VarArgAMD64Helper(Func, Msan, Visitor);
1808 }
1809
1810 }  // namespace
1811
1812 bool MemorySanitizer::runOnFunction(Function &F) {
1813   MemorySanitizerVisitor Visitor(F, *this);
1814
1815   // Clear out readonly/readnone attributes.
1816   AttrBuilder B;
1817   B.addAttribute(Attribute::ReadOnly)
1818     .addAttribute(Attribute::ReadNone);
1819   F.removeAttribute(AttributeSet::FunctionIndex,
1820                     Attribute::get(F.getContext(), B));
1821
1822   return Visitor.runOnFunction();
1823 }