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