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 /// The algorithm of the tool is similar to Memcheck
14 /// (http://goo.gl/QKbem). We associate a few shadow bits with every
15 /// byte of the application memory, poison the shadow of the malloc-ed
16 /// or alloca-ed memory, load the shadow bits on every memory read,
17 /// propagate the shadow bits through some of the arithmetic
18 /// instruction (including MOV), store the shadow bits on every memory
19 /// write, report a bug on some other instructions (e.g. JMP) if the
20 /// associated shadow is poisoned.
22 /// But there are differences too. The first and the major one:
23 /// compiler instrumentation instead of binary instrumentation. This
24 /// gives us much better register allocation, possible compiler
25 /// optimizations and a fast start-up. But this brings the major issue
26 /// as well: msan needs to see all program events, including system
27 /// calls and reads/writes in system libraries, so we either need to
28 /// compile *everything* with msan or use a binary translation
29 /// component (e.g. DynamoRIO) to instrument pre-built libraries.
30 /// Another difference from Memcheck is that we use 8 shadow bits per
31 /// byte of application memory and use a direct shadow mapping. This
32 /// greatly simplifies the instrumentation code and avoids races on
33 /// shadow updates (Memcheck is single-threaded so races are not a
34 /// concern there. Memcheck uses 2 shadow bits per byte with a slow
35 /// path storage that uses 8 bits per byte).
37 /// The default value of shadow is 0, which means "clean" (not poisoned).
39 /// Every module initializer should call __msan_init to ensure that the
40 /// shadow memory is ready. On error, __msan_warning is called. Since
41 /// parameters and return values may be passed via registers, we have a
42 /// specialized thread-local shadow for return values
43 /// (__msan_retval_tls) and parameters (__msan_param_tls).
47 /// MemorySanitizer can track origins (allocation points) of all uninitialized
48 /// values. This behavior is controlled with a flag (msan-track-origins) and is
49 /// disabled by default.
51 /// Origins are 4-byte values created and interpreted by the runtime library.
52 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
53 /// of application memory. Propagation of origins is basically a bunch of
54 /// "select" instructions that pick the origin of a dirty argument, if an
55 /// instruction has one.
57 /// Every 4 aligned, consecutive bytes of application memory have one origin
58 /// value associated with them. If these bytes contain uninitialized data
59 /// coming from 2 different allocations, the last store wins. Because of this,
60 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
63 /// Origins are meaningless for fully initialized values, so MemorySanitizer
64 /// avoids storing origin to memory when a fully initialized value is stored.
65 /// This way it avoids needless overwritting origin of the 4-byte region on
66 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
70 /// Ideally, every atomic store of application value should update the
71 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
72 /// of two disjoint locations can not be done without severe slowdown.
74 /// Therefore, we implement an approximation that may err on the safe side.
75 /// In this implementation, every atomically accessed location in the program
76 /// may only change from (partially) uninitialized to fully initialized, but
77 /// not the other way around. We load the shadow _after_ the application load,
78 /// and we store the shadow _before_ the app store. Also, we always store clean
79 /// shadow (if the application store is atomic). This way, if the store-load
80 /// pair constitutes a happens-before arc, shadow store and load are correctly
81 /// ordered such that the load will get either the value that was stored, or
82 /// some later value (which is always clean).
84 /// This does not work very well with Compare-And-Swap (CAS) and
85 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
86 /// must store the new shadow before the app operation, and load the shadow
87 /// after the app operation. Computers don't work this way. Current
88 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
89 /// value. It implements the store part as a simple atomic store by storing a
92 //===----------------------------------------------------------------------===//
94 #include "llvm/Transforms/Instrumentation.h"
95 #include "llvm/ADT/DepthFirstIterator.h"
96 #include "llvm/ADT/SmallString.h"
97 #include "llvm/ADT/SmallVector.h"
98 #include "llvm/ADT/StringExtras.h"
99 #include "llvm/ADT/Triple.h"
100 #include "llvm/IR/DataLayout.h"
101 #include "llvm/IR/Function.h"
102 #include "llvm/IR/IRBuilder.h"
103 #include "llvm/IR/InlineAsm.h"
104 #include "llvm/IR/InstVisitor.h"
105 #include "llvm/IR/IntrinsicInst.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/MDBuilder.h"
108 #include "llvm/IR/Module.h"
109 #include "llvm/IR/Type.h"
110 #include "llvm/IR/ValueMap.h"
111 #include "llvm/Support/CommandLine.h"
112 #include "llvm/Support/Compiler.h"
113 #include "llvm/Support/Debug.h"
114 #include "llvm/Support/raw_ostream.h"
115 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include "llvm/Transforms/Utils/ModuleUtils.h"
119 using namespace llvm;
121 #define DEBUG_TYPE "msan"
123 static const unsigned kOriginSize = 4;
124 static const unsigned kMinOriginAlignment = 4;
125 static const unsigned kShadowTLSAlignment = 8;
127 // These constants must be kept in sync with the ones in msan.h.
128 static const unsigned kParamTLSSize = 800;
129 static const unsigned kRetvalTLSSize = 800;
131 // Accesses sizes are powers of two: 1, 2, 4, 8.
132 static const size_t kNumberOfAccessSizes = 4;
134 /// \brief Track origins of uninitialized values.
136 /// Adds a section to MemorySanitizer report that points to the allocation
137 /// (stack or heap) the uninitialized bits came from originally.
138 static cl::opt<int> ClTrackOrigins("msan-track-origins",
139 cl::desc("Track origins (allocation sites) of poisoned memory"),
140 cl::Hidden, cl::init(0));
141 static cl::opt<bool> ClKeepGoing("msan-keep-going",
142 cl::desc("keep going after reporting a UMR"),
143 cl::Hidden, cl::init(false));
144 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
145 cl::desc("poison uninitialized stack variables"),
146 cl::Hidden, cl::init(true));
147 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
148 cl::desc("poison uninitialized stack variables with a call"),
149 cl::Hidden, cl::init(false));
150 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
151 cl::desc("poison uninitialized stack variables with the given patter"),
152 cl::Hidden, cl::init(0xff));
153 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
154 cl::desc("poison undef temps"),
155 cl::Hidden, cl::init(true));
157 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
158 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
159 cl::Hidden, cl::init(true));
161 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
162 cl::desc("exact handling of relational integer ICmp"),
163 cl::Hidden, cl::init(false));
165 // This flag controls whether we check the shadow of the address
166 // operand of load or store. Such bugs are very rare, since load from
167 // a garbage address typically results in SEGV, but still happen
168 // (e.g. only lower bits of address are garbage, or the access happens
169 // early at program startup where malloc-ed memory is more likely to
170 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
171 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
172 cl::desc("report accesses through a pointer which has poisoned shadow"),
173 cl::Hidden, cl::init(true));
175 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
176 cl::desc("print out instructions with default strict semantics"),
177 cl::Hidden, cl::init(false));
179 static cl::opt<int> ClInstrumentationWithCallThreshold(
180 "msan-instrumentation-with-call-threshold",
182 "If the function being instrumented requires more than "
183 "this number of checks and origin stores, use callbacks instead of "
184 "inline checks (-1 means never use callbacks)."),
185 cl::Hidden, cl::init(3500));
187 // This is an experiment to enable handling of cases where shadow is a non-zero
188 // compile-time constant. For some unexplainable reason they were silently
189 // ignored in the instrumentation.
190 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
191 cl::desc("Insert checks for constant shadow values"),
192 cl::Hidden, cl::init(false));
194 static const char *const kMsanModuleCtorName = "msan.module_ctor";
195 static const char *const kMsanInitName = "__msan_init";
199 // Memory map parameters used in application-to-shadow address calculation.
200 // Offset = (Addr & ~AndMask) ^ XorMask
201 // Shadow = ShadowBase + Offset
202 // Origin = OriginBase + Offset
203 struct MemoryMapParams {
210 struct PlatformMemoryMapParams {
211 const MemoryMapParams *bits32;
212 const MemoryMapParams *bits64;
216 static const MemoryMapParams Linux_I386_MemoryMapParams = {
217 0x000080000000, // AndMask
218 0, // XorMask (not used)
219 0, // ShadowBase (not used)
220 0x000040000000, // OriginBase
224 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
225 0x400000000000, // AndMask
226 0, // XorMask (not used)
227 0, // ShadowBase (not used)
228 0x200000000000, // OriginBase
232 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
233 0x004000000000, // AndMask
234 0, // XorMask (not used)
235 0, // ShadowBase (not used)
236 0x002000000000, // OriginBase
240 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
241 0x000180000000, // AndMask
242 0x000040000000, // XorMask
243 0x000020000000, // ShadowBase
244 0x000700000000, // OriginBase
248 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
249 0xc00000000000, // AndMask
250 0x200000000000, // XorMask
251 0x100000000000, // ShadowBase
252 0x380000000000, // OriginBase
255 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
256 &Linux_I386_MemoryMapParams,
257 &Linux_X86_64_MemoryMapParams,
260 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
262 &Linux_MIPS64_MemoryMapParams,
265 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
266 &FreeBSD_I386_MemoryMapParams,
267 &FreeBSD_X86_64_MemoryMapParams,
270 /// \brief An instrumentation pass implementing detection of uninitialized
273 /// MemorySanitizer: instrument the code in module to find
274 /// uninitialized reads.
275 class MemorySanitizer : public FunctionPass {
277 MemorySanitizer(int TrackOrigins = 0)
279 TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
280 WarningFn(nullptr) {}
281 const char *getPassName() const override { return "MemorySanitizer"; }
282 bool runOnFunction(Function &F) override;
283 bool doInitialization(Module &M) override;
284 static char ID; // Pass identification, replacement for typeid.
287 void initializeCallbacks(Module &M);
289 /// \brief Track origins (allocation points) of uninitialized values.
295 /// \brief Thread-local shadow storage for function parameters.
296 GlobalVariable *ParamTLS;
297 /// \brief Thread-local origin storage for function parameters.
298 GlobalVariable *ParamOriginTLS;
299 /// \brief Thread-local shadow storage for function return value.
300 GlobalVariable *RetvalTLS;
301 /// \brief Thread-local origin storage for function return value.
302 GlobalVariable *RetvalOriginTLS;
303 /// \brief Thread-local shadow storage for in-register va_arg function
304 /// parameters (x86_64-specific).
305 GlobalVariable *VAArgTLS;
306 /// \brief Thread-local shadow storage for va_arg overflow area
307 /// (x86_64-specific).
308 GlobalVariable *VAArgOverflowSizeTLS;
309 /// \brief Thread-local space used to pass origin value to the UMR reporting
311 GlobalVariable *OriginTLS;
313 /// \brief The run-time callback to print a warning.
315 // These arrays are indexed by log2(AccessSize).
316 Value *MaybeWarningFn[kNumberOfAccessSizes];
317 Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
319 /// \brief Run-time helper that generates a new origin value for a stack
321 Value *MsanSetAllocaOrigin4Fn;
322 /// \brief Run-time helper that poisons stack on function entry.
323 Value *MsanPoisonStackFn;
324 /// \brief Run-time helper that records a store (or any event) of an
325 /// uninitialized value and returns an updated origin id encoding this info.
326 Value *MsanChainOriginFn;
327 /// \brief MSan runtime replacements for memmove, memcpy and memset.
328 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
330 /// \brief Memory map parameters used in application-to-shadow calculation.
331 const MemoryMapParams *MapParams;
333 MDNode *ColdCallWeights;
334 /// \brief Branch weights for origin store.
335 MDNode *OriginStoreWeights;
336 /// \brief An empty volatile inline asm that prevents callback merge.
338 Function *MsanCtorFunction;
340 friend struct MemorySanitizerVisitor;
341 friend struct VarArgAMD64Helper;
342 friend struct VarArgMIPS64Helper;
346 char MemorySanitizer::ID = 0;
347 INITIALIZE_PASS(MemorySanitizer, "msan",
348 "MemorySanitizer: detects uninitialized reads.",
351 FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
352 return new MemorySanitizer(TrackOrigins);
355 /// \brief Create a non-const global initialized with the given string.
357 /// Creates a writable global for Str so that we can pass it to the
358 /// run-time lib. Runtime uses first 4 bytes of the string to store the
359 /// frame ID, so the string needs to be mutable.
360 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
362 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
363 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
364 GlobalValue::PrivateLinkage, StrConst, "");
368 /// \brief Insert extern declaration of runtime-provided functions and globals.
369 void MemorySanitizer::initializeCallbacks(Module &M) {
370 // Only do this once.
375 // Create the callback.
376 // FIXME: this function should have "Cold" calling conv,
377 // which is not yet implemented.
378 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
379 : "__msan_warning_noreturn";
380 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
382 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
384 unsigned AccessSize = 1 << AccessSizeIndex;
385 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
386 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
387 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
388 IRB.getInt32Ty(), nullptr);
390 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
391 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
392 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
393 IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
396 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
397 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
398 IRB.getInt8PtrTy(), IntptrTy, nullptr);
400 M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
401 IRB.getInt8PtrTy(), IntptrTy, nullptr);
402 MsanChainOriginFn = M.getOrInsertFunction(
403 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
404 MemmoveFn = M.getOrInsertFunction(
405 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
406 IRB.getInt8PtrTy(), IntptrTy, nullptr);
407 MemcpyFn = M.getOrInsertFunction(
408 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
410 MemsetFn = M.getOrInsertFunction(
411 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
415 RetvalTLS = new GlobalVariable(
416 M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
417 GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
418 GlobalVariable::InitialExecTLSModel);
419 RetvalOriginTLS = new GlobalVariable(
420 M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
421 "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
423 ParamTLS = new GlobalVariable(
424 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
425 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
426 GlobalVariable::InitialExecTLSModel);
427 ParamOriginTLS = new GlobalVariable(
428 M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
429 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
430 nullptr, GlobalVariable::InitialExecTLSModel);
432 VAArgTLS = new GlobalVariable(
433 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
434 GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
435 GlobalVariable::InitialExecTLSModel);
436 VAArgOverflowSizeTLS = new GlobalVariable(
437 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
438 "__msan_va_arg_overflow_size_tls", nullptr,
439 GlobalVariable::InitialExecTLSModel);
440 OriginTLS = new GlobalVariable(
441 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
442 "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
444 // We insert an empty inline asm after __msan_report* to avoid callback merge.
445 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
446 StringRef(""), StringRef(""),
447 /*hasSideEffects=*/true);
450 /// \brief Module-level initialization.
452 /// inserts a call to __msan_init to the module's constructor list.
453 bool MemorySanitizer::doInitialization(Module &M) {
454 auto &DL = M.getDataLayout();
456 Triple TargetTriple(M.getTargetTriple());
457 switch (TargetTriple.getOS()) {
458 case Triple::FreeBSD:
459 switch (TargetTriple.getArch()) {
461 MapParams = FreeBSD_X86_MemoryMapParams.bits64;
464 MapParams = FreeBSD_X86_MemoryMapParams.bits32;
467 report_fatal_error("unsupported architecture");
471 switch (TargetTriple.getArch()) {
473 MapParams = Linux_X86_MemoryMapParams.bits64;
476 MapParams = Linux_X86_MemoryMapParams.bits32;
479 case Triple::mips64el:
480 MapParams = Linux_MIPS_MemoryMapParams.bits64;
483 report_fatal_error("unsupported architecture");
487 report_fatal_error("unsupported operating system");
490 C = &(M.getContext());
492 IntptrTy = IRB.getIntPtrTy(DL);
493 OriginTy = IRB.getInt32Ty();
495 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
496 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
498 std::tie(MsanCtorFunction, std::ignore) =
499 createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
503 appendToGlobalCtors(M, MsanCtorFunction, 0);
506 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
507 IRB.getInt32(TrackOrigins), "__msan_track_origins");
510 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
511 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
518 /// \brief A helper class that handles instrumentation of VarArg
519 /// functions on a particular platform.
521 /// Implementations are expected to insert the instrumentation
522 /// necessary to propagate argument shadow through VarArg function
523 /// calls. Visit* methods are called during an InstVisitor pass over
524 /// the function, and should avoid creating new basic blocks. A new
525 /// instance of this class is created for each instrumented function.
526 struct VarArgHelper {
527 /// \brief Visit a CallSite.
528 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
530 /// \brief Visit a va_start call.
531 virtual void visitVAStartInst(VAStartInst &I) = 0;
533 /// \brief Visit a va_copy call.
534 virtual void visitVACopyInst(VACopyInst &I) = 0;
536 /// \brief Finalize function instrumentation.
538 /// This method is called after visiting all interesting (see above)
539 /// instructions in a function.
540 virtual void finalizeInstrumentation() = 0;
542 virtual ~VarArgHelper() {}
545 struct MemorySanitizerVisitor;
548 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
549 MemorySanitizerVisitor &Visitor);
551 unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
552 if (TypeSize <= 8) return 0;
553 return Log2_32_Ceil(TypeSize / 8);
556 /// This class does all the work for a given function. Store and Load
557 /// instructions store and load corresponding shadow and origin
558 /// values. Most instructions propagate shadow from arguments to their
559 /// return values. Certain instructions (most importantly, BranchInst)
560 /// test their argument shadow and print reports (with a runtime call) if it's
562 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
565 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
566 ValueMap<Value*, Value*> ShadowMap, OriginMap;
567 std::unique_ptr<VarArgHelper> VAHelper;
569 // The following flags disable parts of MSan instrumentation based on
570 // blacklist contents and command-line options.
572 bool PropagateShadow;
575 bool CheckReturnValue;
577 struct ShadowOriginAndInsertPoint {
580 Instruction *OrigIns;
581 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
582 : Shadow(S), Origin(O), OrigIns(I) { }
584 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
585 SmallVector<Instruction*, 16> StoreList;
587 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
588 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
589 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
590 InsertChecks = SanitizeFunction;
591 PropagateShadow = SanitizeFunction;
592 PoisonStack = SanitizeFunction && ClPoisonStack;
593 PoisonUndef = SanitizeFunction && ClPoisonUndef;
594 // FIXME: Consider using SpecialCaseList to specify a list of functions that
595 // must always return fully initialized values. For now, we hardcode "main".
596 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
598 DEBUG(if (!InsertChecks)
599 dbgs() << "MemorySanitizer is not inserting checks into '"
600 << F.getName() << "'\n");
603 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
604 if (MS.TrackOrigins <= 1) return V;
605 return IRB.CreateCall(MS.MsanChainOriginFn, V);
608 Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
609 const DataLayout &DL = F.getParent()->getDataLayout();
610 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
611 if (IntptrSize == kOriginSize) return Origin;
612 assert(IntptrSize == kOriginSize * 2);
613 Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
614 return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
617 /// \brief Fill memory range with the given origin value.
618 void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
619 unsigned Size, unsigned Alignment) {
620 const DataLayout &DL = F.getParent()->getDataLayout();
621 unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
622 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
623 assert(IntptrAlignment >= kMinOriginAlignment);
624 assert(IntptrSize >= kOriginSize);
627 unsigned CurrentAlignment = Alignment;
628 if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
629 Value *IntptrOrigin = originToIntptr(IRB, Origin);
630 Value *IntptrOriginPtr =
631 IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
632 for (unsigned i = 0; i < Size / IntptrSize; ++i) {
633 Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
635 IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
636 Ofs += IntptrSize / kOriginSize;
637 CurrentAlignment = IntptrAlignment;
641 for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
643 i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
644 IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
645 CurrentAlignment = kMinOriginAlignment;
649 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
650 unsigned Alignment, bool AsCall) {
651 const DataLayout &DL = F.getParent()->getDataLayout();
652 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
653 unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
654 if (isa<StructType>(Shadow->getType())) {
655 paintOrigin(IRB, updateOrigin(Origin, IRB),
656 getOriginPtr(Addr, IRB, Alignment), StoreSize,
659 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
660 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
661 if (ConstantShadow) {
662 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
663 paintOrigin(IRB, updateOrigin(Origin, IRB),
664 getOriginPtr(Addr, IRB, Alignment), StoreSize,
669 unsigned TypeSizeInBits =
670 DL.getTypeSizeInBits(ConvertedShadow->getType());
671 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
672 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
673 Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
674 Value *ConvertedShadow2 = IRB.CreateZExt(
675 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
676 IRB.CreateCall(Fn, {ConvertedShadow2,
677 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
680 Value *Cmp = IRB.CreateICmpNE(
681 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
682 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
683 Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
684 IRBuilder<> IRBNew(CheckTerm);
685 paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
686 getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
692 void materializeStores(bool InstrumentWithCalls) {
693 for (auto Inst : StoreList) {
694 StoreInst &SI = *dyn_cast<StoreInst>(Inst);
696 IRBuilder<> IRB(&SI);
697 Value *Val = SI.getValueOperand();
698 Value *Addr = SI.getPointerOperand();
699 Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
700 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
703 IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
704 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
707 if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
709 if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
711 if (MS.TrackOrigins && !SI.isAtomic())
712 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI.getAlignment(),
713 InstrumentWithCalls);
717 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
719 IRBuilder<> IRB(OrigIns);
720 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
721 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
722 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
724 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
725 if (ConstantShadow) {
726 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
727 if (MS.TrackOrigins) {
728 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
731 IRB.CreateCall(MS.WarningFn, {});
732 IRB.CreateCall(MS.EmptyAsm, {});
733 // FIXME: Insert UnreachableInst if !ClKeepGoing?
734 // This may invalidate some of the following checks and needs to be done
740 const DataLayout &DL = OrigIns->getModule()->getDataLayout();
742 unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
743 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
744 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
745 Value *Fn = MS.MaybeWarningFn[SizeIndex];
746 Value *ConvertedShadow2 =
747 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
748 IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
750 : (Value *)IRB.getInt32(0)});
752 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
753 getCleanShadow(ConvertedShadow), "_mscmp");
754 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
756 /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
758 IRB.SetInsertPoint(CheckTerm);
759 if (MS.TrackOrigins) {
760 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
763 IRB.CreateCall(MS.WarningFn, {});
764 IRB.CreateCall(MS.EmptyAsm, {});
765 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
769 void materializeChecks(bool InstrumentWithCalls) {
770 for (const auto &ShadowData : InstrumentationList) {
771 Instruction *OrigIns = ShadowData.OrigIns;
772 Value *Shadow = ShadowData.Shadow;
773 Value *Origin = ShadowData.Origin;
774 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
776 DEBUG(dbgs() << "DONE:\n" << F);
779 /// \brief Add MemorySanitizer instrumentation to a function.
780 bool runOnFunction() {
781 MS.initializeCallbacks(*F.getParent());
783 // In the presence of unreachable blocks, we may see Phi nodes with
784 // incoming nodes from such blocks. Since InstVisitor skips unreachable
785 // blocks, such nodes will not have any shadow value associated with them.
786 // It's easier to remove unreachable blocks than deal with missing shadow.
787 removeUnreachableBlocks(F);
789 // Iterate all BBs in depth-first order and create shadow instructions
790 // for all instructions (where applicable).
791 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
792 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
796 // Finalize PHI nodes.
797 for (PHINode *PN : ShadowPHINodes) {
798 PHINode *PNS = cast<PHINode>(getShadow(PN));
799 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
800 size_t NumValues = PN->getNumIncomingValues();
801 for (size_t v = 0; v < NumValues; v++) {
802 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
803 if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
807 VAHelper->finalizeInstrumentation();
809 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
810 InstrumentationList.size() + StoreList.size() >
811 (unsigned)ClInstrumentationWithCallThreshold;
813 // Delayed instrumentation of StoreInst.
814 // This may add new checks to be inserted later.
815 materializeStores(InstrumentWithCalls);
817 // Insert shadow value checks.
818 materializeChecks(InstrumentWithCalls);
823 /// \brief Compute the shadow type that corresponds to a given Value.
824 Type *getShadowTy(Value *V) {
825 return getShadowTy(V->getType());
828 /// \brief Compute the shadow type that corresponds to a given Type.
829 Type *getShadowTy(Type *OrigTy) {
830 if (!OrigTy->isSized()) {
833 // For integer type, shadow is the same as the original type.
834 // This may return weird-sized types like i1.
835 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
837 const DataLayout &DL = F.getParent()->getDataLayout();
838 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
839 uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
840 return VectorType::get(IntegerType::get(*MS.C, EltSize),
841 VT->getNumElements());
843 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
844 return ArrayType::get(getShadowTy(AT->getElementType()),
845 AT->getNumElements());
847 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
848 SmallVector<Type*, 4> Elements;
849 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
850 Elements.push_back(getShadowTy(ST->getElementType(i)));
851 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
852 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
855 uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
856 return IntegerType::get(*MS.C, TypeSize);
859 /// \brief Flatten a vector type.
860 Type *getShadowTyNoVec(Type *ty) {
861 if (VectorType *vt = dyn_cast<VectorType>(ty))
862 return IntegerType::get(*MS.C, vt->getBitWidth());
866 /// \brief Convert a shadow value to it's flattened variant.
867 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
868 Type *Ty = V->getType();
869 Type *NoVecTy = getShadowTyNoVec(Ty);
870 if (Ty == NoVecTy) return V;
871 return IRB.CreateBitCast(V, NoVecTy);
874 /// \brief Compute the integer shadow offset that corresponds to a given
875 /// application address.
877 /// Offset = (Addr & ~AndMask) ^ XorMask
878 Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
879 uint64_t AndMask = MS.MapParams->AndMask;
880 assert(AndMask != 0 && "AndMask shall be specified");
882 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
883 ConstantInt::get(MS.IntptrTy, ~AndMask));
885 uint64_t XorMask = MS.MapParams->XorMask;
887 OffsetLong = IRB.CreateXor(OffsetLong,
888 ConstantInt::get(MS.IntptrTy, XorMask));
892 /// \brief Compute the shadow address that corresponds to a given application
895 /// Shadow = ShadowBase + Offset
896 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
898 Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
899 uint64_t ShadowBase = MS.MapParams->ShadowBase;
902 IRB.CreateAdd(ShadowLong,
903 ConstantInt::get(MS.IntptrTy, ShadowBase));
904 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
907 /// \brief Compute the origin address that corresponds to a given application
910 /// OriginAddr = (OriginBase + Offset) & ~3ULL
911 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
912 Value *OriginLong = getShadowPtrOffset(Addr, IRB);
913 uint64_t OriginBase = MS.MapParams->OriginBase;
916 IRB.CreateAdd(OriginLong,
917 ConstantInt::get(MS.IntptrTy, OriginBase));
918 if (Alignment < kMinOriginAlignment) {
919 uint64_t Mask = kMinOriginAlignment - 1;
920 OriginLong = IRB.CreateAnd(OriginLong,
921 ConstantInt::get(MS.IntptrTy, ~Mask));
923 return IRB.CreateIntToPtr(OriginLong,
924 PointerType::get(IRB.getInt32Ty(), 0));
927 /// \brief Compute the shadow address for a given function argument.
929 /// Shadow = ParamTLS+ArgOffset.
930 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
932 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
933 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
934 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
938 /// \brief Compute the origin address for a given function argument.
939 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
941 if (!MS.TrackOrigins) return nullptr;
942 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
943 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
944 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
948 /// \brief Compute the shadow address for a retval.
949 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
950 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
951 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
955 /// \brief Compute the origin address for a retval.
956 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
957 // We keep a single origin for the entire retval. Might be too optimistic.
958 return MS.RetvalOriginTLS;
961 /// \brief Set SV to be the shadow value for V.
962 void setShadow(Value *V, Value *SV) {
963 assert(!ShadowMap.count(V) && "Values may only have one shadow");
964 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
967 /// \brief Set Origin to be the origin value for V.
968 void setOrigin(Value *V, Value *Origin) {
969 if (!MS.TrackOrigins) return;
970 assert(!OriginMap.count(V) && "Values may only have one origin");
971 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
972 OriginMap[V] = Origin;
975 /// \brief Create a clean shadow value for a given value.
977 /// Clean shadow (all zeroes) means all bits of the value are defined
979 Constant *getCleanShadow(Value *V) {
980 Type *ShadowTy = getShadowTy(V);
983 return Constant::getNullValue(ShadowTy);
986 /// \brief Create a dirty shadow of a given shadow type.
987 Constant *getPoisonedShadow(Type *ShadowTy) {
989 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
990 return Constant::getAllOnesValue(ShadowTy);
991 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
992 SmallVector<Constant *, 4> Vals(AT->getNumElements(),
993 getPoisonedShadow(AT->getElementType()));
994 return ConstantArray::get(AT, Vals);
996 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
997 SmallVector<Constant *, 4> Vals;
998 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
999 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1000 return ConstantStruct::get(ST, Vals);
1002 llvm_unreachable("Unexpected shadow type");
1005 /// \brief Create a dirty shadow for a given value.
1006 Constant *getPoisonedShadow(Value *V) {
1007 Type *ShadowTy = getShadowTy(V);
1010 return getPoisonedShadow(ShadowTy);
1013 /// \brief Create a clean (zero) origin.
1014 Value *getCleanOrigin() {
1015 return Constant::getNullValue(MS.OriginTy);
1018 /// \brief Get the shadow value for a given Value.
1020 /// This function either returns the value set earlier with setShadow,
1021 /// or extracts if from ParamTLS (for function arguments).
1022 Value *getShadow(Value *V) {
1023 if (!PropagateShadow) return getCleanShadow(V);
1024 if (Instruction *I = dyn_cast<Instruction>(V)) {
1025 // For instructions the shadow is already stored in the map.
1026 Value *Shadow = ShadowMap[V];
1028 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
1030 assert(Shadow && "No shadow for a value");
1034 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
1035 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
1036 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
1040 if (Argument *A = dyn_cast<Argument>(V)) {
1041 // For arguments we compute the shadow on demand and store it in the map.
1042 Value **ShadowPtr = &ShadowMap[V];
1045 Function *F = A->getParent();
1046 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
1047 unsigned ArgOffset = 0;
1048 const DataLayout &DL = F->getParent()->getDataLayout();
1049 for (auto &FArg : F->args()) {
1050 if (!FArg.getType()->isSized()) {
1051 DEBUG(dbgs() << "Arg is not sized\n");
1056 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
1057 : DL.getTypeAllocSize(FArg.getType());
1059 bool Overflow = ArgOffset + Size > kParamTLSSize;
1060 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1061 if (FArg.hasByValAttr()) {
1062 // ByVal pointer itself has clean shadow. We copy the actual
1063 // argument shadow to the underlying memory.
1064 // Figure out maximal valid memcpy alignment.
1065 unsigned ArgAlign = FArg.getParamAlignment();
1066 if (ArgAlign == 0) {
1067 Type *EltType = A->getType()->getPointerElementType();
1068 ArgAlign = DL.getABITypeAlignment(EltType);
1071 // ParamTLS overflow.
1072 EntryIRB.CreateMemSet(
1073 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
1074 Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
1076 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1077 Value *Cpy = EntryIRB.CreateMemCpy(
1078 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
1080 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
1083 *ShadowPtr = getCleanShadow(V);
1086 // ParamTLS overflow.
1087 *ShadowPtr = getCleanShadow(V);
1090 EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1093 DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
1094 **ShadowPtr << "\n");
1095 if (MS.TrackOrigins && !Overflow) {
1097 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
1098 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
1100 setOrigin(A, getCleanOrigin());
1103 ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
1105 assert(*ShadowPtr && "Could not find shadow for an argument");
1108 // For everything else the shadow is zero.
1109 return getCleanShadow(V);
1112 /// \brief Get the shadow for i-th argument of the instruction I.
1113 Value *getShadow(Instruction *I, int i) {
1114 return getShadow(I->getOperand(i));
1117 /// \brief Get the origin for a value.
1118 Value *getOrigin(Value *V) {
1119 if (!MS.TrackOrigins) return nullptr;
1120 if (!PropagateShadow) return getCleanOrigin();
1121 if (isa<Constant>(V)) return getCleanOrigin();
1122 assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1123 "Unexpected value type in getOrigin()");
1124 Value *Origin = OriginMap[V];
1125 assert(Origin && "Missing origin");
1129 /// \brief Get the origin for i-th argument of the instruction I.
1130 Value *getOrigin(Instruction *I, int i) {
1131 return getOrigin(I->getOperand(i));
1134 /// \brief Remember the place where a shadow check should be inserted.
1136 /// This location will be later instrumented with a check that will print a
1137 /// UMR warning in runtime if the shadow value is not 0.
1138 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1140 if (!InsertChecks) return;
1142 Type *ShadowTy = Shadow->getType();
1143 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1144 "Can only insert checks for integer and vector shadow types");
1146 InstrumentationList.push_back(
1147 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1150 /// \brief Remember the place where a shadow check should be inserted.
1152 /// This location will be later instrumented with a check that will print a
1153 /// UMR warning in runtime if the value is not fully defined.
1154 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1156 Value *Shadow, *Origin;
1157 if (ClCheckConstantShadow) {
1158 Shadow = getShadow(Val);
1159 if (!Shadow) return;
1160 Origin = getOrigin(Val);
1162 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1163 if (!Shadow) return;
1164 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1166 insertShadowCheck(Shadow, Origin, OrigIns);
1169 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1178 case AcquireRelease:
1179 return AcquireRelease;
1180 case SequentiallyConsistent:
1181 return SequentiallyConsistent;
1183 llvm_unreachable("Unknown ordering");
1186 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1195 case AcquireRelease:
1196 return AcquireRelease;
1197 case SequentiallyConsistent:
1198 return SequentiallyConsistent;
1200 llvm_unreachable("Unknown ordering");
1203 // ------------------- Visitors.
1205 /// \brief Instrument LoadInst
1207 /// Loads the corresponding shadow and (optionally) origin.
1208 /// Optionally, checks that the load address is fully defined.
1209 void visitLoadInst(LoadInst &I) {
1210 assert(I.getType()->isSized() && "Load type must have size");
1211 IRBuilder<> IRB(I.getNextNode());
1212 Type *ShadowTy = getShadowTy(&I);
1213 Value *Addr = I.getPointerOperand();
1214 if (PropagateShadow && !I.getMetadata("nosanitize")) {
1215 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1217 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1219 setShadow(&I, getCleanShadow(&I));
1222 if (ClCheckAccessAddress)
1223 insertShadowCheck(I.getPointerOperand(), &I);
1226 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1228 if (MS.TrackOrigins) {
1229 if (PropagateShadow) {
1230 unsigned Alignment = I.getAlignment();
1231 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1232 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
1235 setOrigin(&I, getCleanOrigin());
1240 /// \brief Instrument StoreInst
1242 /// Stores the corresponding shadow and (optionally) origin.
1243 /// Optionally, checks that the store address is fully defined.
1244 void visitStoreInst(StoreInst &I) {
1245 StoreList.push_back(&I);
1248 void handleCASOrRMW(Instruction &I) {
1249 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1251 IRBuilder<> IRB(&I);
1252 Value *Addr = I.getOperand(0);
1253 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1255 if (ClCheckAccessAddress)
1256 insertShadowCheck(Addr, &I);
1258 // Only test the conditional argument of cmpxchg instruction.
1259 // The other argument can potentially be uninitialized, but we can not
1260 // detect this situation reliably without possible false positives.
1261 if (isa<AtomicCmpXchgInst>(I))
1262 insertShadowCheck(I.getOperand(1), &I);
1264 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1266 setShadow(&I, getCleanShadow(&I));
1267 setOrigin(&I, getCleanOrigin());
1270 void visitAtomicRMWInst(AtomicRMWInst &I) {
1272 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1275 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1277 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1280 // Vector manipulation.
1281 void visitExtractElementInst(ExtractElementInst &I) {
1282 insertShadowCheck(I.getOperand(1), &I);
1283 IRBuilder<> IRB(&I);
1284 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1286 setOrigin(&I, getOrigin(&I, 0));
1289 void visitInsertElementInst(InsertElementInst &I) {
1290 insertShadowCheck(I.getOperand(2), &I);
1291 IRBuilder<> IRB(&I);
1292 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1293 I.getOperand(2), "_msprop"));
1294 setOriginForNaryOp(I);
1297 void visitShuffleVectorInst(ShuffleVectorInst &I) {
1298 insertShadowCheck(I.getOperand(2), &I);
1299 IRBuilder<> IRB(&I);
1300 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1301 I.getOperand(2), "_msprop"));
1302 setOriginForNaryOp(I);
1306 void visitSExtInst(SExtInst &I) {
1307 IRBuilder<> IRB(&I);
1308 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1309 setOrigin(&I, getOrigin(&I, 0));
1312 void visitZExtInst(ZExtInst &I) {
1313 IRBuilder<> IRB(&I);
1314 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1315 setOrigin(&I, getOrigin(&I, 0));
1318 void visitTruncInst(TruncInst &I) {
1319 IRBuilder<> IRB(&I);
1320 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1321 setOrigin(&I, getOrigin(&I, 0));
1324 void visitBitCastInst(BitCastInst &I) {
1325 IRBuilder<> IRB(&I);
1326 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1327 setOrigin(&I, getOrigin(&I, 0));
1330 void visitPtrToIntInst(PtrToIntInst &I) {
1331 IRBuilder<> IRB(&I);
1332 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1333 "_msprop_ptrtoint"));
1334 setOrigin(&I, getOrigin(&I, 0));
1337 void visitIntToPtrInst(IntToPtrInst &I) {
1338 IRBuilder<> IRB(&I);
1339 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1340 "_msprop_inttoptr"));
1341 setOrigin(&I, getOrigin(&I, 0));
1344 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1345 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1346 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1347 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1348 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1349 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1351 /// \brief Propagate shadow for bitwise AND.
1353 /// This code is exact, i.e. if, for example, a bit in the left argument
1354 /// is defined and 0, then neither the value not definedness of the
1355 /// corresponding bit in B don't affect the resulting shadow.
1356 void visitAnd(BinaryOperator &I) {
1357 IRBuilder<> IRB(&I);
1358 // "And" of 0 and a poisoned value results in unpoisoned value.
1359 // 1&1 => 1; 0&1 => 0; p&1 => p;
1360 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1361 // 1&p => p; 0&p => 0; p&p => p;
1362 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1363 Value *S1 = getShadow(&I, 0);
1364 Value *S2 = getShadow(&I, 1);
1365 Value *V1 = I.getOperand(0);
1366 Value *V2 = I.getOperand(1);
1367 if (V1->getType() != S1->getType()) {
1368 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1369 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1371 Value *S1S2 = IRB.CreateAnd(S1, S2);
1372 Value *V1S2 = IRB.CreateAnd(V1, S2);
1373 Value *S1V2 = IRB.CreateAnd(S1, V2);
1374 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1375 setOriginForNaryOp(I);
1378 void visitOr(BinaryOperator &I) {
1379 IRBuilder<> IRB(&I);
1380 // "Or" of 1 and a poisoned value results in unpoisoned value.
1381 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1382 // 1|0 => 1; 0|0 => 0; p|0 => p;
1383 // 1|p => 1; 0|p => p; p|p => p;
1384 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1385 Value *S1 = getShadow(&I, 0);
1386 Value *S2 = getShadow(&I, 1);
1387 Value *V1 = IRB.CreateNot(I.getOperand(0));
1388 Value *V2 = IRB.CreateNot(I.getOperand(1));
1389 if (V1->getType() != S1->getType()) {
1390 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1391 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1393 Value *S1S2 = IRB.CreateAnd(S1, S2);
1394 Value *V1S2 = IRB.CreateAnd(V1, S2);
1395 Value *S1V2 = IRB.CreateAnd(S1, V2);
1396 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1397 setOriginForNaryOp(I);
1400 /// \brief Default propagation of shadow and/or origin.
1402 /// This class implements the general case of shadow propagation, used in all
1403 /// cases where we don't know and/or don't care about what the operation
1404 /// actually does. It converts all input shadow values to a common type
1405 /// (extending or truncating as necessary), and bitwise OR's them.
1407 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1408 /// fully initialized), and less prone to false positives.
1410 /// This class also implements the general case of origin propagation. For a
1411 /// Nary operation, result origin is set to the origin of an argument that is
1412 /// not entirely initialized. If there is more than one such arguments, the
1413 /// rightmost of them is picked. It does not matter which one is picked if all
1414 /// arguments are initialized.
1415 template <bool CombineShadow>
1420 MemorySanitizerVisitor *MSV;
1423 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1424 Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
1426 /// \brief Add a pair of shadow and origin values to the mix.
1427 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1428 if (CombineShadow) {
1433 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1434 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1438 if (MSV->MS.TrackOrigins) {
1443 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1444 // No point in adding something that might result in 0 origin value.
1445 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1446 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1448 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1449 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1456 /// \brief Add an application value to the mix.
1457 Combiner &Add(Value *V) {
1458 Value *OpShadow = MSV->getShadow(V);
1459 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
1460 return Add(OpShadow, OpOrigin);
1463 /// \brief Set the current combined values as the given instruction's shadow
1465 void Done(Instruction *I) {
1466 if (CombineShadow) {
1468 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1469 MSV->setShadow(I, Shadow);
1471 if (MSV->MS.TrackOrigins) {
1473 MSV->setOrigin(I, Origin);
1478 typedef Combiner<true> ShadowAndOriginCombiner;
1479 typedef Combiner<false> OriginCombiner;
1481 /// \brief Propagate origin for arbitrary operation.
1482 void setOriginForNaryOp(Instruction &I) {
1483 if (!MS.TrackOrigins) return;
1484 IRBuilder<> IRB(&I);
1485 OriginCombiner OC(this, IRB);
1486 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1491 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1492 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1493 "Vector of pointers is not a valid shadow type");
1494 return Ty->isVectorTy() ?
1495 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1496 Ty->getPrimitiveSizeInBits();
1499 /// \brief Cast between two shadow types, extending or truncating as
1501 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1502 bool Signed = false) {
1503 Type *srcTy = V->getType();
1504 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1505 return IRB.CreateIntCast(V, dstTy, Signed);
1506 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1507 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1508 return IRB.CreateIntCast(V, dstTy, Signed);
1509 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1510 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1511 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1513 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1514 return IRB.CreateBitCast(V2, dstTy);
1515 // TODO: handle struct types.
1518 /// \brief Cast an application value to the type of its own shadow.
1519 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1520 Type *ShadowTy = getShadowTy(V);
1521 if (V->getType() == ShadowTy)
1523 if (V->getType()->isPtrOrPtrVectorTy())
1524 return IRB.CreatePtrToInt(V, ShadowTy);
1526 return IRB.CreateBitCast(V, ShadowTy);
1529 /// \brief Propagate shadow for arbitrary operation.
1530 void handleShadowOr(Instruction &I) {
1531 IRBuilder<> IRB(&I);
1532 ShadowAndOriginCombiner SC(this, IRB);
1533 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1538 // \brief Handle multiplication by constant.
1540 // Handle a special case of multiplication by constant that may have one or
1541 // more zeros in the lower bits. This makes corresponding number of lower bits
1542 // of the result zero as well. We model it by shifting the other operand
1543 // shadow left by the required number of bits. Effectively, we transform
1544 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1545 // We use multiplication by 2**N instead of shift to cover the case of
1546 // multiplication by 0, which may occur in some elements of a vector operand.
1547 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1549 Constant *ShadowMul;
1550 Type *Ty = ConstArg->getType();
1551 if (Ty->isVectorTy()) {
1552 unsigned NumElements = Ty->getVectorNumElements();
1553 Type *EltTy = Ty->getSequentialElementType();
1554 SmallVector<Constant *, 16> Elements;
1555 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1557 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1558 APInt V = Elt->getValue();
1559 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1560 Elements.push_back(ConstantInt::get(EltTy, V2));
1562 ShadowMul = ConstantVector::get(Elements);
1564 ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1565 APInt V = Elt->getValue();
1566 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1567 ShadowMul = ConstantInt::get(Elt->getType(), V2);
1570 IRBuilder<> IRB(&I);
1572 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1573 setOrigin(&I, getOrigin(OtherArg));
1576 void visitMul(BinaryOperator &I) {
1577 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1578 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1579 if (constOp0 && !constOp1)
1580 handleMulByConstant(I, constOp0, I.getOperand(1));
1581 else if (constOp1 && !constOp0)
1582 handleMulByConstant(I, constOp1, I.getOperand(0));
1587 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1588 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1589 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1590 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1591 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1592 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1594 void handleDiv(Instruction &I) {
1595 IRBuilder<> IRB(&I);
1596 // Strict on the second argument.
1597 insertShadowCheck(I.getOperand(1), &I);
1598 setShadow(&I, getShadow(&I, 0));
1599 setOrigin(&I, getOrigin(&I, 0));
1602 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1603 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1604 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1605 void visitURem(BinaryOperator &I) { handleDiv(I); }
1606 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1607 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1609 /// \brief Instrument == and != comparisons.
1611 /// Sometimes the comparison result is known even if some of the bits of the
1612 /// arguments are not.
1613 void handleEqualityComparison(ICmpInst &I) {
1614 IRBuilder<> IRB(&I);
1615 Value *A = I.getOperand(0);
1616 Value *B = I.getOperand(1);
1617 Value *Sa = getShadow(A);
1618 Value *Sb = getShadow(B);
1620 // Get rid of pointers and vectors of pointers.
1621 // For ints (and vectors of ints), types of A and Sa match,
1622 // and this is a no-op.
1623 A = IRB.CreatePointerCast(A, Sa->getType());
1624 B = IRB.CreatePointerCast(B, Sb->getType());
1626 // A == B <==> (C = A^B) == 0
1627 // A != B <==> (C = A^B) != 0
1629 Value *C = IRB.CreateXor(A, B);
1630 Value *Sc = IRB.CreateOr(Sa, Sb);
1631 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1632 // Result is defined if one of the following is true
1633 // * there is a defined 1 bit in C
1634 // * C is fully defined
1635 // Si = !(C & ~Sc) && Sc
1636 Value *Zero = Constant::getNullValue(Sc->getType());
1637 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1639 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1641 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1642 Si->setName("_msprop_icmp");
1644 setOriginForNaryOp(I);
1647 /// \brief Build the lowest possible value of V, taking into account V's
1648 /// uninitialized bits.
1649 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1652 // Split shadow into sign bit and other bits.
1653 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1654 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1655 // Maximise the undefined shadow bit, minimize other undefined bits.
1657 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1659 // Minimize undefined bits.
1660 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1664 /// \brief Build the highest possible value of V, taking into account V's
1665 /// uninitialized bits.
1666 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1669 // Split shadow into sign bit and other bits.
1670 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1671 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1672 // Minimise the undefined shadow bit, maximise other undefined bits.
1674 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1676 // Maximize undefined bits.
1677 return IRB.CreateOr(A, Sa);
1681 /// \brief Instrument relational comparisons.
1683 /// This function does exact shadow propagation for all relational
1684 /// comparisons of integers, pointers and vectors of those.
1685 /// FIXME: output seems suboptimal when one of the operands is a constant
1686 void handleRelationalComparisonExact(ICmpInst &I) {
1687 IRBuilder<> IRB(&I);
1688 Value *A = I.getOperand(0);
1689 Value *B = I.getOperand(1);
1690 Value *Sa = getShadow(A);
1691 Value *Sb = getShadow(B);
1693 // Get rid of pointers and vectors of pointers.
1694 // For ints (and vectors of ints), types of A and Sa match,
1695 // and this is a no-op.
1696 A = IRB.CreatePointerCast(A, Sa->getType());
1697 B = IRB.CreatePointerCast(B, Sb->getType());
1699 // Let [a0, a1] be the interval of possible values of A, taking into account
1700 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1701 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1702 bool IsSigned = I.isSigned();
1703 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1704 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1705 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1706 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1707 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1708 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1709 Value *Si = IRB.CreateXor(S1, S2);
1711 setOriginForNaryOp(I);
1714 /// \brief Instrument signed relational comparisons.
1716 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1717 /// propagating the highest bit of the shadow. Everything else is delegated
1718 /// to handleShadowOr().
1719 void handleSignedRelationalComparison(ICmpInst &I) {
1720 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1721 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1722 Value* op = nullptr;
1723 CmpInst::Predicate pre = I.getPredicate();
1724 if (constOp0 && constOp0->isNullValue() &&
1725 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1726 op = I.getOperand(1);
1727 } else if (constOp1 && constOp1->isNullValue() &&
1728 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1729 op = I.getOperand(0);
1732 IRBuilder<> IRB(&I);
1734 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1735 setShadow(&I, Shadow);
1736 setOrigin(&I, getOrigin(op));
1742 void visitICmpInst(ICmpInst &I) {
1743 if (!ClHandleICmp) {
1747 if (I.isEquality()) {
1748 handleEqualityComparison(I);
1752 assert(I.isRelational());
1753 if (ClHandleICmpExact) {
1754 handleRelationalComparisonExact(I);
1758 handleSignedRelationalComparison(I);
1762 assert(I.isUnsigned());
1763 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1764 handleRelationalComparisonExact(I);
1771 void visitFCmpInst(FCmpInst &I) {
1775 void handleShift(BinaryOperator &I) {
1776 IRBuilder<> IRB(&I);
1777 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1778 // Otherwise perform the same shift on S1.
1779 Value *S1 = getShadow(&I, 0);
1780 Value *S2 = getShadow(&I, 1);
1781 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1783 Value *V2 = I.getOperand(1);
1784 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1785 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1786 setOriginForNaryOp(I);
1789 void visitShl(BinaryOperator &I) { handleShift(I); }
1790 void visitAShr(BinaryOperator &I) { handleShift(I); }
1791 void visitLShr(BinaryOperator &I) { handleShift(I); }
1793 /// \brief Instrument llvm.memmove
1795 /// At this point we don't know if llvm.memmove will be inlined or not.
1796 /// If we don't instrument it and it gets inlined,
1797 /// our interceptor will not kick in and we will lose the memmove.
1798 /// If we instrument the call here, but it does not get inlined,
1799 /// we will memove the shadow twice: which is bad in case
1800 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1802 /// Similar situation exists for memcpy and memset.
1803 void visitMemMoveInst(MemMoveInst &I) {
1804 IRBuilder<> IRB(&I);
1807 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1808 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1809 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1810 I.eraseFromParent();
1813 // Similar to memmove: avoid copying shadow twice.
1814 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1815 // FIXME: consider doing manual inline for small constant sizes and proper
1817 void visitMemCpyInst(MemCpyInst &I) {
1818 IRBuilder<> IRB(&I);
1821 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1822 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1823 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1824 I.eraseFromParent();
1828 void visitMemSetInst(MemSetInst &I) {
1829 IRBuilder<> IRB(&I);
1832 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1833 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1834 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1835 I.eraseFromParent();
1838 void visitVAStartInst(VAStartInst &I) {
1839 VAHelper->visitVAStartInst(I);
1842 void visitVACopyInst(VACopyInst &I) {
1843 VAHelper->visitVACopyInst(I);
1846 enum IntrinsicKind {
1847 IK_DoesNotAccessMemory,
1852 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1853 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1854 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1855 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1856 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1857 const int UnknownModRefBehavior = IK_WritesMemory;
1858 #define GET_INTRINSIC_MODREF_BEHAVIOR
1859 #define ModRefBehavior IntrinsicKind
1860 #include "llvm/IR/Intrinsics.gen"
1861 #undef ModRefBehavior
1862 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1865 /// \brief Handle vector store-like intrinsics.
1867 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1868 /// has 1 pointer argument and 1 vector argument, returns void.
1869 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1870 IRBuilder<> IRB(&I);
1871 Value* Addr = I.getArgOperand(0);
1872 Value *Shadow = getShadow(&I, 1);
1873 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1875 // We don't know the pointer alignment (could be unaligned SSE store!).
1876 // Have to assume to worst case.
1877 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1879 if (ClCheckAccessAddress)
1880 insertShadowCheck(Addr, &I);
1882 // FIXME: use ClStoreCleanOrigin
1883 // FIXME: factor out common code from materializeStores
1884 if (MS.TrackOrigins)
1885 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
1889 /// \brief Handle vector load-like intrinsics.
1891 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1892 /// has 1 pointer argument, returns a vector.
1893 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1894 IRBuilder<> IRB(&I);
1895 Value *Addr = I.getArgOperand(0);
1897 Type *ShadowTy = getShadowTy(&I);
1898 if (PropagateShadow) {
1899 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1900 // We don't know the pointer alignment (could be unaligned SSE load!).
1901 // Have to assume to worst case.
1902 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1904 setShadow(&I, getCleanShadow(&I));
1907 if (ClCheckAccessAddress)
1908 insertShadowCheck(Addr, &I);
1910 if (MS.TrackOrigins) {
1911 if (PropagateShadow)
1912 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
1914 setOrigin(&I, getCleanOrigin());
1919 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1921 /// Instrument intrinsics with any number of arguments of the same type,
1922 /// equal to the return type. The type should be simple (no aggregates or
1923 /// pointers; vectors are fine).
1924 /// Caller guarantees that this intrinsic does not access memory.
1925 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1926 Type *RetTy = I.getType();
1927 if (!(RetTy->isIntOrIntVectorTy() ||
1928 RetTy->isFPOrFPVectorTy() ||
1929 RetTy->isX86_MMXTy()))
1932 unsigned NumArgOperands = I.getNumArgOperands();
1934 for (unsigned i = 0; i < NumArgOperands; ++i) {
1935 Type *Ty = I.getArgOperand(i)->getType();
1940 IRBuilder<> IRB(&I);
1941 ShadowAndOriginCombiner SC(this, IRB);
1942 for (unsigned i = 0; i < NumArgOperands; ++i)
1943 SC.Add(I.getArgOperand(i));
1949 /// \brief Heuristically instrument unknown intrinsics.
1951 /// The main purpose of this code is to do something reasonable with all
1952 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1953 /// We recognize several classes of intrinsics by their argument types and
1954 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1955 /// sure that we know what the intrinsic does.
1957 /// We special-case intrinsics where this approach fails. See llvm.bswap
1958 /// handling as an example of that.
1959 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1960 unsigned NumArgOperands = I.getNumArgOperands();
1961 if (NumArgOperands == 0)
1964 Intrinsic::ID iid = I.getIntrinsicID();
1965 IntrinsicKind IK = getIntrinsicKind(iid);
1966 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1967 bool WritesMemory = IK == IK_WritesMemory;
1968 assert(!(OnlyReadsMemory && WritesMemory));
1970 if (NumArgOperands == 2 &&
1971 I.getArgOperand(0)->getType()->isPointerTy() &&
1972 I.getArgOperand(1)->getType()->isVectorTy() &&
1973 I.getType()->isVoidTy() &&
1975 // This looks like a vector store.
1976 return handleVectorStoreIntrinsic(I);
1979 if (NumArgOperands == 1 &&
1980 I.getArgOperand(0)->getType()->isPointerTy() &&
1981 I.getType()->isVectorTy() &&
1983 // This looks like a vector load.
1984 return handleVectorLoadIntrinsic(I);
1987 if (!OnlyReadsMemory && !WritesMemory)
1988 if (maybeHandleSimpleNomemIntrinsic(I))
1991 // FIXME: detect and handle SSE maskstore/maskload
1995 void handleBswap(IntrinsicInst &I) {
1996 IRBuilder<> IRB(&I);
1997 Value *Op = I.getArgOperand(0);
1998 Type *OpType = Op->getType();
1999 Function *BswapFunc = Intrinsic::getDeclaration(
2000 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
2001 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2002 setOrigin(&I, getOrigin(Op));
2005 // \brief Instrument vector convert instrinsic.
2007 // This function instruments intrinsics like cvtsi2ss:
2008 // %Out = int_xxx_cvtyyy(%ConvertOp)
2010 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2011 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2012 // number \p Out elements, and (if has 2 arguments) copies the rest of the
2013 // elements from \p CopyOp.
2014 // In most cases conversion involves floating-point value which may trigger a
2015 // hardware exception when not fully initialized. For this reason we require
2016 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2017 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2018 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2019 // return a fully initialized value.
2020 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2021 IRBuilder<> IRB(&I);
2022 Value *CopyOp, *ConvertOp;
2024 switch (I.getNumArgOperands()) {
2026 assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
2028 CopyOp = I.getArgOperand(0);
2029 ConvertOp = I.getArgOperand(1);
2032 ConvertOp = I.getArgOperand(0);
2036 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2039 // The first *NumUsedElements* elements of ConvertOp are converted to the
2040 // same number of output elements. The rest of the output is copied from
2041 // CopyOp, or (if not available) filled with zeroes.
2042 // Combine shadow for elements of ConvertOp that are used in this operation,
2043 // and insert a check.
2044 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2045 // int->any conversion.
2046 Value *ConvertShadow = getShadow(ConvertOp);
2047 Value *AggShadow = nullptr;
2048 if (ConvertOp->getType()->isVectorTy()) {
2049 AggShadow = IRB.CreateExtractElement(
2050 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2051 for (int i = 1; i < NumUsedElements; ++i) {
2052 Value *MoreShadow = IRB.CreateExtractElement(
2053 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2054 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2057 AggShadow = ConvertShadow;
2059 assert(AggShadow->getType()->isIntegerTy());
2060 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2062 // Build result shadow by zero-filling parts of CopyOp shadow that come from
2065 assert(CopyOp->getType() == I.getType());
2066 assert(CopyOp->getType()->isVectorTy());
2067 Value *ResultShadow = getShadow(CopyOp);
2068 Type *EltTy = ResultShadow->getType()->getVectorElementType();
2069 for (int i = 0; i < NumUsedElements; ++i) {
2070 ResultShadow = IRB.CreateInsertElement(
2071 ResultShadow, ConstantInt::getNullValue(EltTy),
2072 ConstantInt::get(IRB.getInt32Ty(), i));
2074 setShadow(&I, ResultShadow);
2075 setOrigin(&I, getOrigin(CopyOp));
2077 setShadow(&I, getCleanShadow(&I));
2078 setOrigin(&I, getCleanOrigin());
2082 // Given a scalar or vector, extract lower 64 bits (or less), and return all
2083 // zeroes if it is zero, and all ones otherwise.
2084 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2085 if (S->getType()->isVectorTy())
2086 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2087 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2088 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2089 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2092 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2093 Type *T = S->getType();
2094 assert(T->isVectorTy());
2095 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2096 return IRB.CreateSExt(S2, T);
2099 // \brief Instrument vector shift instrinsic.
2101 // This function instruments intrinsics like int_x86_avx2_psll_w.
2102 // Intrinsic shifts %In by %ShiftSize bits.
2103 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2104 // size, and the rest is ignored. Behavior is defined even if shift size is
2105 // greater than register (or field) width.
2106 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2107 assert(I.getNumArgOperands() == 2);
2108 IRBuilder<> IRB(&I);
2109 // If any of the S2 bits are poisoned, the whole thing is poisoned.
2110 // Otherwise perform the same shift on S1.
2111 Value *S1 = getShadow(&I, 0);
2112 Value *S2 = getShadow(&I, 1);
2113 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2114 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2115 Value *V1 = I.getOperand(0);
2116 Value *V2 = I.getOperand(1);
2117 Value *Shift = IRB.CreateCall(I.getCalledValue(),
2118 {IRB.CreateBitCast(S1, V1->getType()), V2});
2119 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2120 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2121 setOriginForNaryOp(I);
2124 // \brief Get an X86_MMX-sized vector type.
2125 Type *getMMXVectorTy(unsigned EltSizeInBits) {
2126 const unsigned X86_MMXSizeInBits = 64;
2127 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2128 X86_MMXSizeInBits / EltSizeInBits);
2131 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2133 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2135 case llvm::Intrinsic::x86_sse2_packsswb_128:
2136 case llvm::Intrinsic::x86_sse2_packuswb_128:
2137 return llvm::Intrinsic::x86_sse2_packsswb_128;
2139 case llvm::Intrinsic::x86_sse2_packssdw_128:
2140 case llvm::Intrinsic::x86_sse41_packusdw:
2141 return llvm::Intrinsic::x86_sse2_packssdw_128;
2143 case llvm::Intrinsic::x86_avx2_packsswb:
2144 case llvm::Intrinsic::x86_avx2_packuswb:
2145 return llvm::Intrinsic::x86_avx2_packsswb;
2147 case llvm::Intrinsic::x86_avx2_packssdw:
2148 case llvm::Intrinsic::x86_avx2_packusdw:
2149 return llvm::Intrinsic::x86_avx2_packssdw;
2151 case llvm::Intrinsic::x86_mmx_packsswb:
2152 case llvm::Intrinsic::x86_mmx_packuswb:
2153 return llvm::Intrinsic::x86_mmx_packsswb;
2155 case llvm::Intrinsic::x86_mmx_packssdw:
2156 return llvm::Intrinsic::x86_mmx_packssdw;
2158 llvm_unreachable("unexpected intrinsic id");
2162 // \brief Instrument vector pack instrinsic.
2164 // This function instruments intrinsics like x86_mmx_packsswb, that
2165 // packs elements of 2 input vectors into half as many bits with saturation.
2166 // Shadow is propagated with the signed variant of the same intrinsic applied
2167 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2168 // EltSizeInBits is used only for x86mmx arguments.
2169 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
2170 assert(I.getNumArgOperands() == 2);
2171 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2172 IRBuilder<> IRB(&I);
2173 Value *S1 = getShadow(&I, 0);
2174 Value *S2 = getShadow(&I, 1);
2175 assert(isX86_MMX || S1->getType()->isVectorTy());
2177 // SExt and ICmpNE below must apply to individual elements of input vectors.
2178 // In case of x86mmx arguments, cast them to appropriate vector types and
2180 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2182 S1 = IRB.CreateBitCast(S1, T);
2183 S2 = IRB.CreateBitCast(S2, T);
2185 Value *S1_ext = IRB.CreateSExt(
2186 IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2187 Value *S2_ext = IRB.CreateSExt(
2188 IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
2190 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2191 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2192 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2195 Function *ShadowFn = Intrinsic::getDeclaration(
2196 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2199 IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
2200 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2202 setOriginForNaryOp(I);
2205 // \brief Instrument sum-of-absolute-differencies intrinsic.
2206 void handleVectorSadIntrinsic(IntrinsicInst &I) {
2207 const unsigned SignificantBitsPerResultElement = 16;
2208 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2209 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2210 unsigned ZeroBitsPerResultElement =
2211 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2213 IRBuilder<> IRB(&I);
2214 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2215 S = IRB.CreateBitCast(S, ResTy);
2216 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2218 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2219 S = IRB.CreateBitCast(S, getShadowTy(&I));
2221 setOriginForNaryOp(I);
2224 // \brief Instrument multiply-add intrinsic.
2225 void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2226 unsigned EltSizeInBits = 0) {
2227 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2228 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2229 IRBuilder<> IRB(&I);
2230 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2231 S = IRB.CreateBitCast(S, ResTy);
2232 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2234 S = IRB.CreateBitCast(S, getShadowTy(&I));
2236 setOriginForNaryOp(I);
2239 void visitIntrinsicInst(IntrinsicInst &I) {
2240 switch (I.getIntrinsicID()) {
2241 case llvm::Intrinsic::bswap:
2244 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2245 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2246 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2247 case llvm::Intrinsic::x86_avx512_cvtss2usi:
2248 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2249 case llvm::Intrinsic::x86_avx512_cvttss2usi:
2250 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2251 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2252 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2253 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2254 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2255 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2256 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2257 case llvm::Intrinsic::x86_sse2_cvtsd2si:
2258 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2259 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2260 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2261 case llvm::Intrinsic::x86_sse2_cvtss2sd:
2262 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2263 case llvm::Intrinsic::x86_sse2_cvttsd2si:
2264 case llvm::Intrinsic::x86_sse_cvtsi2ss:
2265 case llvm::Intrinsic::x86_sse_cvtsi642ss:
2266 case llvm::Intrinsic::x86_sse_cvtss2si64:
2267 case llvm::Intrinsic::x86_sse_cvtss2si:
2268 case llvm::Intrinsic::x86_sse_cvttss2si64:
2269 case llvm::Intrinsic::x86_sse_cvttss2si:
2270 handleVectorConvertIntrinsic(I, 1);
2272 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2273 case llvm::Intrinsic::x86_sse2_cvtps2pd:
2274 case llvm::Intrinsic::x86_sse_cvtps2pi:
2275 case llvm::Intrinsic::x86_sse_cvttps2pi:
2276 handleVectorConvertIntrinsic(I, 2);
2278 case llvm::Intrinsic::x86_avx2_psll_w:
2279 case llvm::Intrinsic::x86_avx2_psll_d:
2280 case llvm::Intrinsic::x86_avx2_psll_q:
2281 case llvm::Intrinsic::x86_avx2_pslli_w:
2282 case llvm::Intrinsic::x86_avx2_pslli_d:
2283 case llvm::Intrinsic::x86_avx2_pslli_q:
2284 case llvm::Intrinsic::x86_avx2_psrl_w:
2285 case llvm::Intrinsic::x86_avx2_psrl_d:
2286 case llvm::Intrinsic::x86_avx2_psrl_q:
2287 case llvm::Intrinsic::x86_avx2_psra_w:
2288 case llvm::Intrinsic::x86_avx2_psra_d:
2289 case llvm::Intrinsic::x86_avx2_psrli_w:
2290 case llvm::Intrinsic::x86_avx2_psrli_d:
2291 case llvm::Intrinsic::x86_avx2_psrli_q:
2292 case llvm::Intrinsic::x86_avx2_psrai_w:
2293 case llvm::Intrinsic::x86_avx2_psrai_d:
2294 case llvm::Intrinsic::x86_sse2_psll_w:
2295 case llvm::Intrinsic::x86_sse2_psll_d:
2296 case llvm::Intrinsic::x86_sse2_psll_q:
2297 case llvm::Intrinsic::x86_sse2_pslli_w:
2298 case llvm::Intrinsic::x86_sse2_pslli_d:
2299 case llvm::Intrinsic::x86_sse2_pslli_q:
2300 case llvm::Intrinsic::x86_sse2_psrl_w:
2301 case llvm::Intrinsic::x86_sse2_psrl_d:
2302 case llvm::Intrinsic::x86_sse2_psrl_q:
2303 case llvm::Intrinsic::x86_sse2_psra_w:
2304 case llvm::Intrinsic::x86_sse2_psra_d:
2305 case llvm::Intrinsic::x86_sse2_psrli_w:
2306 case llvm::Intrinsic::x86_sse2_psrli_d:
2307 case llvm::Intrinsic::x86_sse2_psrli_q:
2308 case llvm::Intrinsic::x86_sse2_psrai_w:
2309 case llvm::Intrinsic::x86_sse2_psrai_d:
2310 case llvm::Intrinsic::x86_mmx_psll_w:
2311 case llvm::Intrinsic::x86_mmx_psll_d:
2312 case llvm::Intrinsic::x86_mmx_psll_q:
2313 case llvm::Intrinsic::x86_mmx_pslli_w:
2314 case llvm::Intrinsic::x86_mmx_pslli_d:
2315 case llvm::Intrinsic::x86_mmx_pslli_q:
2316 case llvm::Intrinsic::x86_mmx_psrl_w:
2317 case llvm::Intrinsic::x86_mmx_psrl_d:
2318 case llvm::Intrinsic::x86_mmx_psrl_q:
2319 case llvm::Intrinsic::x86_mmx_psra_w:
2320 case llvm::Intrinsic::x86_mmx_psra_d:
2321 case llvm::Intrinsic::x86_mmx_psrli_w:
2322 case llvm::Intrinsic::x86_mmx_psrli_d:
2323 case llvm::Intrinsic::x86_mmx_psrli_q:
2324 case llvm::Intrinsic::x86_mmx_psrai_w:
2325 case llvm::Intrinsic::x86_mmx_psrai_d:
2326 handleVectorShiftIntrinsic(I, /* Variable */ false);
2328 case llvm::Intrinsic::x86_avx2_psllv_d:
2329 case llvm::Intrinsic::x86_avx2_psllv_d_256:
2330 case llvm::Intrinsic::x86_avx2_psllv_q:
2331 case llvm::Intrinsic::x86_avx2_psllv_q_256:
2332 case llvm::Intrinsic::x86_avx2_psrlv_d:
2333 case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2334 case llvm::Intrinsic::x86_avx2_psrlv_q:
2335 case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2336 case llvm::Intrinsic::x86_avx2_psrav_d:
2337 case llvm::Intrinsic::x86_avx2_psrav_d_256:
2338 handleVectorShiftIntrinsic(I, /* Variable */ true);
2341 case llvm::Intrinsic::x86_sse2_packsswb_128:
2342 case llvm::Intrinsic::x86_sse2_packssdw_128:
2343 case llvm::Intrinsic::x86_sse2_packuswb_128:
2344 case llvm::Intrinsic::x86_sse41_packusdw:
2345 case llvm::Intrinsic::x86_avx2_packsswb:
2346 case llvm::Intrinsic::x86_avx2_packssdw:
2347 case llvm::Intrinsic::x86_avx2_packuswb:
2348 case llvm::Intrinsic::x86_avx2_packusdw:
2349 handleVectorPackIntrinsic(I);
2352 case llvm::Intrinsic::x86_mmx_packsswb:
2353 case llvm::Intrinsic::x86_mmx_packuswb:
2354 handleVectorPackIntrinsic(I, 16);
2357 case llvm::Intrinsic::x86_mmx_packssdw:
2358 handleVectorPackIntrinsic(I, 32);
2361 case llvm::Intrinsic::x86_mmx_psad_bw:
2362 case llvm::Intrinsic::x86_sse2_psad_bw:
2363 case llvm::Intrinsic::x86_avx2_psad_bw:
2364 handleVectorSadIntrinsic(I);
2367 case llvm::Intrinsic::x86_sse2_pmadd_wd:
2368 case llvm::Intrinsic::x86_avx2_pmadd_wd:
2369 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2370 case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2371 handleVectorPmaddIntrinsic(I);
2374 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2375 handleVectorPmaddIntrinsic(I, 8);
2378 case llvm::Intrinsic::x86_mmx_pmadd_wd:
2379 handleVectorPmaddIntrinsic(I, 16);
2383 if (!handleUnknownIntrinsic(I))
2384 visitInstruction(I);
2389 void visitCallSite(CallSite CS) {
2390 Instruction &I = *CS.getInstruction();
2391 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2393 CallInst *Call = cast<CallInst>(&I);
2395 // For inline asm, do the usual thing: check argument shadow and mark all
2396 // outputs as clean. Note that any side effects of the inline asm that are
2397 // not immediately visible in its constraints are not handled.
2398 if (Call->isInlineAsm()) {
2399 visitInstruction(I);
2403 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
2405 // We are going to insert code that relies on the fact that the callee
2406 // will become a non-readonly function after it is instrumented by us. To
2407 // prevent this code from being optimized out, mark that function
2408 // non-readonly in advance.
2409 if (Function *Func = Call->getCalledFunction()) {
2410 // Clear out readonly/readnone attributes.
2412 B.addAttribute(Attribute::ReadOnly)
2413 .addAttribute(Attribute::ReadNone);
2414 Func->removeAttributes(AttributeSet::FunctionIndex,
2415 AttributeSet::get(Func->getContext(),
2416 AttributeSet::FunctionIndex,
2420 IRBuilder<> IRB(&I);
2422 unsigned ArgOffset = 0;
2423 DEBUG(dbgs() << " CallSite: " << I << "\n");
2424 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2425 ArgIt != End; ++ArgIt) {
2427 unsigned i = ArgIt - CS.arg_begin();
2428 if (!A->getType()->isSized()) {
2429 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2433 Value *Store = nullptr;
2434 // Compute the Shadow for arg even if it is ByVal, because
2435 // in that case getShadow() will copy the actual arg shadow to
2436 // __msan_param_tls.
2437 Value *ArgShadow = getShadow(A);
2438 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2439 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2440 " Shadow: " << *ArgShadow << "\n");
2441 bool ArgIsInitialized = false;
2442 const DataLayout &DL = F.getParent()->getDataLayout();
2443 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
2444 assert(A->getType()->isPointerTy() &&
2445 "ByVal argument is not a pointer!");
2446 Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
2447 if (ArgOffset + Size > kParamTLSSize) break;
2448 unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2449 unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
2450 Store = IRB.CreateMemCpy(ArgShadowBase,
2451 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2454 Size = DL.getTypeAllocSize(A->getType());
2455 if (ArgOffset + Size > kParamTLSSize) break;
2456 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2457 kShadowTLSAlignment);
2458 Constant *Cst = dyn_cast<Constant>(ArgShadow);
2459 if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
2461 if (MS.TrackOrigins && !ArgIsInitialized)
2462 IRB.CreateStore(getOrigin(A),
2463 getOriginPtrForArgument(A, IRB, ArgOffset));
2465 assert(Size != 0 && Store != nullptr);
2466 DEBUG(dbgs() << " Param:" << *Store << "\n");
2467 ArgOffset += RoundUpToAlignment(Size, 8);
2469 DEBUG(dbgs() << " done with call args\n");
2472 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
2473 if (FT->isVarArg()) {
2474 VAHelper->visitCallSite(CS, IRB);
2477 // Now, get the shadow for the RetVal.
2478 if (!I.getType()->isSized()) return;
2479 IRBuilder<> IRBBefore(&I);
2480 // Until we have full dynamic coverage, make sure the retval shadow is 0.
2481 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
2482 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
2483 Instruction *NextInsn = nullptr;
2485 NextInsn = I.getNextNode();
2487 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2488 if (!NormalDest->getSinglePredecessor()) {
2489 // FIXME: this case is tricky, so we are just conservative here.
2490 // Perhaps we need to split the edge between this BB and NormalDest,
2491 // but a naive attempt to use SplitEdge leads to a crash.
2492 setShadow(&I, getCleanShadow(&I));
2493 setOrigin(&I, getCleanOrigin());
2496 NextInsn = NormalDest->getFirstInsertionPt();
2498 "Could not find insertion point for retval shadow load");
2500 IRBuilder<> IRBAfter(NextInsn);
2501 Value *RetvalShadow =
2502 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2503 kShadowTLSAlignment, "_msret");
2504 setShadow(&I, RetvalShadow);
2505 if (MS.TrackOrigins)
2506 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2509 void visitReturnInst(ReturnInst &I) {
2510 IRBuilder<> IRB(&I);
2511 Value *RetVal = I.getReturnValue();
2512 if (!RetVal) return;
2513 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2514 if (CheckReturnValue) {
2515 insertShadowCheck(RetVal, &I);
2516 Value *Shadow = getCleanShadow(RetVal);
2517 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2519 Value *Shadow = getShadow(RetVal);
2520 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2521 // FIXME: make it conditional if ClStoreCleanOrigin==0
2522 if (MS.TrackOrigins)
2523 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2527 void visitPHINode(PHINode &I) {
2528 IRBuilder<> IRB(&I);
2529 if (!PropagateShadow) {
2530 setShadow(&I, getCleanShadow(&I));
2531 setOrigin(&I, getCleanOrigin());
2535 ShadowPHINodes.push_back(&I);
2536 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2538 if (MS.TrackOrigins)
2539 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2543 void visitAllocaInst(AllocaInst &I) {
2544 setShadow(&I, getCleanShadow(&I));
2545 setOrigin(&I, getCleanOrigin());
2546 IRBuilder<> IRB(I.getNextNode());
2547 const DataLayout &DL = F.getParent()->getDataLayout();
2548 uint64_t Size = DL.getTypeAllocSize(I.getAllocatedType());
2549 if (PoisonStack && ClPoisonStackWithCall) {
2550 IRB.CreateCall(MS.MsanPoisonStackFn,
2551 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2552 ConstantInt::get(MS.IntptrTy, Size)});
2554 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2555 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2556 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2559 if (PoisonStack && MS.TrackOrigins) {
2560 SmallString<2048> StackDescriptionStorage;
2561 raw_svector_ostream StackDescription(StackDescriptionStorage);
2562 // We create a string with a description of the stack allocation and
2563 // pass it into __msan_set_alloca_origin.
2564 // It will be printed by the run-time if stack-originated UMR is found.
2565 // The first 4 bytes of the string are set to '----' and will be replaced
2566 // by __msan_va_arg_overflow_size_tls at the first call.
2567 StackDescription << "----" << I.getName() << "@" << F.getName();
2569 createPrivateNonConstGlobalForString(*F.getParent(),
2570 StackDescription.str());
2572 IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
2573 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2574 ConstantInt::get(MS.IntptrTy, Size),
2575 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2576 IRB.CreatePointerCast(&F, MS.IntptrTy)});
2580 void visitSelectInst(SelectInst& I) {
2581 IRBuilder<> IRB(&I);
2582 // a = select b, c, d
2583 Value *B = I.getCondition();
2584 Value *C = I.getTrueValue();
2585 Value *D = I.getFalseValue();
2586 Value *Sb = getShadow(B);
2587 Value *Sc = getShadow(C);
2588 Value *Sd = getShadow(D);
2590 // Result shadow if condition shadow is 0.
2591 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2593 if (I.getType()->isAggregateType()) {
2594 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2595 // an extra "select". This results in much more compact IR.
2596 // Sa = select Sb, poisoned, (select b, Sc, Sd)
2597 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
2599 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2600 // If Sb (condition is poisoned), look for bits in c and d that are equal
2601 // and both unpoisoned.
2602 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2604 // Cast arguments to shadow-compatible type.
2605 C = CreateAppToShadowCast(IRB, C);
2606 D = CreateAppToShadowCast(IRB, D);
2608 // Result shadow if condition shadow is 1.
2609 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
2611 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2613 if (MS.TrackOrigins) {
2614 // Origins are always i32, so any vector conditions must be flattened.
2615 // FIXME: consider tracking vector origins for app vectors?
2616 if (B->getType()->isVectorTy()) {
2617 Type *FlatTy = getShadowTyNoVec(B->getType());
2618 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
2619 ConstantInt::getNullValue(FlatTy));
2620 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
2621 ConstantInt::getNullValue(FlatTy));
2623 // a = select b, c, d
2624 // Oa = Sb ? Ob : (b ? Oc : Od)
2626 &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2627 IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2628 getOrigin(I.getFalseValue()))));
2632 void visitLandingPadInst(LandingPadInst &I) {
2634 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2635 setShadow(&I, getCleanShadow(&I));
2636 setOrigin(&I, getCleanOrigin());
2639 void visitGetElementPtrInst(GetElementPtrInst &I) {
2643 void visitExtractValueInst(ExtractValueInst &I) {
2644 IRBuilder<> IRB(&I);
2645 Value *Agg = I.getAggregateOperand();
2646 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2647 Value *AggShadow = getShadow(Agg);
2648 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2649 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2650 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2651 setShadow(&I, ResShadow);
2652 setOriginForNaryOp(I);
2655 void visitInsertValueInst(InsertValueInst &I) {
2656 IRBuilder<> IRB(&I);
2657 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2658 Value *AggShadow = getShadow(I.getAggregateOperand());
2659 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2660 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2661 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2662 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2663 DEBUG(dbgs() << " Res: " << *Res << "\n");
2665 setOriginForNaryOp(I);
2668 void dumpInst(Instruction &I) {
2669 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2670 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2672 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2674 errs() << "QQQ " << I << "\n";
2677 void visitResumeInst(ResumeInst &I) {
2678 DEBUG(dbgs() << "Resume: " << I << "\n");
2679 // Nothing to do here.
2682 void visitInstruction(Instruction &I) {
2683 // Everything else: stop propagating and check for poisoned shadow.
2684 if (ClDumpStrictInstructions)
2686 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2687 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2688 insertShadowCheck(I.getOperand(i), &I);
2689 setShadow(&I, getCleanShadow(&I));
2690 setOrigin(&I, getCleanOrigin());
2694 /// \brief AMD64-specific implementation of VarArgHelper.
2695 struct VarArgAMD64Helper : public VarArgHelper {
2696 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2697 // See a comment in visitCallSite for more details.
2698 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
2699 static const unsigned AMD64FpEndOffset = 176;
2702 MemorySanitizer &MS;
2703 MemorySanitizerVisitor &MSV;
2704 Value *VAArgTLSCopy;
2705 Value *VAArgOverflowSize;
2707 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2709 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2710 MemorySanitizerVisitor &MSV)
2711 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2712 VAArgOverflowSize(nullptr) {}
2714 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2716 ArgKind classifyArgument(Value* arg) {
2717 // A very rough approximation of X86_64 argument classification rules.
2718 Type *T = arg->getType();
2719 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2720 return AK_FloatingPoint;
2721 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2722 return AK_GeneralPurpose;
2723 if (T->isPointerTy())
2724 return AK_GeneralPurpose;
2728 // For VarArg functions, store the argument shadow in an ABI-specific format
2729 // that corresponds to va_list layout.
2730 // We do this because Clang lowers va_arg in the frontend, and this pass
2731 // only sees the low level code that deals with va_list internals.
2732 // A much easier alternative (provided that Clang emits va_arg instructions)
2733 // would have been to associate each live instance of va_list with a copy of
2734 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2736 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2737 unsigned GpOffset = 0;
2738 unsigned FpOffset = AMD64GpEndOffset;
2739 unsigned OverflowOffset = AMD64FpEndOffset;
2740 const DataLayout &DL = F.getParent()->getDataLayout();
2741 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2742 ArgIt != End; ++ArgIt) {
2744 unsigned ArgNo = CS.getArgumentNo(ArgIt);
2745 bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2747 // ByVal arguments always go to the overflow area.
2748 assert(A->getType()->isPointerTy());
2749 Type *RealTy = A->getType()->getPointerElementType();
2750 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
2751 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
2752 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2753 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2754 ArgSize, kShadowTLSAlignment);
2756 ArgKind AK = classifyArgument(A);
2757 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2759 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2763 case AK_GeneralPurpose:
2764 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2767 case AK_FloatingPoint:
2768 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2772 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
2773 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2774 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2776 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2779 Constant *OverflowSize =
2780 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2781 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2784 /// \brief Compute the shadow address for a given va_arg.
2785 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2787 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2788 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2789 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2793 void visitVAStartInst(VAStartInst &I) override {
2794 IRBuilder<> IRB(&I);
2795 VAStartInstrumentationList.push_back(&I);
2796 Value *VAListTag = I.getArgOperand(0);
2797 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2799 // Unpoison the whole __va_list_tag.
2800 // FIXME: magic ABI constants.
2801 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2802 /* size */24, /* alignment */8, false);
2805 void visitVACopyInst(VACopyInst &I) override {
2806 IRBuilder<> IRB(&I);
2807 Value *VAListTag = I.getArgOperand(0);
2808 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2810 // Unpoison the whole __va_list_tag.
2811 // FIXME: magic ABI constants.
2812 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2813 /* size */24, /* alignment */8, false);
2816 void finalizeInstrumentation() override {
2817 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2818 "finalizeInstrumentation called twice");
2819 if (!VAStartInstrumentationList.empty()) {
2820 // If there is a va_start in this function, make a backup copy of
2821 // va_arg_tls somewhere in the function entry block.
2822 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2823 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2825 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2827 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2828 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2831 // Instrument va_start.
2832 // Copy va_list shadow from the backup copy of the TLS contents.
2833 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2834 CallInst *OrigInst = VAStartInstrumentationList[i];
2835 IRBuilder<> IRB(OrigInst->getNextNode());
2836 Value *VAListTag = OrigInst->getArgOperand(0);
2838 Value *RegSaveAreaPtrPtr =
2840 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2841 ConstantInt::get(MS.IntptrTy, 16)),
2842 Type::getInt64PtrTy(*MS.C));
2843 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2844 Value *RegSaveAreaShadowPtr =
2845 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2846 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2847 AMD64FpEndOffset, 16);
2849 Value *OverflowArgAreaPtrPtr =
2851 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2852 ConstantInt::get(MS.IntptrTy, 8)),
2853 Type::getInt64PtrTy(*MS.C));
2854 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2855 Value *OverflowArgAreaShadowPtr =
2856 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2857 Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
2859 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2864 /// \brief MIPS64-specific implementation of VarArgHelper.
2865 struct VarArgMIPS64Helper : public VarArgHelper {
2867 MemorySanitizer &MS;
2868 MemorySanitizerVisitor &MSV;
2869 Value *VAArgTLSCopy;
2872 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2874 VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
2875 MemorySanitizerVisitor &MSV)
2876 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2877 VAArgSize(nullptr) {}
2879 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2880 unsigned VAArgOffset = 0;
2881 const DataLayout &DL = F.getParent()->getDataLayout();
2882 for (CallSite::arg_iterator ArgIt = CS.arg_begin() + 1, End = CS.arg_end();
2883 ArgIt != End; ++ArgIt) {
2886 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
2887 #if defined(__MIPSEB__) || defined(MIPSEB)
2888 // Adjusting the shadow for argument with size < 8 to match the placement
2889 // of bits in big endian system
2891 VAArgOffset += (8 - ArgSize);
2893 Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
2894 VAArgOffset += ArgSize;
2895 VAArgOffset = RoundUpToAlignment(VAArgOffset, 8);
2896 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2899 Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
2900 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
2901 // a new class member i.e. it is the total size of all VarArgs.
2902 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
2905 /// \brief Compute the shadow address for a given va_arg.
2906 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2908 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2909 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2910 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2914 void visitVAStartInst(VAStartInst &I) override {
2915 IRBuilder<> IRB(&I);
2916 VAStartInstrumentationList.push_back(&I);
2917 Value *VAListTag = I.getArgOperand(0);
2918 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2919 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2920 /* size */8, /* alignment */8, false);
2923 void visitVACopyInst(VACopyInst &I) override {
2924 IRBuilder<> IRB(&I);
2925 Value *VAListTag = I.getArgOperand(0);
2926 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2927 // Unpoison the whole __va_list_tag.
2928 // FIXME: magic ABI constants.
2929 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2930 /* size */8, /* alignment */8, false);
2933 void finalizeInstrumentation() override {
2934 assert(!VAArgSize && !VAArgTLSCopy &&
2935 "finalizeInstrumentation called twice");
2936 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2937 VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2938 Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
2941 if (!VAStartInstrumentationList.empty()) {
2942 // If there is a va_start in this function, make a backup copy of
2943 // va_arg_tls somewhere in the function entry block.
2944 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2945 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2948 // Instrument va_start.
2949 // Copy va_list shadow from the backup copy of the TLS contents.
2950 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2951 CallInst *OrigInst = VAStartInstrumentationList[i];
2952 IRBuilder<> IRB(OrigInst->getNextNode());
2953 Value *VAListTag = OrigInst->getArgOperand(0);
2954 Value *RegSaveAreaPtrPtr =
2955 IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2956 Type::getInt64PtrTy(*MS.C));
2957 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2958 Value *RegSaveAreaShadowPtr =
2959 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2960 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
2965 /// \brief A no-op implementation of VarArgHelper.
2966 struct VarArgNoOpHelper : public VarArgHelper {
2967 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2968 MemorySanitizerVisitor &MSV) {}
2970 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
2972 void visitVAStartInst(VAStartInst &I) override {}
2974 void visitVACopyInst(VACopyInst &I) override {}
2976 void finalizeInstrumentation() override {}
2979 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
2980 MemorySanitizerVisitor &Visitor) {
2981 // VarArg handling is only implemented on AMD64. False positives are possible
2982 // on other platforms.
2983 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2984 if (TargetTriple.getArch() == llvm::Triple::x86_64)
2985 return new VarArgAMD64Helper(Func, Msan, Visitor);
2986 else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
2987 TargetTriple.getArch() == llvm::Triple::mips64el)
2988 return new VarArgMIPS64Helper(Func, Msan, Visitor);
2990 return new VarArgNoOpHelper(Func, Msan, Visitor);
2995 bool MemorySanitizer::runOnFunction(Function &F) {
2996 if (&F == MsanCtorFunction)
2998 MemorySanitizerVisitor Visitor(F, *this);
3000 // Clear out readonly/readnone attributes.
3002 B.addAttribute(Attribute::ReadOnly)
3003 .addAttribute(Attribute::ReadNone);
3004 F.removeAttributes(AttributeSet::FunctionIndex,
3005 AttributeSet::get(F.getContext(),
3006 AttributeSet::FunctionIndex, B));
3008 return Visitor.runOnFunction();