1 //===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file is a part of MemorySanitizer, a detector of uninitialized
13 /// Status: early prototype.
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.
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).
39 /// The default value of shadow is 0, which means "clean" (not poisoned).
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).
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.
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.
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
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 //===----------------------------------------------------------------------===//
71 #define DEBUG_TYPE "msan"
73 #include "llvm/Transforms/Instrumentation.h"
74 #include "llvm/ADT/DepthFirstIterator.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/ValueMap.h"
78 #include "llvm/IR/DataLayout.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/IRBuilder.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/IntrinsicInst.h"
83 #include "llvm/IR/LLVMContext.h"
84 #include "llvm/IR/MDBuilder.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/Type.h"
87 #include "llvm/InstVisitor.h"
88 #include "llvm/Support/CommandLine.h"
89 #include "llvm/Support/Compiler.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
93 #include "llvm/Transforms/Utils/BlackList.h"
94 #include "llvm/Transforms/Utils/Local.h"
95 #include "llvm/Transforms/Utils/ModuleUtils.h"
99 static const uint64_t kShadowMask32 = 1ULL << 31;
100 static const uint64_t kShadowMask64 = 1ULL << 46;
101 static const uint64_t kOriginOffset32 = 1ULL << 30;
102 static const uint64_t kOriginOffset64 = 1ULL << 45;
103 static const unsigned kMinOriginAlignment = 4;
104 static const unsigned kShadowTLSAlignment = 8;
106 /// \brief Track origins of uninitialized values.
108 /// Adds a section to MemorySanitizer report that points to the allocation
109 /// (stack or heap) the uninitialized bits came from originally.
110 static cl::opt<bool> ClTrackOrigins("msan-track-origins",
111 cl::desc("Track origins (allocation sites) of poisoned memory"),
112 cl::Hidden, cl::init(false));
113 static cl::opt<bool> ClKeepGoing("msan-keep-going",
114 cl::desc("keep going after reporting a UMR"),
115 cl::Hidden, cl::init(false));
116 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
117 cl::desc("poison uninitialized stack variables"),
118 cl::Hidden, cl::init(true));
119 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
120 cl::desc("poison uninitialized stack variables with a call"),
121 cl::Hidden, cl::init(false));
122 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
123 cl::desc("poison uninitialized stack variables with the given patter"),
124 cl::Hidden, cl::init(0xff));
126 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
127 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
128 cl::Hidden, cl::init(true));
130 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
131 cl::desc("exact handling of relational integer ICmp"),
132 cl::Hidden, cl::init(false));
134 static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
135 cl::desc("store origin for clean (fully initialized) values"),
136 cl::Hidden, cl::init(false));
138 // This flag controls whether we check the shadow of the address
139 // operand of load or store. Such bugs are very rare, since load from
140 // a garbage address typically results in SEGV, but still happen
141 // (e.g. only lower bits of address are garbage, or the access happens
142 // early at program startup where malloc-ed memory is more likely to
143 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
144 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
145 cl::desc("report accesses through a pointer which has poisoned shadow"),
146 cl::Hidden, cl::init(true));
148 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
149 cl::desc("print out instructions with default strict semantics"),
150 cl::Hidden, cl::init(false));
152 static cl::opt<std::string> ClBlacklistFile("msan-blacklist",
153 cl::desc("File containing the list of functions where MemorySanitizer "
154 "should not report bugs"), cl::Hidden);
158 /// \brief An instrumentation pass implementing detection of uninitialized
161 /// MemorySanitizer: instrument the code in module to find
162 /// uninitialized reads.
163 class MemorySanitizer : public FunctionPass {
165 MemorySanitizer(bool TrackOrigins = false,
166 StringRef BlacklistFile = StringRef())
168 TrackOrigins(TrackOrigins || ClTrackOrigins),
171 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
173 const char *getPassName() const { return "MemorySanitizer"; }
174 bool runOnFunction(Function &F);
175 bool doInitialization(Module &M);
176 static char ID; // Pass identification, replacement for typeid.
179 void initializeCallbacks(Module &M);
181 /// \brief Track origins (allocation points) of uninitialized values.
188 /// \brief Thread-local shadow storage for function parameters.
189 GlobalVariable *ParamTLS;
190 /// \brief Thread-local origin storage for function parameters.
191 GlobalVariable *ParamOriginTLS;
192 /// \brief Thread-local shadow storage for function return value.
193 GlobalVariable *RetvalTLS;
194 /// \brief Thread-local origin storage for function return value.
195 GlobalVariable *RetvalOriginTLS;
196 /// \brief Thread-local shadow storage for in-register va_arg function
197 /// parameters (x86_64-specific).
198 GlobalVariable *VAArgTLS;
199 /// \brief Thread-local shadow storage for va_arg overflow area
200 /// (x86_64-specific).
201 GlobalVariable *VAArgOverflowSizeTLS;
202 /// \brief Thread-local space used to pass origin value to the UMR reporting
204 GlobalVariable *OriginTLS;
206 /// \brief The run-time callback to print a warning.
208 /// \brief Run-time helper that copies origin info for a memory range.
209 Value *MsanCopyOriginFn;
210 /// \brief Run-time helper that generates a new origin value for a stack
212 Value *MsanSetAllocaOriginFn;
213 /// \brief Run-time helper that poisons stack on function entry.
214 Value *MsanPoisonStackFn;
215 /// \brief MSan runtime replacements for memmove, memcpy and memset.
216 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
218 /// \brief Address mask used in application-to-shadow address calculation.
219 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
221 /// \brief Offset of the origin shadow from the "normal" shadow.
222 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
223 uint64_t OriginOffset;
224 /// \brief Branch weights for error reporting.
225 MDNode *ColdCallWeights;
226 /// \brief Branch weights for origin store.
227 MDNode *OriginStoreWeights;
228 /// \bried Path to blacklist file.
229 SmallString<64> BlacklistFile;
230 /// \brief The blacklist.
231 OwningPtr<BlackList> BL;
232 /// \brief An empty volatile inline asm that prevents callback merge.
235 friend struct MemorySanitizerVisitor;
236 friend struct VarArgAMD64Helper;
240 char MemorySanitizer::ID = 0;
241 INITIALIZE_PASS(MemorySanitizer, "msan",
242 "MemorySanitizer: detects uninitialized reads.",
245 FunctionPass *llvm::createMemorySanitizerPass(bool TrackOrigins,
246 StringRef BlacklistFile) {
247 return new MemorySanitizer(TrackOrigins, BlacklistFile);
250 /// \brief Create a non-const global initialized with the given string.
252 /// Creates a writable global for Str so that we can pass it to the
253 /// run-time lib. Runtime uses first 4 bytes of the string to store the
254 /// frame ID, so the string needs to be mutable.
255 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
257 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
258 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
259 GlobalValue::PrivateLinkage, StrConst, "");
263 /// \brief Insert extern declaration of runtime-provided functions and globals.
264 void MemorySanitizer::initializeCallbacks(Module &M) {
265 // Only do this once.
270 // Create the callback.
271 // FIXME: this function should have "Cold" calling conv,
272 // which is not yet implemented.
273 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
274 : "__msan_warning_noreturn";
275 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
277 MsanCopyOriginFn = M.getOrInsertFunction(
278 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
279 IRB.getInt8PtrTy(), IntptrTy, NULL);
280 MsanSetAllocaOriginFn = M.getOrInsertFunction(
281 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
282 IRB.getInt8PtrTy(), NULL);
283 MsanPoisonStackFn = M.getOrInsertFunction(
284 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
285 MemmoveFn = M.getOrInsertFunction(
286 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
287 IRB.getInt8PtrTy(), IntptrTy, NULL);
288 MemcpyFn = M.getOrInsertFunction(
289 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
291 MemsetFn = M.getOrInsertFunction(
292 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
296 RetvalTLS = new GlobalVariable(
297 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
298 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
299 GlobalVariable::GeneralDynamicTLSModel);
300 RetvalOriginTLS = new GlobalVariable(
301 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
302 "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
304 ParamTLS = new GlobalVariable(
305 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
306 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
307 GlobalVariable::GeneralDynamicTLSModel);
308 ParamOriginTLS = new GlobalVariable(
309 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
310 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
312 VAArgTLS = new GlobalVariable(
313 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
314 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
315 GlobalVariable::GeneralDynamicTLSModel);
316 VAArgOverflowSizeTLS = new GlobalVariable(
317 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
318 "__msan_va_arg_overflow_size_tls", 0,
319 GlobalVariable::GeneralDynamicTLSModel);
320 OriginTLS = new GlobalVariable(
321 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
322 "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
324 // We insert an empty inline asm after __msan_report* to avoid callback merge.
325 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
326 StringRef(""), StringRef(""),
327 /*hasSideEffects=*/true);
330 /// \brief Module-level initialization.
332 /// inserts a call to __msan_init to the module's constructor list.
333 bool MemorySanitizer::doInitialization(Module &M) {
334 TD = getAnalysisIfAvailable<DataLayout>();
337 BL.reset(new BlackList(BlacklistFile));
338 C = &(M.getContext());
339 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
342 ShadowMask = kShadowMask64;
343 OriginOffset = kOriginOffset64;
346 ShadowMask = kShadowMask32;
347 OriginOffset = kOriginOffset32;
350 report_fatal_error("unsupported pointer size");
355 IntptrTy = IRB.getIntPtrTy(TD);
356 OriginTy = IRB.getInt32Ty();
358 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
359 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
361 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
362 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
363 "__msan_init", IRB.getVoidTy(), NULL)), 0);
365 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
366 IRB.getInt32(TrackOrigins), "__msan_track_origins");
368 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
369 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
376 /// \brief A helper class that handles instrumentation of VarArg
377 /// functions on a particular platform.
379 /// Implementations are expected to insert the instrumentation
380 /// necessary to propagate argument shadow through VarArg function
381 /// calls. Visit* methods are called during an InstVisitor pass over
382 /// the function, and should avoid creating new basic blocks. A new
383 /// instance of this class is created for each instrumented function.
384 struct VarArgHelper {
385 /// \brief Visit a CallSite.
386 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
388 /// \brief Visit a va_start call.
389 virtual void visitVAStartInst(VAStartInst &I) = 0;
391 /// \brief Visit a va_copy call.
392 virtual void visitVACopyInst(VACopyInst &I) = 0;
394 /// \brief Finalize function instrumentation.
396 /// This method is called after visiting all interesting (see above)
397 /// instructions in a function.
398 virtual void finalizeInstrumentation() = 0;
400 virtual ~VarArgHelper() {}
403 struct MemorySanitizerVisitor;
406 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
407 MemorySanitizerVisitor &Visitor);
409 /// This class does all the work for a given function. Store and Load
410 /// instructions store and load corresponding shadow and origin
411 /// values. Most instructions propagate shadow from arguments to their
412 /// return values. Certain instructions (most importantly, BranchInst)
413 /// test their argument shadow and print reports (with a runtime call) if it's
415 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
418 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
419 ValueMap<Value*, Value*> ShadowMap, OriginMap;
421 OwningPtr<VarArgHelper> VAHelper;
423 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
424 // See a comment in visitCallSite for more details.
425 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
426 static const unsigned AMD64FpEndOffset = 176;
428 struct ShadowOriginAndInsertPoint {
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) { }
436 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
437 SmallVector<Instruction*, 16> StoreList;
439 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
440 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
441 InsertChecks = !MS.BL->isIn(F);
442 DEBUG(if (!InsertChecks)
443 dbgs() << "MemorySanitizer is not inserting checks into '"
444 << F.getName() << "'\n");
447 void materializeStores() {
448 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
449 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
452 Value *Val = I.getValueOperand();
453 Value *Addr = I.getPointerOperand();
454 Value *Shadow = getShadow(Val);
455 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
458 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
459 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
462 if (ClCheckAccessAddress)
463 insertCheck(Addr, &I);
465 if (MS.TrackOrigins) {
466 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
467 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
468 IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB),
471 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
473 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
474 // TODO(eugenis): handle non-zero constant shadow by inserting an
475 // unconditional check (can not simply fail compilation as this could
476 // be in the dead code).
480 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
481 getCleanShadow(ConvertedShadow), "_mscmp");
482 Instruction *CheckTerm =
483 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
484 MS.OriginStoreWeights);
485 IRBuilder<> IRBNew(CheckTerm);
486 IRBNew.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRBNew),
493 void materializeChecks() {
494 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
495 Instruction *Shadow = InstrumentationList[i].Shadow;
496 Instruction *OrigIns = InstrumentationList[i].OrigIns;
497 IRBuilder<> IRB(OrigIns);
498 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
499 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
500 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
501 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
502 getCleanShadow(ConvertedShadow), "_mscmp");
503 Instruction *CheckTerm =
504 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
505 /* Unreachable */ !ClKeepGoing,
508 IRB.SetInsertPoint(CheckTerm);
509 if (MS.TrackOrigins) {
510 Instruction *Origin = InstrumentationList[i].Origin;
511 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
514 CallInst *Call = IRB.CreateCall(MS.WarningFn);
515 Call->setDebugLoc(OrigIns->getDebugLoc());
516 IRB.CreateCall(MS.EmptyAsm);
517 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
519 DEBUG(dbgs() << "DONE:\n" << F);
522 /// \brief Add MemorySanitizer instrumentation to a function.
523 bool runOnFunction() {
524 MS.initializeCallbacks(*F.getParent());
525 if (!MS.TD) return false;
527 // In the presence of unreachable blocks, we may see Phi nodes with
528 // incoming nodes from such blocks. Since InstVisitor skips unreachable
529 // blocks, such nodes will not have any shadow value associated with them.
530 // It's easier to remove unreachable blocks than deal with missing shadow.
531 removeUnreachableBlocks(F);
533 // Iterate all BBs in depth-first order and create shadow instructions
534 // for all instructions (where applicable).
535 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
536 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
537 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
538 BasicBlock *BB = *DI;
542 // Finalize PHI nodes.
543 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
544 PHINode *PN = ShadowPHINodes[i];
545 PHINode *PNS = cast<PHINode>(getShadow(PN));
546 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
547 size_t NumValues = PN->getNumIncomingValues();
548 for (size_t v = 0; v < NumValues; v++) {
549 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
551 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
555 VAHelper->finalizeInstrumentation();
557 // Delayed instrumentation of StoreInst.
558 // This may add new checks to be inserted later.
561 // Insert shadow value checks.
567 /// \brief Compute the shadow type that corresponds to a given Value.
568 Type *getShadowTy(Value *V) {
569 return getShadowTy(V->getType());
572 /// \brief Compute the shadow type that corresponds to a given Type.
573 Type *getShadowTy(Type *OrigTy) {
574 if (!OrigTy->isSized()) {
577 // For integer type, shadow is the same as the original type.
578 // This may return weird-sized types like i1.
579 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
581 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
582 uint32_t EltSize = MS.TD->getTypeSizeInBits(VT->getElementType());
583 return VectorType::get(IntegerType::get(*MS.C, EltSize),
584 VT->getNumElements());
586 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
587 SmallVector<Type*, 4> Elements;
588 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
589 Elements.push_back(getShadowTy(ST->getElementType(i)));
590 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
591 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
594 uint32_t TypeSize = MS.TD->getTypeSizeInBits(OrigTy);
595 return IntegerType::get(*MS.C, TypeSize);
598 /// \brief Flatten a vector type.
599 Type *getShadowTyNoVec(Type *ty) {
600 if (VectorType *vt = dyn_cast<VectorType>(ty))
601 return IntegerType::get(*MS.C, vt->getBitWidth());
605 /// \brief Convert a shadow value to it's flattened variant.
606 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
607 Type *Ty = V->getType();
608 Type *NoVecTy = getShadowTyNoVec(Ty);
609 if (Ty == NoVecTy) return V;
610 return IRB.CreateBitCast(V, NoVecTy);
613 /// \brief Compute the shadow address that corresponds to a given application
616 /// Shadow = Addr & ~ShadowMask.
617 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
620 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
621 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
622 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
625 /// \brief Compute the origin address that corresponds to a given application
628 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
629 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
631 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
632 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
634 IRB.CreateAdd(ShadowLong,
635 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
637 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
638 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
641 /// \brief Compute the shadow address for a given function argument.
643 /// Shadow = ParamTLS+ArgOffset.
644 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
646 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
647 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
648 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
652 /// \brief Compute the origin address for a given function argument.
653 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
655 if (!MS.TrackOrigins) return 0;
656 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
657 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
658 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
662 /// \brief Compute the shadow address for a retval.
663 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
664 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
665 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
669 /// \brief Compute the origin address for a retval.
670 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
671 // We keep a single origin for the entire retval. Might be too optimistic.
672 return MS.RetvalOriginTLS;
675 /// \brief Set SV to be the shadow value for V.
676 void setShadow(Value *V, Value *SV) {
677 assert(!ShadowMap.count(V) && "Values may only have one shadow");
681 /// \brief Set Origin to be the origin value for V.
682 void setOrigin(Value *V, Value *Origin) {
683 if (!MS.TrackOrigins) return;
684 assert(!OriginMap.count(V) && "Values may only have one origin");
685 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
686 OriginMap[V] = Origin;
689 /// \brief Create a clean shadow value for a given value.
691 /// Clean shadow (all zeroes) means all bits of the value are defined
693 Value *getCleanShadow(Value *V) {
694 Type *ShadowTy = getShadowTy(V);
697 return Constant::getNullValue(ShadowTy);
700 /// \brief Create a dirty shadow of a given shadow type.
701 Constant *getPoisonedShadow(Type *ShadowTy) {
703 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
704 return Constant::getAllOnesValue(ShadowTy);
705 StructType *ST = cast<StructType>(ShadowTy);
706 SmallVector<Constant *, 4> Vals;
707 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
708 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
709 return ConstantStruct::get(ST, Vals);
712 /// \brief Create a clean (zero) origin.
713 Value *getCleanOrigin() {
714 return Constant::getNullValue(MS.OriginTy);
717 /// \brief Get the shadow value for a given Value.
719 /// This function either returns the value set earlier with setShadow,
720 /// or extracts if from ParamTLS (for function arguments).
721 Value *getShadow(Value *V) {
722 if (Instruction *I = dyn_cast<Instruction>(V)) {
723 // For instructions the shadow is already stored in the map.
724 Value *Shadow = ShadowMap[V];
726 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
728 assert(Shadow && "No shadow for a value");
732 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
733 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
734 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
738 if (Argument *A = dyn_cast<Argument>(V)) {
739 // For arguments we compute the shadow on demand and store it in the map.
740 Value **ShadowPtr = &ShadowMap[V];
743 Function *F = A->getParent();
744 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
745 unsigned ArgOffset = 0;
746 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
748 if (!AI->getType()->isSized()) {
749 DEBUG(dbgs() << "Arg is not sized\n");
752 unsigned Size = AI->hasByValAttr()
753 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
754 : MS.TD->getTypeAllocSize(AI->getType());
756 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
757 if (AI->hasByValAttr()) {
758 // ByVal pointer itself has clean shadow. We copy the actual
759 // argument shadow to the underlying memory.
760 Value *Cpy = EntryIRB.CreateMemCpy(
761 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
762 Base, Size, AI->getParamAlignment());
763 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
765 *ShadowPtr = getCleanShadow(V);
767 *ShadowPtr = EntryIRB.CreateLoad(Base);
769 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
770 **ShadowPtr << "\n");
771 if (MS.TrackOrigins) {
772 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
773 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
776 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
778 assert(*ShadowPtr && "Could not find shadow for an argument");
781 // For everything else the shadow is zero.
782 return getCleanShadow(V);
785 /// \brief Get the shadow for i-th argument of the instruction I.
786 Value *getShadow(Instruction *I, int i) {
787 return getShadow(I->getOperand(i));
790 /// \brief Get the origin for a value.
791 Value *getOrigin(Value *V) {
792 if (!MS.TrackOrigins) return 0;
793 if (isa<Instruction>(V) || isa<Argument>(V)) {
794 Value *Origin = OriginMap[V];
796 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
797 Origin = getCleanOrigin();
801 return getCleanOrigin();
804 /// \brief Get the origin for i-th argument of the instruction I.
805 Value *getOrigin(Instruction *I, int i) {
806 return getOrigin(I->getOperand(i));
809 /// \brief Remember the place where a shadow check should be inserted.
811 /// This location will be later instrumented with a check that will print a
812 /// UMR warning in runtime if the value is not fully defined.
813 void insertCheck(Value *Val, Instruction *OrigIns) {
815 if (!InsertChecks) return;
816 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
819 Type *ShadowTy = Shadow->getType();
820 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
821 "Can only insert checks for integer and vector shadow types");
823 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
824 InstrumentationList.push_back(
825 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
828 // ------------------- Visitors.
830 /// \brief Instrument LoadInst
832 /// Loads the corresponding shadow and (optionally) origin.
833 /// Optionally, checks that the load address is fully defined.
834 void visitLoadInst(LoadInst &I) {
835 assert(I.getType()->isSized() && "Load type must have size");
837 Type *ShadowTy = getShadowTy(&I);
838 Value *Addr = I.getPointerOperand();
839 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
840 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
842 if (ClCheckAccessAddress)
843 insertCheck(I.getPointerOperand(), &I);
845 if (MS.TrackOrigins) {
846 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
847 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
851 /// \brief Instrument StoreInst
853 /// Stores the corresponding shadow and (optionally) origin.
854 /// Optionally, checks that the store address is fully defined.
855 void visitStoreInst(StoreInst &I) {
856 StoreList.push_back(&I);
859 // Vector manipulation.
860 void visitExtractElementInst(ExtractElementInst &I) {
861 insertCheck(I.getOperand(1), &I);
863 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
865 setOrigin(&I, getOrigin(&I, 0));
868 void visitInsertElementInst(InsertElementInst &I) {
869 insertCheck(I.getOperand(2), &I);
871 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
872 I.getOperand(2), "_msprop"));
873 setOriginForNaryOp(I);
876 void visitShuffleVectorInst(ShuffleVectorInst &I) {
877 insertCheck(I.getOperand(2), &I);
879 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
880 I.getOperand(2), "_msprop"));
881 setOriginForNaryOp(I);
885 void visitSExtInst(SExtInst &I) {
887 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
888 setOrigin(&I, getOrigin(&I, 0));
891 void visitZExtInst(ZExtInst &I) {
893 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
894 setOrigin(&I, getOrigin(&I, 0));
897 void visitTruncInst(TruncInst &I) {
899 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
900 setOrigin(&I, getOrigin(&I, 0));
903 void visitBitCastInst(BitCastInst &I) {
905 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
906 setOrigin(&I, getOrigin(&I, 0));
909 void visitPtrToIntInst(PtrToIntInst &I) {
911 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
912 "_msprop_ptrtoint"));
913 setOrigin(&I, getOrigin(&I, 0));
916 void visitIntToPtrInst(IntToPtrInst &I) {
918 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
919 "_msprop_inttoptr"));
920 setOrigin(&I, getOrigin(&I, 0));
923 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
924 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
925 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
926 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
927 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
928 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
930 /// \brief Propagate shadow for bitwise AND.
932 /// This code is exact, i.e. if, for example, a bit in the left argument
933 /// is defined and 0, then neither the value not definedness of the
934 /// corresponding bit in B don't affect the resulting shadow.
935 void visitAnd(BinaryOperator &I) {
937 // "And" of 0 and a poisoned value results in unpoisoned value.
938 // 1&1 => 1; 0&1 => 0; p&1 => p;
939 // 1&0 => 0; 0&0 => 0; p&0 => 0;
940 // 1&p => p; 0&p => 0; p&p => p;
941 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
942 Value *S1 = getShadow(&I, 0);
943 Value *S2 = getShadow(&I, 1);
944 Value *V1 = I.getOperand(0);
945 Value *V2 = I.getOperand(1);
946 if (V1->getType() != S1->getType()) {
947 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
948 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
950 Value *S1S2 = IRB.CreateAnd(S1, S2);
951 Value *V1S2 = IRB.CreateAnd(V1, S2);
952 Value *S1V2 = IRB.CreateAnd(S1, V2);
953 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
954 setOriginForNaryOp(I);
957 void visitOr(BinaryOperator &I) {
959 // "Or" of 1 and a poisoned value results in unpoisoned value.
960 // 1|1 => 1; 0|1 => 1; p|1 => 1;
961 // 1|0 => 1; 0|0 => 0; p|0 => p;
962 // 1|p => 1; 0|p => p; p|p => p;
963 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
964 Value *S1 = getShadow(&I, 0);
965 Value *S2 = getShadow(&I, 1);
966 Value *V1 = IRB.CreateNot(I.getOperand(0));
967 Value *V2 = IRB.CreateNot(I.getOperand(1));
968 if (V1->getType() != S1->getType()) {
969 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
970 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
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);
979 /// \brief Default propagation of shadow and/or origin.
981 /// This class implements the general case of shadow propagation, used in all
982 /// cases where we don't know and/or don't care about what the operation
983 /// actually does. It converts all input shadow values to a common type
984 /// (extending or truncating as necessary), and bitwise OR's them.
986 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
987 /// fully initialized), and less prone to false positives.
989 /// This class also implements the general case of origin propagation. For a
990 /// Nary operation, result origin is set to the origin of an argument that is
991 /// not entirely initialized. If there is more than one such arguments, the
992 /// rightmost of them is picked. It does not matter which one is picked if all
993 /// arguments are initialized.
994 template <bool CombineShadow>
999 MemorySanitizerVisitor *MSV;
1002 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1003 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
1005 /// \brief Add a pair of shadow and origin values to the mix.
1006 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1007 if (CombineShadow) {
1012 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1013 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1017 if (MSV->MS.TrackOrigins) {
1022 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1023 Value *Cond = IRB.CreateICmpNE(FlatShadow,
1024 MSV->getCleanShadow(FlatShadow));
1025 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1031 /// \brief Add an application value to the mix.
1032 Combiner &Add(Value *V) {
1033 Value *OpShadow = MSV->getShadow(V);
1034 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
1035 return Add(OpShadow, OpOrigin);
1038 /// \brief Set the current combined values as the given instruction's shadow
1040 void Done(Instruction *I) {
1041 if (CombineShadow) {
1043 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1044 MSV->setShadow(I, Shadow);
1046 if (MSV->MS.TrackOrigins) {
1048 MSV->setOrigin(I, Origin);
1053 typedef Combiner<true> ShadowAndOriginCombiner;
1054 typedef Combiner<false> OriginCombiner;
1056 /// \brief Propagate origin for arbitrary operation.
1057 void setOriginForNaryOp(Instruction &I) {
1058 if (!MS.TrackOrigins) return;
1059 IRBuilder<> IRB(&I);
1060 OriginCombiner OC(this, IRB);
1061 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1066 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1067 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1068 "Vector of pointers is not a valid shadow type");
1069 return Ty->isVectorTy() ?
1070 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1071 Ty->getPrimitiveSizeInBits();
1074 /// \brief Cast between two shadow types, extending or truncating as
1076 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1077 Type *srcTy = V->getType();
1078 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1079 return IRB.CreateIntCast(V, dstTy, false);
1080 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1081 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1082 return IRB.CreateIntCast(V, dstTy, false);
1083 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1084 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1085 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1087 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1088 return IRB.CreateBitCast(V2, dstTy);
1089 // TODO: handle struct types.
1092 /// \brief Propagate shadow for arbitrary operation.
1093 void handleShadowOr(Instruction &I) {
1094 IRBuilder<> IRB(&I);
1095 ShadowAndOriginCombiner SC(this, IRB);
1096 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1101 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1102 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1103 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1104 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1105 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1106 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1107 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1109 void handleDiv(Instruction &I) {
1110 IRBuilder<> IRB(&I);
1111 // Strict on the second argument.
1112 insertCheck(I.getOperand(1), &I);
1113 setShadow(&I, getShadow(&I, 0));
1114 setOrigin(&I, getOrigin(&I, 0));
1117 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1118 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1119 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1120 void visitURem(BinaryOperator &I) { handleDiv(I); }
1121 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1122 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1124 /// \brief Instrument == and != comparisons.
1126 /// Sometimes the comparison result is known even if some of the bits of the
1127 /// arguments are not.
1128 void handleEqualityComparison(ICmpInst &I) {
1129 IRBuilder<> IRB(&I);
1130 Value *A = I.getOperand(0);
1131 Value *B = I.getOperand(1);
1132 Value *Sa = getShadow(A);
1133 Value *Sb = getShadow(B);
1135 // Get rid of pointers and vectors of pointers.
1136 // For ints (and vectors of ints), types of A and Sa match,
1137 // and this is a no-op.
1138 A = IRB.CreatePointerCast(A, Sa->getType());
1139 B = IRB.CreatePointerCast(B, Sb->getType());
1141 // A == B <==> (C = A^B) == 0
1142 // A != B <==> (C = A^B) != 0
1144 Value *C = IRB.CreateXor(A, B);
1145 Value *Sc = IRB.CreateOr(Sa, Sb);
1146 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1147 // Result is defined if one of the following is true
1148 // * there is a defined 1 bit in C
1149 // * C is fully defined
1150 // Si = !(C & ~Sc) && Sc
1151 Value *Zero = Constant::getNullValue(Sc->getType());
1152 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1154 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1156 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1157 Si->setName("_msprop_icmp");
1159 setOriginForNaryOp(I);
1162 /// \brief Build the lowest possible value of V, taking into account V's
1163 /// uninitialized bits.
1164 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1167 // Split shadow into sign bit and other bits.
1168 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1169 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1170 // Maximise the undefined shadow bit, minimize other undefined bits.
1172 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1174 // Minimize undefined bits.
1175 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1179 /// \brief Build the highest possible value of V, taking into account V's
1180 /// uninitialized bits.
1181 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1184 // Split shadow into sign bit and other bits.
1185 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1186 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1187 // Minimise the undefined shadow bit, maximise other undefined bits.
1189 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1191 // Maximize undefined bits.
1192 return IRB.CreateOr(A, Sa);
1196 /// \brief Instrument relational comparisons.
1198 /// This function does exact shadow propagation for all relational
1199 /// comparisons of integers, pointers and vectors of those.
1200 /// FIXME: output seems suboptimal when one of the operands is a constant
1201 void handleRelationalComparisonExact(ICmpInst &I) {
1202 IRBuilder<> IRB(&I);
1203 Value *A = I.getOperand(0);
1204 Value *B = I.getOperand(1);
1205 Value *Sa = getShadow(A);
1206 Value *Sb = getShadow(B);
1208 // Get rid of pointers and vectors of pointers.
1209 // For ints (and vectors of ints), types of A and Sa match,
1210 // and this is a no-op.
1211 A = IRB.CreatePointerCast(A, Sa->getType());
1212 B = IRB.CreatePointerCast(B, Sb->getType());
1214 // Let [a0, a1] be the interval of possible values of A, taking into account
1215 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1216 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1217 bool IsSigned = I.isSigned();
1218 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1219 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1220 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1221 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1222 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1223 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1224 Value *Si = IRB.CreateXor(S1, S2);
1226 setOriginForNaryOp(I);
1229 /// \brief Instrument signed relational comparisons.
1231 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1232 /// propagating the highest bit of the shadow. Everything else is delegated
1233 /// to handleShadowOr().
1234 void handleSignedRelationalComparison(ICmpInst &I) {
1235 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1236 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1238 CmpInst::Predicate pre = I.getPredicate();
1239 if (constOp0 && constOp0->isNullValue() &&
1240 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1241 op = I.getOperand(1);
1242 } else if (constOp1 && constOp1->isNullValue() &&
1243 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1244 op = I.getOperand(0);
1247 IRBuilder<> IRB(&I);
1249 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1250 setShadow(&I, Shadow);
1251 setOrigin(&I, getOrigin(op));
1257 void visitICmpInst(ICmpInst &I) {
1258 if (!ClHandleICmp) {
1262 if (I.isEquality()) {
1263 handleEqualityComparison(I);
1267 assert(I.isRelational());
1268 if (ClHandleICmpExact) {
1269 handleRelationalComparisonExact(I);
1273 handleSignedRelationalComparison(I);
1277 assert(I.isUnsigned());
1278 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1279 handleRelationalComparisonExact(I);
1286 void visitFCmpInst(FCmpInst &I) {
1290 void handleShift(BinaryOperator &I) {
1291 IRBuilder<> IRB(&I);
1292 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1293 // Otherwise perform the same shift on S1.
1294 Value *S1 = getShadow(&I, 0);
1295 Value *S2 = getShadow(&I, 1);
1296 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1298 Value *V2 = I.getOperand(1);
1299 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1300 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1301 setOriginForNaryOp(I);
1304 void visitShl(BinaryOperator &I) { handleShift(I); }
1305 void visitAShr(BinaryOperator &I) { handleShift(I); }
1306 void visitLShr(BinaryOperator &I) { handleShift(I); }
1308 /// \brief Instrument llvm.memmove
1310 /// At this point we don't know if llvm.memmove will be inlined or not.
1311 /// If we don't instrument it and it gets inlined,
1312 /// our interceptor will not kick in and we will lose the memmove.
1313 /// If we instrument the call here, but it does not get inlined,
1314 /// we will memove the shadow twice: which is bad in case
1315 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1317 /// Similar situation exists for memcpy and memset.
1318 void visitMemMoveInst(MemMoveInst &I) {
1319 IRBuilder<> IRB(&I);
1322 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1323 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1324 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1325 I.eraseFromParent();
1328 // Similar to memmove: avoid copying shadow twice.
1329 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1330 // FIXME: consider doing manual inline for small constant sizes and proper
1332 void visitMemCpyInst(MemCpyInst &I) {
1333 IRBuilder<> IRB(&I);
1336 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1337 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1338 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1339 I.eraseFromParent();
1343 void visitMemSetInst(MemSetInst &I) {
1344 IRBuilder<> IRB(&I);
1347 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1348 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1349 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1350 I.eraseFromParent();
1353 void visitVAStartInst(VAStartInst &I) {
1354 VAHelper->visitVAStartInst(I);
1357 void visitVACopyInst(VACopyInst &I) {
1358 VAHelper->visitVACopyInst(I);
1361 enum IntrinsicKind {
1362 IK_DoesNotAccessMemory,
1367 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1368 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1369 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1370 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1371 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1372 const int UnknownModRefBehavior = IK_WritesMemory;
1373 #define GET_INTRINSIC_MODREF_BEHAVIOR
1374 #define ModRefBehavior IntrinsicKind
1375 #include "llvm/IR/Intrinsics.gen"
1376 #undef ModRefBehavior
1377 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1380 /// \brief Handle vector store-like intrinsics.
1382 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1383 /// has 1 pointer argument and 1 vector argument, returns void.
1384 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1385 IRBuilder<> IRB(&I);
1386 Value* Addr = I.getArgOperand(0);
1387 Value *Shadow = getShadow(&I, 1);
1388 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1390 // We don't know the pointer alignment (could be unaligned SSE store!).
1391 // Have to assume to worst case.
1392 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1394 if (ClCheckAccessAddress)
1395 insertCheck(Addr, &I);
1397 // FIXME: use ClStoreCleanOrigin
1398 // FIXME: factor out common code from materializeStores
1399 if (MS.TrackOrigins)
1400 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1404 /// \brief Handle vector load-like intrinsics.
1406 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1407 /// has 1 pointer argument, returns a vector.
1408 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1409 IRBuilder<> IRB(&I);
1410 Value *Addr = I.getArgOperand(0);
1412 Type *ShadowTy = getShadowTy(&I);
1413 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1414 // We don't know the pointer alignment (could be unaligned SSE load!).
1415 // Have to assume to worst case.
1416 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1418 if (ClCheckAccessAddress)
1419 insertCheck(Addr, &I);
1421 if (MS.TrackOrigins)
1422 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1426 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1428 /// Instrument intrinsics with any number of arguments of the same type,
1429 /// equal to the return type. The type should be simple (no aggregates or
1430 /// pointers; vectors are fine).
1431 /// Caller guarantees that this intrinsic does not access memory.
1432 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1433 Type *RetTy = I.getType();
1434 if (!(RetTy->isIntOrIntVectorTy() ||
1435 RetTy->isFPOrFPVectorTy() ||
1436 RetTy->isX86_MMXTy()))
1439 unsigned NumArgOperands = I.getNumArgOperands();
1441 for (unsigned i = 0; i < NumArgOperands; ++i) {
1442 Type *Ty = I.getArgOperand(i)->getType();
1447 IRBuilder<> IRB(&I);
1448 ShadowAndOriginCombiner SC(this, IRB);
1449 for (unsigned i = 0; i < NumArgOperands; ++i)
1450 SC.Add(I.getArgOperand(i));
1456 /// \brief Heuristically instrument unknown intrinsics.
1458 /// The main purpose of this code is to do something reasonable with all
1459 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1460 /// We recognize several classes of intrinsics by their argument types and
1461 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1462 /// sure that we know what the intrinsic does.
1464 /// We special-case intrinsics where this approach fails. See llvm.bswap
1465 /// handling as an example of that.
1466 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1467 unsigned NumArgOperands = I.getNumArgOperands();
1468 if (NumArgOperands == 0)
1471 Intrinsic::ID iid = I.getIntrinsicID();
1472 IntrinsicKind IK = getIntrinsicKind(iid);
1473 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1474 bool WritesMemory = IK == IK_WritesMemory;
1475 assert(!(OnlyReadsMemory && WritesMemory));
1477 if (NumArgOperands == 2 &&
1478 I.getArgOperand(0)->getType()->isPointerTy() &&
1479 I.getArgOperand(1)->getType()->isVectorTy() &&
1480 I.getType()->isVoidTy() &&
1482 // This looks like a vector store.
1483 return handleVectorStoreIntrinsic(I);
1486 if (NumArgOperands == 1 &&
1487 I.getArgOperand(0)->getType()->isPointerTy() &&
1488 I.getType()->isVectorTy() &&
1490 // This looks like a vector load.
1491 return handleVectorLoadIntrinsic(I);
1494 if (!OnlyReadsMemory && !WritesMemory)
1495 if (maybeHandleSimpleNomemIntrinsic(I))
1498 // FIXME: detect and handle SSE maskstore/maskload
1502 void handleBswap(IntrinsicInst &I) {
1503 IRBuilder<> IRB(&I);
1504 Value *Op = I.getArgOperand(0);
1505 Type *OpType = Op->getType();
1506 Function *BswapFunc = Intrinsic::getDeclaration(
1507 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1508 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1509 setOrigin(&I, getOrigin(Op));
1512 void visitIntrinsicInst(IntrinsicInst &I) {
1513 switch (I.getIntrinsicID()) {
1514 case llvm::Intrinsic::bswap:
1518 if (!handleUnknownIntrinsic(I))
1519 visitInstruction(I);
1524 void visitCallSite(CallSite CS) {
1525 Instruction &I = *CS.getInstruction();
1526 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1528 CallInst *Call = cast<CallInst>(&I);
1530 // For inline asm, do the usual thing: check argument shadow and mark all
1531 // outputs as clean. Note that any side effects of the inline asm that are
1532 // not immediately visible in its constraints are not handled.
1533 if (Call->isInlineAsm()) {
1534 visitInstruction(I);
1538 // Allow only tail calls with the same types, otherwise
1539 // we may have a false positive: shadow for a non-void RetVal
1540 // will get propagated to a void RetVal.
1541 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1542 Call->setTailCall(false);
1544 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1546 // We are going to insert code that relies on the fact that the callee
1547 // will become a non-readonly function after it is instrumented by us. To
1548 // prevent this code from being optimized out, mark that function
1549 // non-readonly in advance.
1550 if (Function *Func = Call->getCalledFunction()) {
1551 // Clear out readonly/readnone attributes.
1553 B.addAttribute(Attribute::ReadOnly)
1554 .addAttribute(Attribute::ReadNone);
1555 Func->removeAttributes(AttributeSet::FunctionIndex,
1556 AttributeSet::get(Func->getContext(),
1557 AttributeSet::FunctionIndex,
1561 IRBuilder<> IRB(&I);
1562 unsigned ArgOffset = 0;
1563 DEBUG(dbgs() << " CallSite: " << I << "\n");
1564 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1565 ArgIt != End; ++ArgIt) {
1567 unsigned i = ArgIt - CS.arg_begin();
1568 if (!A->getType()->isSized()) {
1569 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1574 // Compute the Shadow for arg even if it is ByVal, because
1575 // in that case getShadow() will copy the actual arg shadow to
1576 // __msan_param_tls.
1577 Value *ArgShadow = getShadow(A);
1578 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1579 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1580 " Shadow: " << *ArgShadow << "\n");
1581 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
1582 assert(A->getType()->isPointerTy() &&
1583 "ByVal argument is not a pointer!");
1584 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1585 unsigned Alignment = CS.getParamAlignment(i + 1);
1586 Store = IRB.CreateMemCpy(ArgShadowBase,
1587 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1590 Size = MS.TD->getTypeAllocSize(A->getType());
1591 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1592 kShadowTLSAlignment);
1594 if (MS.TrackOrigins)
1595 IRB.CreateStore(getOrigin(A),
1596 getOriginPtrForArgument(A, IRB, ArgOffset));
1598 assert(Size != 0 && Store != 0);
1599 DEBUG(dbgs() << " Param:" << *Store << "\n");
1600 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1602 DEBUG(dbgs() << " done with call args\n");
1605 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1606 if (FT->isVarArg()) {
1607 VAHelper->visitCallSite(CS, IRB);
1610 // Now, get the shadow for the RetVal.
1611 if (!I.getType()->isSized()) return;
1612 IRBuilder<> IRBBefore(&I);
1613 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1614 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1615 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
1616 Instruction *NextInsn = 0;
1618 NextInsn = I.getNextNode();
1620 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1621 if (!NormalDest->getSinglePredecessor()) {
1622 // FIXME: this case is tricky, so we are just conservative here.
1623 // Perhaps we need to split the edge between this BB and NormalDest,
1624 // but a naive attempt to use SplitEdge leads to a crash.
1625 setShadow(&I, getCleanShadow(&I));
1626 setOrigin(&I, getCleanOrigin());
1629 NextInsn = NormalDest->getFirstInsertionPt();
1631 "Could not find insertion point for retval shadow load");
1633 IRBuilder<> IRBAfter(NextInsn);
1634 Value *RetvalShadow =
1635 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1636 kShadowTLSAlignment, "_msret");
1637 setShadow(&I, RetvalShadow);
1638 if (MS.TrackOrigins)
1639 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1642 void visitReturnInst(ReturnInst &I) {
1643 IRBuilder<> IRB(&I);
1644 if (Value *RetVal = I.getReturnValue()) {
1645 // Set the shadow for the RetVal.
1646 Value *Shadow = getShadow(RetVal);
1647 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1648 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
1649 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1650 if (MS.TrackOrigins)
1651 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1655 void visitPHINode(PHINode &I) {
1656 IRBuilder<> IRB(&I);
1657 ShadowPHINodes.push_back(&I);
1658 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1660 if (MS.TrackOrigins)
1661 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1665 void visitAllocaInst(AllocaInst &I) {
1666 setShadow(&I, getCleanShadow(&I));
1667 if (!ClPoisonStack) return;
1668 IRBuilder<> IRB(I.getNextNode());
1669 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1670 if (ClPoisonStackWithCall) {
1671 IRB.CreateCall2(MS.MsanPoisonStackFn,
1672 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1673 ConstantInt::get(MS.IntptrTy, Size));
1675 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1676 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1677 Size, I.getAlignment());
1680 if (MS.TrackOrigins) {
1681 setOrigin(&I, getCleanOrigin());
1682 SmallString<2048> StackDescriptionStorage;
1683 raw_svector_ostream StackDescription(StackDescriptionStorage);
1684 // We create a string with a description of the stack allocation and
1685 // pass it into __msan_set_alloca_origin.
1686 // It will be printed by the run-time if stack-originated UMR is found.
1687 // The first 4 bytes of the string are set to '----' and will be replaced
1688 // by __msan_va_arg_overflow_size_tls at the first call.
1689 StackDescription << "----" << I.getName() << "@" << F.getName();
1691 createPrivateNonConstGlobalForString(*F.getParent(),
1692 StackDescription.str());
1693 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1694 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1695 ConstantInt::get(MS.IntptrTy, Size),
1696 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1700 void visitSelectInst(SelectInst& I) {
1701 IRBuilder<> IRB(&I);
1702 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1703 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1705 if (MS.TrackOrigins) {
1706 // Origins are always i32, so any vector conditions must be flattened.
1707 // FIXME: consider tracking vector origins for app vectors?
1708 Value *Cond = I.getCondition();
1709 if (Cond->getType()->isVectorTy()) {
1710 Value *ConvertedShadow = convertToShadowTyNoVec(Cond, IRB);
1711 Cond = IRB.CreateICmpNE(ConvertedShadow,
1712 getCleanShadow(ConvertedShadow), "_mso_select");
1714 setOrigin(&I, IRB.CreateSelect(Cond,
1715 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1719 void visitLandingPadInst(LandingPadInst &I) {
1721 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1722 setShadow(&I, getCleanShadow(&I));
1723 setOrigin(&I, getCleanOrigin());
1726 void visitGetElementPtrInst(GetElementPtrInst &I) {
1730 void visitExtractValueInst(ExtractValueInst &I) {
1731 IRBuilder<> IRB(&I);
1732 Value *Agg = I.getAggregateOperand();
1733 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1734 Value *AggShadow = getShadow(Agg);
1735 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1736 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1737 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1738 setShadow(&I, ResShadow);
1739 setOrigin(&I, getCleanOrigin());
1742 void visitInsertValueInst(InsertValueInst &I) {
1743 IRBuilder<> IRB(&I);
1744 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1745 Value *AggShadow = getShadow(I.getAggregateOperand());
1746 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1747 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1748 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1749 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1750 DEBUG(dbgs() << " Res: " << *Res << "\n");
1752 setOrigin(&I, getCleanOrigin());
1755 void dumpInst(Instruction &I) {
1756 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1757 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1759 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1761 errs() << "QQQ " << I << "\n";
1764 void visitResumeInst(ResumeInst &I) {
1765 DEBUG(dbgs() << "Resume: " << I << "\n");
1766 // Nothing to do here.
1769 void visitInstruction(Instruction &I) {
1770 // Everything else: stop propagating and check for poisoned shadow.
1771 if (ClDumpStrictInstructions)
1773 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1774 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1775 insertCheck(I.getOperand(i), &I);
1776 setShadow(&I, getCleanShadow(&I));
1777 setOrigin(&I, getCleanOrigin());
1781 /// \brief AMD64-specific implementation of VarArgHelper.
1782 struct VarArgAMD64Helper : public VarArgHelper {
1783 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1784 // See a comment in visitCallSite for more details.
1785 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
1786 static const unsigned AMD64FpEndOffset = 176;
1789 MemorySanitizer &MS;
1790 MemorySanitizerVisitor &MSV;
1791 Value *VAArgTLSCopy;
1792 Value *VAArgOverflowSize;
1794 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1796 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1797 MemorySanitizerVisitor &MSV)
1798 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1800 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1802 ArgKind classifyArgument(Value* arg) {
1803 // A very rough approximation of X86_64 argument classification rules.
1804 Type *T = arg->getType();
1805 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1806 return AK_FloatingPoint;
1807 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1808 return AK_GeneralPurpose;
1809 if (T->isPointerTy())
1810 return AK_GeneralPurpose;
1814 // For VarArg functions, store the argument shadow in an ABI-specific format
1815 // that corresponds to va_list layout.
1816 // We do this because Clang lowers va_arg in the frontend, and this pass
1817 // only sees the low level code that deals with va_list internals.
1818 // A much easier alternative (provided that Clang emits va_arg instructions)
1819 // would have been to associate each live instance of va_list with a copy of
1820 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1822 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1823 unsigned GpOffset = 0;
1824 unsigned FpOffset = AMD64GpEndOffset;
1825 unsigned OverflowOffset = AMD64FpEndOffset;
1826 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1827 ArgIt != End; ++ArgIt) {
1829 ArgKind AK = classifyArgument(A);
1830 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1832 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1836 case AK_GeneralPurpose:
1837 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1840 case AK_FloatingPoint:
1841 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1845 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1846 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1847 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1849 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
1851 Constant *OverflowSize =
1852 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1853 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1856 /// \brief Compute the shadow address for a given va_arg.
1857 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1859 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1860 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1861 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1865 void visitVAStartInst(VAStartInst &I) {
1866 IRBuilder<> IRB(&I);
1867 VAStartInstrumentationList.push_back(&I);
1868 Value *VAListTag = I.getArgOperand(0);
1869 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1871 // Unpoison the whole __va_list_tag.
1872 // FIXME: magic ABI constants.
1873 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1874 /* size */24, /* alignment */8, false);
1877 void visitVACopyInst(VACopyInst &I) {
1878 IRBuilder<> IRB(&I);
1879 Value *VAListTag = I.getArgOperand(0);
1880 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1882 // Unpoison the whole __va_list_tag.
1883 // FIXME: magic ABI constants.
1884 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1885 /* size */24, /* alignment */8, false);
1888 void finalizeInstrumentation() {
1889 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1890 "finalizeInstrumentation called twice");
1891 if (!VAStartInstrumentationList.empty()) {
1892 // If there is a va_start in this function, make a backup copy of
1893 // va_arg_tls somewhere in the function entry block.
1894 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1895 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1897 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1899 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1900 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1903 // Instrument va_start.
1904 // Copy va_list shadow from the backup copy of the TLS contents.
1905 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1906 CallInst *OrigInst = VAStartInstrumentationList[i];
1907 IRBuilder<> IRB(OrigInst->getNextNode());
1908 Value *VAListTag = OrigInst->getArgOperand(0);
1910 Value *RegSaveAreaPtrPtr =
1912 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1913 ConstantInt::get(MS.IntptrTy, 16)),
1914 Type::getInt64PtrTy(*MS.C));
1915 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1916 Value *RegSaveAreaShadowPtr =
1917 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1918 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1919 AMD64FpEndOffset, 16);
1921 Value *OverflowArgAreaPtrPtr =
1923 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1924 ConstantInt::get(MS.IntptrTy, 8)),
1925 Type::getInt64PtrTy(*MS.C));
1926 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1927 Value *OverflowArgAreaShadowPtr =
1928 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1930 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1931 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1936 VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1937 MemorySanitizerVisitor &Visitor) {
1938 return new VarArgAMD64Helper(Func, Msan, Visitor);
1943 bool MemorySanitizer::runOnFunction(Function &F) {
1944 MemorySanitizerVisitor Visitor(F, *this);
1946 // Clear out readonly/readnone attributes.
1948 B.addAttribute(Attribute::ReadOnly)
1949 .addAttribute(Attribute::ReadNone);
1950 F.removeAttributes(AttributeSet::FunctionIndex,
1951 AttributeSet::get(F.getContext(),
1952 AttributeSet::FunctionIndex, B));
1954 return Visitor.runOnFunction();