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