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