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