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