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).
46 //===----------------------------------------------------------------------===//
48 #define DEBUG_TYPE "msan"
50 #include "llvm/Transforms/Instrumentation.h"
51 #include "BlackList.h"
52 #include "llvm/ADT/DepthFirstIterator.h"
53 #include "llvm/ADT/SmallString.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/ValueMap.h"
56 #include "llvm/DataLayout.h"
57 #include "llvm/Function.h"
58 #include "llvm/IRBuilder.h"
59 #include "llvm/InlineAsm.h"
60 #include "llvm/InstVisitor.h"
61 #include "llvm/IntrinsicInst.h"
62 #include "llvm/LLVMContext.h"
63 #include "llvm/MDBuilder.h"
64 #include "llvm/Module.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Compiler.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
70 #include "llvm/Transforms/Utils/ModuleUtils.h"
71 #include "llvm/Type.h"
75 static const uint64_t kShadowMask32 = 1ULL << 31;
76 static const uint64_t kShadowMask64 = 1ULL << 46;
77 static const uint64_t kOriginOffset32 = 1ULL << 30;
78 static const uint64_t kOriginOffset64 = 1ULL << 45;
79 static const uint64_t kShadowTLSAlignment = 8;
81 // This is an important flag that makes the reports much more
82 // informative at the cost of greater slowdown. Not fully implemented
84 // FIXME: this should be a top-level clang flag, e.g.
85 // -fmemory-sanitizer-full.
86 static cl::opt<bool> ClTrackOrigins("msan-track-origins",
87 cl::desc("Track origins (allocation sites) of poisoned memory"),
88 cl::Hidden, cl::init(false));
89 static cl::opt<bool> ClKeepGoing("msan-keep-going",
90 cl::desc("keep going after reporting a UMR"),
91 cl::Hidden, cl::init(false));
92 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
93 cl::desc("poison uninitialized stack variables"),
94 cl::Hidden, cl::init(true));
95 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
96 cl::desc("poison uninitialized stack variables with a call"),
97 cl::Hidden, cl::init(false));
98 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
99 cl::desc("poison uninitialized stack variables with the given patter"),
100 cl::Hidden, cl::init(0xff));
102 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
103 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
104 cl::Hidden, cl::init(true));
106 static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
107 cl::desc("store origin for clean (fully initialized) values"),
108 cl::Hidden, cl::init(false));
110 // This flag controls whether we check the shadow of the address
111 // operand of load or store. Such bugs are very rare, since load from
112 // a garbage address typically results in SEGV, but still happen
113 // (e.g. only lower bits of address are garbage, or the access happens
114 // early at program startup where malloc-ed memory is more likely to
115 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
116 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
117 cl::desc("report accesses through a pointer which has poisoned shadow"),
118 cl::Hidden, cl::init(true));
120 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
121 cl::desc("print out instructions with default strict semantics"),
122 cl::Hidden, cl::init(false));
124 static cl::opt<std::string> ClBlackListFile("msan-blacklist",
125 cl::desc("File containing the list of functions where MemorySanitizer "
126 "should not report bugs"), cl::Hidden);
130 /// \brief An instrumentation pass implementing detection of uninitialized
133 /// MemorySanitizer: instrument the code in module to find
134 /// uninitialized reads.
135 class MemorySanitizer : public FunctionPass {
137 MemorySanitizer(bool TrackOrigins = false)
139 TrackOrigins(TrackOrigins || ClTrackOrigins),
142 const char *getPassName() const { return "MemorySanitizer"; }
143 bool runOnFunction(Function &F);
144 bool doInitialization(Module &M);
145 static char ID; // Pass identification, replacement for typeid.
148 void initializeCallbacks(Module &M);
150 /// \brief Track origins (allocation points) of uninitialized values.
157 /// \brief Thread-local shadow storage for function parameters.
158 GlobalVariable *ParamTLS;
159 /// \brief Thread-local origin storage for function parameters.
160 GlobalVariable *ParamOriginTLS;
161 /// \brief Thread-local shadow storage for function return value.
162 GlobalVariable *RetvalTLS;
163 /// \brief Thread-local origin storage for function return value.
164 GlobalVariable *RetvalOriginTLS;
165 /// \brief Thread-local shadow storage for in-register va_arg function
166 /// parameters (x86_64-specific).
167 GlobalVariable *VAArgTLS;
168 /// \brief Thread-local shadow storage for va_arg overflow area
169 /// (x86_64-specific).
170 GlobalVariable *VAArgOverflowSizeTLS;
171 /// \brief Thread-local space used to pass origin value to the UMR reporting
173 GlobalVariable *OriginTLS;
175 /// \brief The run-time callback to print a warning.
177 /// \brief Run-time helper that copies origin info for a memory range.
178 Value *MsanCopyOriginFn;
179 /// \brief Run-time helper that generates a new origin value for a stack
181 Value *MsanSetAllocaOriginFn;
182 /// \brief Run-time helper that poisons stack on function entry.
183 Value *MsanPoisonStackFn;
184 /// \brief MSan runtime replacements for memmove, memcpy and memset.
185 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
187 /// \brief Address mask used in application-to-shadow address calculation.
188 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
190 /// \brief Offset of the origin shadow from the "normal" shadow.
191 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
192 uint64_t OriginOffset;
193 /// \brief Branch weights for error reporting.
194 MDNode *ColdCallWeights;
195 /// \brief Branch weights for origin store.
196 MDNode *OriginStoreWeights;
197 /// \brief The blacklist.
198 OwningPtr<BlackList> BL;
199 /// \brief An empty volatile inline asm that prevents callback merge.
202 friend struct MemorySanitizerVisitor;
203 friend struct VarArgAMD64Helper;
207 char MemorySanitizer::ID = 0;
208 INITIALIZE_PASS(MemorySanitizer, "msan",
209 "MemorySanitizer: detects uninitialized reads.",
212 FunctionPass *llvm::createMemorySanitizerPass(bool TrackOrigins) {
213 return new MemorySanitizer(TrackOrigins);
216 /// \brief Create a non-const global initialized with the given string.
218 /// Creates a writable global for Str so that we can pass it to the
219 /// run-time lib. Runtime uses first 4 bytes of the string to store the
220 /// frame ID, so the string needs to be mutable.
221 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
223 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
224 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
225 GlobalValue::PrivateLinkage, StrConst, "");
229 /// \brief Insert extern declaration of runtime-provided functions and globals.
230 void MemorySanitizer::initializeCallbacks(Module &M) {
231 // Only do this once.
236 // Create the callback.
237 // FIXME: this function should have "Cold" calling conv,
238 // which is not yet implemented.
239 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
240 : "__msan_warning_noreturn";
241 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
243 MsanCopyOriginFn = M.getOrInsertFunction(
244 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
245 IRB.getInt8PtrTy(), IntptrTy, NULL);
246 MsanSetAllocaOriginFn = M.getOrInsertFunction(
247 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
248 IRB.getInt8PtrTy(), NULL);
249 MsanPoisonStackFn = M.getOrInsertFunction(
250 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
251 MemmoveFn = M.getOrInsertFunction(
252 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
253 IRB.getInt8PtrTy(), IntptrTy, NULL);
254 MemcpyFn = M.getOrInsertFunction(
255 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
257 MemsetFn = M.getOrInsertFunction(
258 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
262 RetvalTLS = new GlobalVariable(
263 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
264 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
265 GlobalVariable::GeneralDynamicTLSModel);
266 RetvalOriginTLS = new GlobalVariable(
267 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
268 "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
270 ParamTLS = new GlobalVariable(
271 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
272 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
273 GlobalVariable::GeneralDynamicTLSModel);
274 ParamOriginTLS = new GlobalVariable(
275 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
276 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
278 VAArgTLS = new GlobalVariable(
279 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
280 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
281 GlobalVariable::GeneralDynamicTLSModel);
282 VAArgOverflowSizeTLS = new GlobalVariable(
283 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
284 "__msan_va_arg_overflow_size_tls", 0,
285 GlobalVariable::GeneralDynamicTLSModel);
286 OriginTLS = new GlobalVariable(
287 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
288 "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
290 // We insert an empty inline asm after __msan_report* to avoid callback merge.
291 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
292 StringRef(""), StringRef(""),
293 /*hasSideEffects=*/true);
296 /// \brief Module-level initialization.
298 /// inserts a call to __msan_init to the module's constructor list.
299 bool MemorySanitizer::doInitialization(Module &M) {
300 TD = getAnalysisIfAvailable<DataLayout>();
303 BL.reset(new BlackList(ClBlackListFile));
304 C = &(M.getContext());
305 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
308 ShadowMask = kShadowMask64;
309 OriginOffset = kOriginOffset64;
312 ShadowMask = kShadowMask32;
313 OriginOffset = kOriginOffset32;
316 report_fatal_error("unsupported pointer size");
321 IntptrTy = IRB.getIntPtrTy(TD);
322 OriginTy = IRB.getInt32Ty();
324 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
325 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
327 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
328 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
329 "__msan_init", IRB.getVoidTy(), NULL)), 0);
331 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
332 IRB.getInt32(TrackOrigins), "__msan_track_origins");
339 /// \brief A helper class that handles instrumentation of VarArg
340 /// functions on a particular platform.
342 /// Implementations are expected to insert the instrumentation
343 /// necessary to propagate argument shadow through VarArg function
344 /// calls. Visit* methods are called during an InstVisitor pass over
345 /// the function, and should avoid creating new basic blocks. A new
346 /// instance of this class is created for each instrumented function.
347 struct VarArgHelper {
348 /// \brief Visit a CallSite.
349 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
351 /// \brief Visit a va_start call.
352 virtual void visitVAStartInst(VAStartInst &I) = 0;
354 /// \brief Visit a va_copy call.
355 virtual void visitVACopyInst(VACopyInst &I) = 0;
357 /// \brief Finalize function instrumentation.
359 /// This method is called after visiting all interesting (see above)
360 /// instructions in a function.
361 virtual void finalizeInstrumentation() = 0;
363 virtual ~VarArgHelper() {}
366 struct MemorySanitizerVisitor;
369 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
370 MemorySanitizerVisitor &Visitor);
372 /// This class does all the work for a given function. Store and Load
373 /// instructions store and load corresponding shadow and origin
374 /// values. Most instructions propagate shadow from arguments to their
375 /// return values. Certain instructions (most importantly, BranchInst)
376 /// test their argument shadow and print reports (with a runtime call) if it's
378 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
381 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
382 ValueMap<Value*, Value*> ShadowMap, OriginMap;
384 OwningPtr<VarArgHelper> VAHelper;
386 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
387 // See a comment in visitCallSite for more details.
388 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
389 static const unsigned AMD64FpEndOffset = 176;
391 struct ShadowOriginAndInsertPoint {
394 Instruction *OrigIns;
395 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
396 : Shadow(S), Origin(O), OrigIns(I) { }
397 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
399 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
400 SmallVector<Instruction*, 16> StoreList;
402 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
403 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
404 InsertChecks = !MS.BL->isIn(F);
405 DEBUG(if (!InsertChecks)
406 dbgs() << "MemorySanitizer is not inserting checks into '"
407 << F.getName() << "'\n");
410 void materializeStores() {
411 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
412 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
415 Value *Val = I.getValueOperand();
416 Value *Addr = I.getPointerOperand();
417 Value *Shadow = getShadow(Val);
418 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
421 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
422 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
424 // If the store is volatile, add a check.
426 insertCheck(Val, &I);
427 if (ClCheckAccessAddress)
428 insertCheck(Addr, &I);
430 if (MS.TrackOrigins) {
431 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
432 IRB.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRB));
434 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
436 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
437 // TODO(eugenis): handle non-zero constant shadow by inserting an
438 // unconditional check (can not simply fail compilation as this could
439 // be in the dead code).
443 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
444 getCleanShadow(ConvertedShadow), "_mscmp");
445 Instruction *CheckTerm =
446 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
447 MS.OriginStoreWeights);
448 IRBuilder<> IRBNew(CheckTerm);
449 IRBNew.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRBNew));
455 void materializeChecks() {
456 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
457 Instruction *Shadow = InstrumentationList[i].Shadow;
458 Instruction *OrigIns = InstrumentationList[i].OrigIns;
459 IRBuilder<> IRB(OrigIns);
460 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
461 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
462 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
463 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
464 getCleanShadow(ConvertedShadow), "_mscmp");
465 Instruction *CheckTerm =
466 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
467 /* Unreachable */ !ClKeepGoing,
470 IRB.SetInsertPoint(CheckTerm);
471 if (MS.TrackOrigins) {
472 Instruction *Origin = InstrumentationList[i].Origin;
473 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
476 CallInst *Call = IRB.CreateCall(MS.WarningFn);
477 Call->setDebugLoc(OrigIns->getDebugLoc());
478 IRB.CreateCall(MS.EmptyAsm);
479 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
481 DEBUG(dbgs() << "DONE:\n" << F);
484 /// \brief Add MemorySanitizer instrumentation to a function.
485 bool runOnFunction() {
486 MS.initializeCallbacks(*F.getParent());
487 if (!MS.TD) return false;
488 // Iterate all BBs in depth-first order and create shadow instructions
489 // for all instructions (where applicable).
490 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
491 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
492 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
493 BasicBlock *BB = *DI;
497 // Finalize PHI nodes.
498 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
499 PHINode *PN = ShadowPHINodes[i];
500 PHINode *PNS = cast<PHINode>(getShadow(PN));
501 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
502 size_t NumValues = PN->getNumIncomingValues();
503 for (size_t v = 0; v < NumValues; v++) {
504 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
506 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
510 VAHelper->finalizeInstrumentation();
512 // Delayed instrumentation of StoreInst.
513 // This may add new checks to be inserted later.
516 // Insert shadow value checks.
522 /// \brief Compute the shadow type that corresponds to a given Value.
523 Type *getShadowTy(Value *V) {
524 return getShadowTy(V->getType());
527 /// \brief Compute the shadow type that corresponds to a given Type.
528 Type *getShadowTy(Type *OrigTy) {
529 if (!OrigTy->isSized()) {
532 // For integer type, shadow is the same as the original type.
533 // This may return weird-sized types like i1.
534 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
536 if (VectorType *VT = dyn_cast<VectorType>(OrigTy))
537 return VectorType::getInteger(VT);
538 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
539 SmallVector<Type*, 4> Elements;
540 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
541 Elements.push_back(getShadowTy(ST->getElementType(i)));
542 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
543 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
546 uint32_t TypeSize = MS.TD->getTypeStoreSizeInBits(OrigTy);
547 return IntegerType::get(*MS.C, TypeSize);
550 /// \brief Flatten a vector type.
551 Type *getShadowTyNoVec(Type *ty) {
552 if (VectorType *vt = dyn_cast<VectorType>(ty))
553 return IntegerType::get(*MS.C, vt->getBitWidth());
557 /// \brief Convert a shadow value to it's flattened variant.
558 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
559 Type *Ty = V->getType();
560 Type *NoVecTy = getShadowTyNoVec(Ty);
561 if (Ty == NoVecTy) return V;
562 return IRB.CreateBitCast(V, NoVecTy);
565 /// \brief Compute the shadow address that corresponds to a given application
568 /// Shadow = Addr & ~ShadowMask.
569 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
572 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
573 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
574 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
577 /// \brief Compute the origin address that corresponds to a given application
580 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
581 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
583 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
584 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
586 IRB.CreateAdd(ShadowLong,
587 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
589 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
590 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
593 /// \brief Compute the shadow address for a given function argument.
595 /// Shadow = ParamTLS+ArgOffset.
596 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
598 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
599 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
600 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
604 /// \brief Compute the origin address for a given function argument.
605 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
607 if (!MS.TrackOrigins) return 0;
608 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
609 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
610 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
614 /// \brief Compute the shadow address for a retval.
615 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
616 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
617 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
621 /// \brief Compute the origin address for a retval.
622 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
623 // We keep a single origin for the entire retval. Might be too optimistic.
624 return MS.RetvalOriginTLS;
627 /// \brief Set SV to be the shadow value for V.
628 void setShadow(Value *V, Value *SV) {
629 assert(!ShadowMap.count(V) && "Values may only have one shadow");
633 /// \brief Set Origin to be the origin value for V.
634 void setOrigin(Value *V, Value *Origin) {
635 if (!MS.TrackOrigins) return;
636 assert(!OriginMap.count(V) && "Values may only have one origin");
637 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
638 OriginMap[V] = Origin;
641 /// \brief Create a clean shadow value for a given value.
643 /// Clean shadow (all zeroes) means all bits of the value are defined
645 Value *getCleanShadow(Value *V) {
646 Type *ShadowTy = getShadowTy(V);
649 return Constant::getNullValue(ShadowTy);
652 /// \brief Create a dirty shadow of a given shadow type.
653 Constant *getPoisonedShadow(Type *ShadowTy) {
655 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
656 return Constant::getAllOnesValue(ShadowTy);
657 StructType *ST = cast<StructType>(ShadowTy);
658 SmallVector<Constant *, 4> Vals;
659 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
660 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
661 return ConstantStruct::get(ST, Vals);
664 /// \brief Create a clean (zero) origin.
665 Value *getCleanOrigin() {
666 return Constant::getNullValue(MS.OriginTy);
669 /// \brief Get the shadow value for a given Value.
671 /// This function either returns the value set earlier with setShadow,
672 /// or extracts if from ParamTLS (for function arguments).
673 Value *getShadow(Value *V) {
674 if (Instruction *I = dyn_cast<Instruction>(V)) {
675 // For instructions the shadow is already stored in the map.
676 Value *Shadow = ShadowMap[V];
678 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
680 assert(Shadow && "No shadow for a value");
684 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
685 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
686 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
690 if (Argument *A = dyn_cast<Argument>(V)) {
691 // For arguments we compute the shadow on demand and store it in the map.
692 Value **ShadowPtr = &ShadowMap[V];
695 Function *F = A->getParent();
696 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
697 unsigned ArgOffset = 0;
698 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
700 if (!AI->getType()->isSized()) {
701 DEBUG(dbgs() << "Arg is not sized\n");
704 unsigned Size = AI->hasByValAttr()
705 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
706 : MS.TD->getTypeAllocSize(AI->getType());
708 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
709 if (AI->hasByValAttr()) {
710 // ByVal pointer itself has clean shadow. We copy the actual
711 // argument shadow to the underlying memory.
712 Value *Cpy = EntryIRB.CreateMemCpy(
713 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
714 Base, Size, AI->getParamAlignment());
715 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
717 *ShadowPtr = getCleanShadow(V);
719 *ShadowPtr = EntryIRB.CreateLoad(Base);
721 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
722 **ShadowPtr << "\n");
723 if (MS.TrackOrigins) {
724 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
725 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
728 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
730 assert(*ShadowPtr && "Could not find shadow for an argument");
733 // For everything else the shadow is zero.
734 return getCleanShadow(V);
737 /// \brief Get the shadow for i-th argument of the instruction I.
738 Value *getShadow(Instruction *I, int i) {
739 return getShadow(I->getOperand(i));
742 /// \brief Get the origin for a value.
743 Value *getOrigin(Value *V) {
744 if (!MS.TrackOrigins) return 0;
745 if (isa<Instruction>(V) || isa<Argument>(V)) {
746 Value *Origin = OriginMap[V];
748 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
749 Origin = getCleanOrigin();
753 return getCleanOrigin();
756 /// \brief Get the origin for i-th argument of the instruction I.
757 Value *getOrigin(Instruction *I, int i) {
758 return getOrigin(I->getOperand(i));
761 /// \brief Remember the place where a shadow check should be inserted.
763 /// This location will be later instrumented with a check that will print a
764 /// UMR warning in runtime if the value is not fully defined.
765 void insertCheck(Value *Val, Instruction *OrigIns) {
767 if (!InsertChecks) return;
768 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
771 Type *ShadowTy = Shadow->getType();
772 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
773 "Can only insert checks for integer and vector shadow types");
775 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
776 InstrumentationList.push_back(
777 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
780 // ------------------- Visitors.
782 /// \brief Instrument LoadInst
784 /// Loads the corresponding shadow and (optionally) origin.
785 /// Optionally, checks that the load address is fully defined.
786 void visitLoadInst(LoadInst &I) {
787 assert(I.getType()->isSized() && "Load type must have size");
789 Type *ShadowTy = getShadowTy(&I);
790 Value *Addr = I.getPointerOperand();
791 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
792 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
794 if (ClCheckAccessAddress)
795 insertCheck(I.getPointerOperand(), &I);
798 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
801 /// \brief Instrument StoreInst
803 /// Stores the corresponding shadow and (optionally) origin.
804 /// Optionally, checks that the store address is fully defined.
805 /// Volatile stores check that the value being stored is fully defined.
806 void visitStoreInst(StoreInst &I) {
807 StoreList.push_back(&I);
810 // Vector manipulation.
811 void visitExtractElementInst(ExtractElementInst &I) {
812 insertCheck(I.getOperand(1), &I);
814 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
816 setOrigin(&I, getOrigin(&I, 0));
819 void visitInsertElementInst(InsertElementInst &I) {
820 insertCheck(I.getOperand(2), &I);
822 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
823 I.getOperand(2), "_msprop"));
824 setOriginForNaryOp(I);
827 void visitShuffleVectorInst(ShuffleVectorInst &I) {
828 insertCheck(I.getOperand(2), &I);
830 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
831 I.getOperand(2), "_msprop"));
832 setOriginForNaryOp(I);
836 void visitSExtInst(SExtInst &I) {
838 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
839 setOrigin(&I, getOrigin(&I, 0));
842 void visitZExtInst(ZExtInst &I) {
844 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
845 setOrigin(&I, getOrigin(&I, 0));
848 void visitTruncInst(TruncInst &I) {
850 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
851 setOrigin(&I, getOrigin(&I, 0));
854 void visitBitCastInst(BitCastInst &I) {
856 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
857 setOrigin(&I, getOrigin(&I, 0));
860 void visitPtrToIntInst(PtrToIntInst &I) {
862 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
863 "_msprop_ptrtoint"));
864 setOrigin(&I, getOrigin(&I, 0));
867 void visitIntToPtrInst(IntToPtrInst &I) {
869 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
870 "_msprop_inttoptr"));
871 setOrigin(&I, getOrigin(&I, 0));
874 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
875 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
876 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
877 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
878 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
879 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
881 /// \brief Propagate shadow for bitwise AND.
883 /// This code is exact, i.e. if, for example, a bit in the left argument
884 /// is defined and 0, then neither the value not definedness of the
885 /// corresponding bit in B don't affect the resulting shadow.
886 void visitAnd(BinaryOperator &I) {
888 // "And" of 0 and a poisoned value results in unpoisoned value.
889 // 1&1 => 1; 0&1 => 0; p&1 => p;
890 // 1&0 => 0; 0&0 => 0; p&0 => 0;
891 // 1&p => p; 0&p => 0; p&p => p;
892 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
893 Value *S1 = getShadow(&I, 0);
894 Value *S2 = getShadow(&I, 1);
895 Value *V1 = I.getOperand(0);
896 Value *V2 = I.getOperand(1);
897 if (V1->getType() != S1->getType()) {
898 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
899 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
901 Value *S1S2 = IRB.CreateAnd(S1, S2);
902 Value *V1S2 = IRB.CreateAnd(V1, S2);
903 Value *S1V2 = IRB.CreateAnd(S1, V2);
904 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
905 setOriginForNaryOp(I);
908 void visitOr(BinaryOperator &I) {
910 // "Or" of 1 and a poisoned value results in unpoisoned value.
911 // 1|1 => 1; 0|1 => 1; p|1 => 1;
912 // 1|0 => 1; 0|0 => 0; p|0 => p;
913 // 1|p => 1; 0|p => p; p|p => p;
914 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
915 Value *S1 = getShadow(&I, 0);
916 Value *S2 = getShadow(&I, 1);
917 Value *V1 = IRB.CreateNot(I.getOperand(0));
918 Value *V2 = IRB.CreateNot(I.getOperand(1));
919 if (V1->getType() != S1->getType()) {
920 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
921 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
923 Value *S1S2 = IRB.CreateAnd(S1, S2);
924 Value *V1S2 = IRB.CreateAnd(V1, S2);
925 Value *S1V2 = IRB.CreateAnd(S1, V2);
926 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
927 setOriginForNaryOp(I);
930 /// \brief Default propagation of shadow and/or origin.
932 /// This class implements the general case of shadow propagation, used in all
933 /// cases where we don't know and/or don't care about what the operation
934 /// actually does. It converts all input shadow values to a common type
935 /// (extending or truncating as necessary), and bitwise OR's them.
937 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
938 /// fully initialized), and less prone to false positives.
940 /// This class also implements the general case of origin propagation. For a
941 /// Nary operation, result origin is set to the origin of an argument that is
942 /// not entirely initialized. If there is more than one such arguments, the
943 /// rightmost of them is picked. It does not matter which one is picked if all
944 /// arguments are initialized.
945 template <bool CombineShadow>
950 MemorySanitizerVisitor *MSV;
953 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
954 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
956 /// \brief Add a pair of shadow and origin values to the mix.
957 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
963 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
964 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
968 if (MSV->MS.TrackOrigins) {
973 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
974 Value *Cond = IRB.CreateICmpNE(FlatShadow,
975 MSV->getCleanShadow(FlatShadow));
976 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
982 /// \brief Add an application value to the mix.
983 Combiner &Add(Value *V) {
984 Value *OpShadow = MSV->getShadow(V);
985 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
986 return Add(OpShadow, OpOrigin);
989 /// \brief Set the current combined values as the given instruction's shadow
991 void Done(Instruction *I) {
994 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
995 MSV->setShadow(I, Shadow);
997 if (MSV->MS.TrackOrigins) {
999 MSV->setOrigin(I, Origin);
1004 typedef Combiner<true> ShadowAndOriginCombiner;
1005 typedef Combiner<false> OriginCombiner;
1007 /// \brief Propagate origin for arbitrary operation.
1008 void setOriginForNaryOp(Instruction &I) {
1009 if (!MS.TrackOrigins) return;
1010 IRBuilder<> IRB(&I);
1011 OriginCombiner OC(this, IRB);
1012 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1017 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1018 return Ty->isVectorTy() ?
1019 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1020 Ty->getPrimitiveSizeInBits();
1023 /// \brief Cast between two shadow types, extending or truncating as
1025 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1026 Type *srcTy = V->getType();
1027 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1028 return IRB.CreateIntCast(V, dstTy, false);
1029 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1030 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1031 return IRB.CreateIntCast(V, dstTy, false);
1032 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1033 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1034 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1036 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1037 return IRB.CreateBitCast(V2, dstTy);
1038 // TODO: handle struct types.
1041 /// \brief Propagate shadow for arbitrary operation.
1042 void handleShadowOr(Instruction &I) {
1043 IRBuilder<> IRB(&I);
1044 ShadowAndOriginCombiner SC(this, IRB);
1045 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1050 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1051 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1052 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1053 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1054 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1055 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1056 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1058 void handleDiv(Instruction &I) {
1059 IRBuilder<> IRB(&I);
1060 // Strict on the second argument.
1061 insertCheck(I.getOperand(1), &I);
1062 setShadow(&I, getShadow(&I, 0));
1063 setOrigin(&I, getOrigin(&I, 0));
1066 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1067 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1068 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1069 void visitURem(BinaryOperator &I) { handleDiv(I); }
1070 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1071 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1073 /// \brief Instrument == and != comparisons.
1075 /// Sometimes the comparison result is known even if some of the bits of the
1076 /// arguments are not.
1077 void handleEqualityComparison(ICmpInst &I) {
1078 IRBuilder<> IRB(&I);
1079 Value *A = I.getOperand(0);
1080 Value *B = I.getOperand(1);
1081 Value *Sa = getShadow(A);
1082 Value *Sb = getShadow(B);
1083 if (A->getType()->isPointerTy())
1084 A = IRB.CreatePointerCast(A, MS.IntptrTy);
1085 if (B->getType()->isPointerTy())
1086 B = IRB.CreatePointerCast(B, MS.IntptrTy);
1087 // A == B <==> (C = A^B) == 0
1088 // A != B <==> (C = A^B) != 0
1090 Value *C = IRB.CreateXor(A, B);
1091 Value *Sc = IRB.CreateOr(Sa, Sb);
1092 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1093 // Result is defined if one of the following is true
1094 // * there is a defined 1 bit in C
1095 // * C is fully defined
1096 // Si = !(C & ~Sc) && Sc
1097 Value *Zero = Constant::getNullValue(Sc->getType());
1098 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1100 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1102 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1103 Si->setName("_msprop_icmp");
1105 setOriginForNaryOp(I);
1108 /// \brief Instrument signed relational comparisons.
1110 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1111 /// propagating the highest bit of the shadow. Everything else is delegated
1112 /// to handleShadowOr().
1113 void handleSignedRelationalComparison(ICmpInst &I) {
1114 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1115 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1117 CmpInst::Predicate pre = I.getPredicate();
1118 if (constOp0 && constOp0->isNullValue() &&
1119 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1120 op = I.getOperand(1);
1121 } else if (constOp1 && constOp1->isNullValue() &&
1122 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1123 op = I.getOperand(0);
1126 IRBuilder<> IRB(&I);
1128 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1129 setShadow(&I, Shadow);
1130 setOrigin(&I, getOrigin(op));
1136 void visitICmpInst(ICmpInst &I) {
1137 if (ClHandleICmp && I.isEquality())
1138 handleEqualityComparison(I);
1139 else if (ClHandleICmp && I.isSigned() && I.isRelational())
1140 handleSignedRelationalComparison(I);
1145 void visitFCmpInst(FCmpInst &I) {
1149 void handleShift(BinaryOperator &I) {
1150 IRBuilder<> IRB(&I);
1151 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1152 // Otherwise perform the same shift on S1.
1153 Value *S1 = getShadow(&I, 0);
1154 Value *S2 = getShadow(&I, 1);
1155 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1157 Value *V2 = I.getOperand(1);
1158 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1159 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1160 setOriginForNaryOp(I);
1163 void visitShl(BinaryOperator &I) { handleShift(I); }
1164 void visitAShr(BinaryOperator &I) { handleShift(I); }
1165 void visitLShr(BinaryOperator &I) { handleShift(I); }
1167 /// \brief Instrument llvm.memmove
1169 /// At this point we don't know if llvm.memmove will be inlined or not.
1170 /// If we don't instrument it and it gets inlined,
1171 /// our interceptor will not kick in and we will lose the memmove.
1172 /// If we instrument the call here, but it does not get inlined,
1173 /// we will memove the shadow twice: which is bad in case
1174 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1176 /// Similar situation exists for memcpy and memset.
1177 void visitMemMoveInst(MemMoveInst &I) {
1178 IRBuilder<> IRB(&I);
1181 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1182 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1183 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1184 I.eraseFromParent();
1187 // Similar to memmove: avoid copying shadow twice.
1188 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1189 // FIXME: consider doing manual inline for small constant sizes and proper
1191 void visitMemCpyInst(MemCpyInst &I) {
1192 IRBuilder<> IRB(&I);
1195 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1196 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1197 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1198 I.eraseFromParent();
1202 void visitMemSetInst(MemSetInst &I) {
1203 IRBuilder<> IRB(&I);
1206 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1207 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1208 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1209 I.eraseFromParent();
1212 void visitVAStartInst(VAStartInst &I) {
1213 VAHelper->visitVAStartInst(I);
1216 void visitVACopyInst(VACopyInst &I) {
1217 VAHelper->visitVACopyInst(I);
1220 enum IntrinsicKind {
1221 IK_DoesNotAccessMemory,
1226 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1227 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1228 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1229 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1230 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1231 const int UnknownModRefBehavior = IK_WritesMemory;
1232 #define GET_INTRINSIC_MODREF_BEHAVIOR
1233 #define ModRefBehavior IntrinsicKind
1234 #include "llvm/Intrinsics.gen"
1235 #undef ModRefBehavior
1236 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1239 /// \brief Handle vector store-like intrinsics.
1241 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1242 /// has 1 pointer argument and 1 vector argument, returns void.
1243 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1244 IRBuilder<> IRB(&I);
1245 Value* Addr = I.getArgOperand(0);
1246 Value *Shadow = getShadow(&I, 1);
1247 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1249 // We don't know the pointer alignment (could be unaligned SSE store!).
1250 // Have to assume to worst case.
1251 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1253 if (ClCheckAccessAddress)
1254 insertCheck(Addr, &I);
1256 // FIXME: use ClStoreCleanOrigin
1257 // FIXME: factor out common code from materializeStores
1258 if (MS.TrackOrigins)
1259 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1263 /// \brief Handle vector load-like intrinsics.
1265 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1266 /// has 1 pointer argument, returns a vector.
1267 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1268 IRBuilder<> IRB(&I);
1269 Value *Addr = I.getArgOperand(0);
1271 Type *ShadowTy = getShadowTy(&I);
1272 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1273 // We don't know the pointer alignment (could be unaligned SSE load!).
1274 // Have to assume to worst case.
1275 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1277 if (ClCheckAccessAddress)
1278 insertCheck(Addr, &I);
1280 if (MS.TrackOrigins)
1281 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1285 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1287 /// Instrument intrinsics with any number of arguments of the same type,
1288 /// equal to the return type. The type should be simple (no aggregates or
1289 /// pointers; vectors are fine).
1290 /// Caller guarantees that this intrinsic does not access memory.
1291 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1292 Type *RetTy = I.getType();
1293 if (!(RetTy->isIntOrIntVectorTy() ||
1294 RetTy->isFPOrFPVectorTy() ||
1295 RetTy->isX86_MMXTy()))
1298 unsigned NumArgOperands = I.getNumArgOperands();
1300 for (unsigned i = 0; i < NumArgOperands; ++i) {
1301 Type *Ty = I.getArgOperand(i)->getType();
1306 IRBuilder<> IRB(&I);
1307 ShadowAndOriginCombiner SC(this, IRB);
1308 for (unsigned i = 0; i < NumArgOperands; ++i)
1309 SC.Add(I.getArgOperand(i));
1315 /// \brief Heuristically instrument unknown intrinsics.
1317 /// The main purpose of this code is to do something reasonable with all
1318 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1319 /// We recognize several classes of intrinsics by their argument types and
1320 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1321 /// sure that we know what the intrinsic does.
1323 /// We special-case intrinsics where this approach fails. See llvm.bswap
1324 /// handling as an example of that.
1325 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1326 unsigned NumArgOperands = I.getNumArgOperands();
1327 if (NumArgOperands == 0)
1330 Intrinsic::ID iid = I.getIntrinsicID();
1331 IntrinsicKind IK = getIntrinsicKind(iid);
1332 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1333 bool WritesMemory = IK == IK_WritesMemory;
1334 assert(!(OnlyReadsMemory && WritesMemory));
1336 if (NumArgOperands == 2 &&
1337 I.getArgOperand(0)->getType()->isPointerTy() &&
1338 I.getArgOperand(1)->getType()->isVectorTy() &&
1339 I.getType()->isVoidTy() &&
1341 // This looks like a vector store.
1342 return handleVectorStoreIntrinsic(I);
1345 if (NumArgOperands == 1 &&
1346 I.getArgOperand(0)->getType()->isPointerTy() &&
1347 I.getType()->isVectorTy() &&
1349 // This looks like a vector load.
1350 return handleVectorLoadIntrinsic(I);
1353 if (!OnlyReadsMemory && !WritesMemory)
1354 if (maybeHandleSimpleNomemIntrinsic(I))
1357 // FIXME: detect and handle SSE maskstore/maskload
1361 void handleBswap(IntrinsicInst &I) {
1362 IRBuilder<> IRB(&I);
1363 Value *Op = I.getArgOperand(0);
1364 Type *OpType = Op->getType();
1365 Function *BswapFunc = Intrinsic::getDeclaration(
1366 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1367 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1368 setOrigin(&I, getOrigin(Op));
1371 void visitIntrinsicInst(IntrinsicInst &I) {
1372 switch (I.getIntrinsicID()) {
1373 case llvm::Intrinsic::bswap:
1377 if (!handleUnknownIntrinsic(I))
1378 visitInstruction(I);
1383 void visitCallSite(CallSite CS) {
1384 Instruction &I = *CS.getInstruction();
1385 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1387 CallInst *Call = cast<CallInst>(&I);
1389 // For inline asm, do the usual thing: check argument shadow and mark all
1390 // outputs as clean. Note that any side effects of the inline asm that are
1391 // not immediately visible in its constraints are not handled.
1392 if (Call->isInlineAsm()) {
1393 visitInstruction(I);
1397 // Allow only tail calls with the same types, otherwise
1398 // we may have a false positive: shadow for a non-void RetVal
1399 // will get propagated to a void RetVal.
1400 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1401 Call->setTailCall(false);
1403 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1405 // We are going to insert code that relies on the fact that the callee
1406 // will become a non-readonly function after it is instrumented by us. To
1407 // prevent this code from being optimized out, mark that function
1408 // non-readonly in advance.
1409 if (Function *Func = Call->getCalledFunction()) {
1410 // Clear out readonly/readnone attributes.
1412 B.addAttribute(Attribute::ReadOnly)
1413 .addAttribute(Attribute::ReadNone);
1414 Func->removeAttribute(AttributeSet::FunctionIndex,
1415 Attribute::get(Func->getContext(), B));
1418 IRBuilder<> IRB(&I);
1419 unsigned ArgOffset = 0;
1420 DEBUG(dbgs() << " CallSite: " << I << "\n");
1421 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1422 ArgIt != End; ++ArgIt) {
1424 unsigned i = ArgIt - CS.arg_begin();
1425 if (!A->getType()->isSized()) {
1426 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1431 // Compute the Shadow for arg even if it is ByVal, because
1432 // in that case getShadow() will copy the actual arg shadow to
1433 // __msan_param_tls.
1434 Value *ArgShadow = getShadow(A);
1435 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1436 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1437 " Shadow: " << *ArgShadow << "\n");
1438 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
1439 assert(A->getType()->isPointerTy() &&
1440 "ByVal argument is not a pointer!");
1441 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1442 unsigned Alignment = CS.getParamAlignment(i + 1);
1443 Store = IRB.CreateMemCpy(ArgShadowBase,
1444 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1447 Size = MS.TD->getTypeAllocSize(A->getType());
1448 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1449 kShadowTLSAlignment);
1451 if (MS.TrackOrigins)
1452 IRB.CreateStore(getOrigin(A),
1453 getOriginPtrForArgument(A, IRB, ArgOffset));
1454 assert(Size != 0 && Store != 0);
1455 DEBUG(dbgs() << " Param:" << *Store << "\n");
1456 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1458 DEBUG(dbgs() << " done with call args\n");
1461 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1462 if (FT->isVarArg()) {
1463 VAHelper->visitCallSite(CS, IRB);
1466 // Now, get the shadow for the RetVal.
1467 if (!I.getType()->isSized()) return;
1468 IRBuilder<> IRBBefore(&I);
1469 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1470 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1471 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
1472 Instruction *NextInsn = 0;
1474 NextInsn = I.getNextNode();
1476 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1477 if (!NormalDest->getSinglePredecessor()) {
1478 // FIXME: this case is tricky, so we are just conservative here.
1479 // Perhaps we need to split the edge between this BB and NormalDest,
1480 // but a naive attempt to use SplitEdge leads to a crash.
1481 setShadow(&I, getCleanShadow(&I));
1482 setOrigin(&I, getCleanOrigin());
1485 NextInsn = NormalDest->getFirstInsertionPt();
1487 "Could not find insertion point for retval shadow load");
1489 IRBuilder<> IRBAfter(NextInsn);
1490 Value *RetvalShadow =
1491 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1492 kShadowTLSAlignment, "_msret");
1493 setShadow(&I, RetvalShadow);
1494 if (MS.TrackOrigins)
1495 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1498 void visitReturnInst(ReturnInst &I) {
1499 IRBuilder<> IRB(&I);
1500 if (Value *RetVal = I.getReturnValue()) {
1501 // Set the shadow for the RetVal.
1502 Value *Shadow = getShadow(RetVal);
1503 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1504 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
1505 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1506 if (MS.TrackOrigins)
1507 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1511 void visitPHINode(PHINode &I) {
1512 IRBuilder<> IRB(&I);
1513 ShadowPHINodes.push_back(&I);
1514 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1516 if (MS.TrackOrigins)
1517 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1521 void visitAllocaInst(AllocaInst &I) {
1522 setShadow(&I, getCleanShadow(&I));
1523 if (!ClPoisonStack) return;
1524 IRBuilder<> IRB(I.getNextNode());
1525 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1526 if (ClPoisonStackWithCall) {
1527 IRB.CreateCall2(MS.MsanPoisonStackFn,
1528 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1529 ConstantInt::get(MS.IntptrTy, Size));
1531 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1532 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1533 Size, I.getAlignment());
1536 if (MS.TrackOrigins) {
1537 setOrigin(&I, getCleanOrigin());
1538 SmallString<2048> StackDescriptionStorage;
1539 raw_svector_ostream StackDescription(StackDescriptionStorage);
1540 // We create a string with a description of the stack allocation and
1541 // pass it into __msan_set_alloca_origin.
1542 // It will be printed by the run-time if stack-originated UMR is found.
1543 // The first 4 bytes of the string are set to '----' and will be replaced
1544 // by __msan_va_arg_overflow_size_tls at the first call.
1545 StackDescription << "----" << I.getName() << "@" << F.getName();
1547 createPrivateNonConstGlobalForString(*F.getParent(),
1548 StackDescription.str());
1549 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1550 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1551 ConstantInt::get(MS.IntptrTy, Size),
1552 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1556 void visitSelectInst(SelectInst& I) {
1557 IRBuilder<> IRB(&I);
1558 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1559 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1561 if (MS.TrackOrigins)
1562 setOrigin(&I, IRB.CreateSelect(I.getCondition(),
1563 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1566 void visitLandingPadInst(LandingPadInst &I) {
1568 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1569 setShadow(&I, getCleanShadow(&I));
1570 setOrigin(&I, getCleanOrigin());
1573 void visitGetElementPtrInst(GetElementPtrInst &I) {
1577 void visitExtractValueInst(ExtractValueInst &I) {
1578 IRBuilder<> IRB(&I);
1579 Value *Agg = I.getAggregateOperand();
1580 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1581 Value *AggShadow = getShadow(Agg);
1582 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1583 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1584 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1585 setShadow(&I, ResShadow);
1586 setOrigin(&I, getCleanOrigin());
1589 void visitInsertValueInst(InsertValueInst &I) {
1590 IRBuilder<> IRB(&I);
1591 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1592 Value *AggShadow = getShadow(I.getAggregateOperand());
1593 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1594 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1595 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1596 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1597 DEBUG(dbgs() << " Res: " << *Res << "\n");
1599 setOrigin(&I, getCleanOrigin());
1602 void dumpInst(Instruction &I) {
1603 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1604 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1606 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1608 errs() << "QQQ " << I << "\n";
1611 void visitResumeInst(ResumeInst &I) {
1612 DEBUG(dbgs() << "Resume: " << I << "\n");
1613 // Nothing to do here.
1616 void visitInstruction(Instruction &I) {
1617 // Everything else: stop propagating and check for poisoned shadow.
1618 if (ClDumpStrictInstructions)
1620 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1621 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1622 insertCheck(I.getOperand(i), &I);
1623 setShadow(&I, getCleanShadow(&I));
1624 setOrigin(&I, getCleanOrigin());
1628 /// \brief AMD64-specific implementation of VarArgHelper.
1629 struct VarArgAMD64Helper : public VarArgHelper {
1630 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1631 // See a comment in visitCallSite for more details.
1632 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
1633 static const unsigned AMD64FpEndOffset = 176;
1636 MemorySanitizer &MS;
1637 MemorySanitizerVisitor &MSV;
1638 Value *VAArgTLSCopy;
1639 Value *VAArgOverflowSize;
1641 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1643 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1644 MemorySanitizerVisitor &MSV)
1645 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1647 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1649 ArgKind classifyArgument(Value* arg) {
1650 // A very rough approximation of X86_64 argument classification rules.
1651 Type *T = arg->getType();
1652 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1653 return AK_FloatingPoint;
1654 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1655 return AK_GeneralPurpose;
1656 if (T->isPointerTy())
1657 return AK_GeneralPurpose;
1661 // For VarArg functions, store the argument shadow in an ABI-specific format
1662 // that corresponds to va_list layout.
1663 // We do this because Clang lowers va_arg in the frontend, and this pass
1664 // only sees the low level code that deals with va_list internals.
1665 // A much easier alternative (provided that Clang emits va_arg instructions)
1666 // would have been to associate each live instance of va_list with a copy of
1667 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1669 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1670 unsigned GpOffset = 0;
1671 unsigned FpOffset = AMD64GpEndOffset;
1672 unsigned OverflowOffset = AMD64FpEndOffset;
1673 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1674 ArgIt != End; ++ArgIt) {
1676 ArgKind AK = classifyArgument(A);
1677 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1679 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1683 case AK_GeneralPurpose:
1684 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1687 case AK_FloatingPoint:
1688 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1692 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1693 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1694 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1696 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
1698 Constant *OverflowSize =
1699 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1700 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1703 /// \brief Compute the shadow address for a given va_arg.
1704 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1706 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1707 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1708 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1712 void visitVAStartInst(VAStartInst &I) {
1713 IRBuilder<> IRB(&I);
1714 VAStartInstrumentationList.push_back(&I);
1715 Value *VAListTag = I.getArgOperand(0);
1716 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1718 // Unpoison the whole __va_list_tag.
1719 // FIXME: magic ABI constants.
1720 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1721 /* size */24, /* alignment */16, false);
1724 void visitVACopyInst(VACopyInst &I) {
1725 IRBuilder<> IRB(&I);
1726 Value *VAListTag = I.getArgOperand(0);
1727 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1729 // Unpoison the whole __va_list_tag.
1730 // FIXME: magic ABI constants.
1731 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1732 /* size */ 24, /* alignment */ 16, false);
1735 void finalizeInstrumentation() {
1736 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1737 "finalizeInstrumentation called twice");
1738 if (!VAStartInstrumentationList.empty()) {
1739 // If there is a va_start in this function, make a backup copy of
1740 // va_arg_tls somewhere in the function entry block.
1741 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1742 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1744 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1746 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1747 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1750 // Instrument va_start.
1751 // Copy va_list shadow from the backup copy of the TLS contents.
1752 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1753 CallInst *OrigInst = VAStartInstrumentationList[i];
1754 IRBuilder<> IRB(OrigInst->getNextNode());
1755 Value *VAListTag = OrigInst->getArgOperand(0);
1757 Value *RegSaveAreaPtrPtr =
1759 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1760 ConstantInt::get(MS.IntptrTy, 16)),
1761 Type::getInt64PtrTy(*MS.C));
1762 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1763 Value *RegSaveAreaShadowPtr =
1764 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1765 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1766 AMD64FpEndOffset, 16);
1768 Value *OverflowArgAreaPtrPtr =
1770 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1771 ConstantInt::get(MS.IntptrTy, 8)),
1772 Type::getInt64PtrTy(*MS.C));
1773 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1774 Value *OverflowArgAreaShadowPtr =
1775 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1777 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1778 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1783 VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1784 MemorySanitizerVisitor &Visitor) {
1785 return new VarArgAMD64Helper(Func, Msan, Visitor);
1790 bool MemorySanitizer::runOnFunction(Function &F) {
1791 MemorySanitizerVisitor Visitor(F, *this);
1793 // Clear out readonly/readnone attributes.
1795 B.addAttribute(Attribute::ReadOnly)
1796 .addAttribute(Attribute::ReadNone);
1797 F.removeAttribute(AttributeSet::FunctionIndex,
1798 Attribute::get(F.getContext(), B));
1800 return Visitor.runOnFunction();