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