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