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 // VMA size definition for architecture that support multiple sizes.
124 // AArch64 has 3 VMA sizes: 39, 42 and 48.
125 #ifndef SANITIZER_AARCH64_VMA
126 # define SANITIZER_AARCH64_VMA 39
128 # if SANITIZER_AARCH64_VMA != 39 && SANITIZER_AARCH64_VMA != 42
129 # error "invalid SANITIZER_AARCH64_VMA size"
133 static const unsigned kOriginSize = 4;
134 static const unsigned kMinOriginAlignment = 4;
135 static const unsigned kShadowTLSAlignment = 8;
137 // These constants must be kept in sync with the ones in msan.h.
138 static const unsigned kParamTLSSize = 800;
139 static const unsigned kRetvalTLSSize = 800;
141 // Accesses sizes are powers of two: 1, 2, 4, 8.
142 static const size_t kNumberOfAccessSizes = 4;
144 /// \brief Track origins of uninitialized values.
146 /// Adds a section to MemorySanitizer report that points to the allocation
147 /// (stack or heap) the uninitialized bits came from originally.
148 static cl::opt<int> ClTrackOrigins("msan-track-origins",
149 cl::desc("Track origins (allocation sites) of poisoned memory"),
150 cl::Hidden, cl::init(0));
151 static cl::opt<bool> ClKeepGoing("msan-keep-going",
152 cl::desc("keep going after reporting a UMR"),
153 cl::Hidden, cl::init(false));
154 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
155 cl::desc("poison uninitialized stack variables"),
156 cl::Hidden, cl::init(true));
157 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
158 cl::desc("poison uninitialized stack variables with a call"),
159 cl::Hidden, cl::init(false));
160 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
161 cl::desc("poison uninitialized stack variables with the given pattern"),
162 cl::Hidden, cl::init(0xff));
163 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
164 cl::desc("poison undef temps"),
165 cl::Hidden, cl::init(true));
167 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
168 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
169 cl::Hidden, cl::init(true));
171 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
172 cl::desc("exact handling of relational integer ICmp"),
173 cl::Hidden, cl::init(false));
175 // This flag controls whether we check the shadow of the address
176 // operand of load or store. Such bugs are very rare, since load from
177 // a garbage address typically results in SEGV, but still happen
178 // (e.g. only lower bits of address are garbage, or the access happens
179 // early at program startup where malloc-ed memory is more likely to
180 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
181 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
182 cl::desc("report accesses through a pointer which has poisoned shadow"),
183 cl::Hidden, cl::init(true));
185 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
186 cl::desc("print out instructions with default strict semantics"),
187 cl::Hidden, cl::init(false));
189 static cl::opt<int> ClInstrumentationWithCallThreshold(
190 "msan-instrumentation-with-call-threshold",
192 "If the function being instrumented requires more than "
193 "this number of checks and origin stores, use callbacks instead of "
194 "inline checks (-1 means never use callbacks)."),
195 cl::Hidden, cl::init(3500));
197 // This is an experiment to enable handling of cases where shadow is a non-zero
198 // compile-time constant. For some unexplainable reason they were silently
199 // ignored in the instrumentation.
200 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
201 cl::desc("Insert checks for constant shadow values"),
202 cl::Hidden, cl::init(false));
204 static const char *const kMsanModuleCtorName = "msan.module_ctor";
205 static const char *const kMsanInitName = "__msan_init";
209 // Memory map parameters used in application-to-shadow address calculation.
210 // Offset = (Addr & ~AndMask) ^ XorMask
211 // Shadow = ShadowBase + Offset
212 // Origin = OriginBase + Offset
213 struct MemoryMapParams {
220 struct PlatformMemoryMapParams {
221 const MemoryMapParams *bits32;
222 const MemoryMapParams *bits64;
226 static const MemoryMapParams Linux_I386_MemoryMapParams = {
227 0x000080000000, // AndMask
228 0, // XorMask (not used)
229 0, // ShadowBase (not used)
230 0x000040000000, // OriginBase
234 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
235 0x400000000000, // AndMask
236 0, // XorMask (not used)
237 0, // ShadowBase (not used)
238 0x200000000000, // OriginBase
242 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
243 0x004000000000, // AndMask
244 0, // XorMask (not used)
245 0, // ShadowBase (not used)
246 0x002000000000, // OriginBase
250 static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
251 0x200000000000, // AndMask
252 0x100000000000, // XorMask
253 0x080000000000, // ShadowBase
254 0x1C0000000000, // OriginBase
258 static const MemoryMapParams Linux_AArch64_MemoryMapParams = {
259 #if SANITIZER_AARCH64_VMA == 39
260 0x007C00000000, // AndMask
261 0x000100000000, // XorMask
262 0x004000000000, // ShadowBase
263 0x004300000000, // OriginBase
264 #elif SANITIZER_AARCH64_VMA == 42
265 0x03E000000000, // AndMask
266 0x001000000000, // XorMask
267 0x010000000000, // ShadowBase
268 0x012000000000, // OriginBase
273 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
274 0x000180000000, // AndMask
275 0x000040000000, // XorMask
276 0x000020000000, // ShadowBase
277 0x000700000000, // OriginBase
281 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
282 0xc00000000000, // AndMask
283 0x200000000000, // XorMask
284 0x100000000000, // ShadowBase
285 0x380000000000, // OriginBase
288 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
289 &Linux_I386_MemoryMapParams,
290 &Linux_X86_64_MemoryMapParams,
293 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
295 &Linux_MIPS64_MemoryMapParams,
298 static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
300 &Linux_PowerPC64_MemoryMapParams,
303 static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = {
305 &Linux_AArch64_MemoryMapParams,
308 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
309 &FreeBSD_I386_MemoryMapParams,
310 &FreeBSD_X86_64_MemoryMapParams,
313 /// \brief An instrumentation pass implementing detection of uninitialized
316 /// MemorySanitizer: instrument the code in module to find
317 /// uninitialized reads.
318 class MemorySanitizer : public FunctionPass {
320 MemorySanitizer(int TrackOrigins = 0)
322 TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
323 WarningFn(nullptr) {}
324 const char *getPassName() const override { return "MemorySanitizer"; }
325 bool runOnFunction(Function &F) override;
326 bool doInitialization(Module &M) override;
327 static char ID; // Pass identification, replacement for typeid.
330 void initializeCallbacks(Module &M);
332 /// \brief Track origins (allocation points) of uninitialized values.
338 /// \brief Thread-local shadow storage for function parameters.
339 GlobalVariable *ParamTLS;
340 /// \brief Thread-local origin storage for function parameters.
341 GlobalVariable *ParamOriginTLS;
342 /// \brief Thread-local shadow storage for function return value.
343 GlobalVariable *RetvalTLS;
344 /// \brief Thread-local origin storage for function return value.
345 GlobalVariable *RetvalOriginTLS;
346 /// \brief Thread-local shadow storage for in-register va_arg function
347 /// parameters (x86_64-specific).
348 GlobalVariable *VAArgTLS;
349 /// \brief Thread-local shadow storage for va_arg overflow area
350 /// (x86_64-specific).
351 GlobalVariable *VAArgOverflowSizeTLS;
352 /// \brief Thread-local space used to pass origin value to the UMR reporting
354 GlobalVariable *OriginTLS;
356 /// \brief The run-time callback to print a warning.
358 // These arrays are indexed by log2(AccessSize).
359 Value *MaybeWarningFn[kNumberOfAccessSizes];
360 Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
362 /// \brief Run-time helper that generates a new origin value for a stack
364 Value *MsanSetAllocaOrigin4Fn;
365 /// \brief Run-time helper that poisons stack on function entry.
366 Value *MsanPoisonStackFn;
367 /// \brief Run-time helper that records a store (or any event) of an
368 /// uninitialized value and returns an updated origin id encoding this info.
369 Value *MsanChainOriginFn;
370 /// \brief MSan runtime replacements for memmove, memcpy and memset.
371 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
373 /// \brief Memory map parameters used in application-to-shadow calculation.
374 const MemoryMapParams *MapParams;
376 MDNode *ColdCallWeights;
377 /// \brief Branch weights for origin store.
378 MDNode *OriginStoreWeights;
379 /// \brief An empty volatile inline asm that prevents callback merge.
381 Function *MsanCtorFunction;
383 friend struct MemorySanitizerVisitor;
384 friend struct VarArgAMD64Helper;
385 friend struct VarArgMIPS64Helper;
387 } // anonymous namespace
389 char MemorySanitizer::ID = 0;
390 INITIALIZE_PASS(MemorySanitizer, "msan",
391 "MemorySanitizer: detects uninitialized reads.",
394 FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
395 return new MemorySanitizer(TrackOrigins);
398 /// \brief Create a non-const global initialized with the given string.
400 /// Creates a writable global for Str so that we can pass it to the
401 /// run-time lib. Runtime uses first 4 bytes of the string to store the
402 /// frame ID, so the string needs to be mutable.
403 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
405 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
406 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
407 GlobalValue::PrivateLinkage, StrConst, "");
410 /// \brief Insert extern declaration of runtime-provided functions and globals.
411 void MemorySanitizer::initializeCallbacks(Module &M) {
412 // Only do this once.
417 // Create the callback.
418 // FIXME: this function should have "Cold" calling conv,
419 // which is not yet implemented.
420 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
421 : "__msan_warning_noreturn";
422 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
424 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
426 unsigned AccessSize = 1 << AccessSizeIndex;
427 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
428 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
429 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
430 IRB.getInt32Ty(), nullptr);
432 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
433 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
434 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
435 IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
438 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
439 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
440 IRB.getInt8PtrTy(), IntptrTy, nullptr);
442 M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
443 IRB.getInt8PtrTy(), IntptrTy, nullptr);
444 MsanChainOriginFn = M.getOrInsertFunction(
445 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
446 MemmoveFn = M.getOrInsertFunction(
447 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
448 IRB.getInt8PtrTy(), IntptrTy, nullptr);
449 MemcpyFn = M.getOrInsertFunction(
450 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
452 MemsetFn = M.getOrInsertFunction(
453 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
457 RetvalTLS = new GlobalVariable(
458 M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
459 GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
460 GlobalVariable::InitialExecTLSModel);
461 RetvalOriginTLS = new GlobalVariable(
462 M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
463 "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
465 ParamTLS = new GlobalVariable(
466 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
467 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
468 GlobalVariable::InitialExecTLSModel);
469 ParamOriginTLS = new GlobalVariable(
470 M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
471 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
472 nullptr, GlobalVariable::InitialExecTLSModel);
474 VAArgTLS = new GlobalVariable(
475 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
476 GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
477 GlobalVariable::InitialExecTLSModel);
478 VAArgOverflowSizeTLS = new GlobalVariable(
479 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
480 "__msan_va_arg_overflow_size_tls", nullptr,
481 GlobalVariable::InitialExecTLSModel);
482 OriginTLS = new GlobalVariable(
483 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
484 "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
486 // We insert an empty inline asm after __msan_report* to avoid callback merge.
487 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
488 StringRef(""), StringRef(""),
489 /*hasSideEffects=*/true);
492 /// \brief Module-level initialization.
494 /// inserts a call to __msan_init to the module's constructor list.
495 bool MemorySanitizer::doInitialization(Module &M) {
496 auto &DL = M.getDataLayout();
498 Triple TargetTriple(M.getTargetTriple());
499 switch (TargetTriple.getOS()) {
500 case Triple::FreeBSD:
501 switch (TargetTriple.getArch()) {
503 MapParams = FreeBSD_X86_MemoryMapParams.bits64;
506 MapParams = FreeBSD_X86_MemoryMapParams.bits32;
509 report_fatal_error("unsupported architecture");
513 switch (TargetTriple.getArch()) {
515 MapParams = Linux_X86_MemoryMapParams.bits64;
518 MapParams = Linux_X86_MemoryMapParams.bits32;
521 case Triple::mips64el:
522 MapParams = Linux_MIPS_MemoryMapParams.bits64;
525 case Triple::ppc64le:
526 MapParams = Linux_PowerPC_MemoryMapParams.bits64;
528 case Triple::aarch64:
529 case Triple::aarch64_be:
530 MapParams = Linux_ARM_MemoryMapParams.bits64;
533 report_fatal_error("unsupported architecture");
537 report_fatal_error("unsupported operating system");
540 C = &(M.getContext());
542 IntptrTy = IRB.getIntPtrTy(DL);
543 OriginTy = IRB.getInt32Ty();
545 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
546 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
548 std::tie(MsanCtorFunction, std::ignore) =
549 createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
553 appendToGlobalCtors(M, MsanCtorFunction, 0);
556 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
557 IRB.getInt32(TrackOrigins), "__msan_track_origins");
560 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
561 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
568 /// \brief A helper class that handles instrumentation of VarArg
569 /// functions on a particular platform.
571 /// Implementations are expected to insert the instrumentation
572 /// necessary to propagate argument shadow through VarArg function
573 /// calls. Visit* methods are called during an InstVisitor pass over
574 /// the function, and should avoid creating new basic blocks. A new
575 /// instance of this class is created for each instrumented function.
576 struct VarArgHelper {
577 /// \brief Visit a CallSite.
578 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
580 /// \brief Visit a va_start call.
581 virtual void visitVAStartInst(VAStartInst &I) = 0;
583 /// \brief Visit a va_copy call.
584 virtual void visitVACopyInst(VACopyInst &I) = 0;
586 /// \brief Finalize function instrumentation.
588 /// This method is called after visiting all interesting (see above)
589 /// instructions in a function.
590 virtual void finalizeInstrumentation() = 0;
592 virtual ~VarArgHelper() {}
595 struct MemorySanitizerVisitor;
598 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
599 MemorySanitizerVisitor &Visitor);
601 unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
602 if (TypeSize <= 8) return 0;
603 return Log2_32_Ceil(TypeSize / 8);
606 /// This class does all the work for a given function. Store and Load
607 /// instructions store and load corresponding shadow and origin
608 /// values. Most instructions propagate shadow from arguments to their
609 /// return values. Certain instructions (most importantly, BranchInst)
610 /// test their argument shadow and print reports (with a runtime call) if it's
612 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
615 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
616 ValueMap<Value*, Value*> ShadowMap, OriginMap;
617 std::unique_ptr<VarArgHelper> VAHelper;
619 // The following flags disable parts of MSan instrumentation based on
620 // blacklist contents and command-line options.
622 bool PropagateShadow;
625 bool CheckReturnValue;
627 struct ShadowOriginAndInsertPoint {
630 Instruction *OrigIns;
631 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
632 : Shadow(S), Origin(O), OrigIns(I) { }
634 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
635 SmallVector<Instruction*, 16> StoreList;
637 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
638 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
639 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
640 InsertChecks = SanitizeFunction;
641 PropagateShadow = SanitizeFunction;
642 PoisonStack = SanitizeFunction && ClPoisonStack;
643 PoisonUndef = SanitizeFunction && ClPoisonUndef;
644 // FIXME: Consider using SpecialCaseList to specify a list of functions that
645 // must always return fully initialized values. For now, we hardcode "main".
646 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
648 DEBUG(if (!InsertChecks)
649 dbgs() << "MemorySanitizer is not inserting checks into '"
650 << F.getName() << "'\n");
653 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
654 if (MS.TrackOrigins <= 1) return V;
655 return IRB.CreateCall(MS.MsanChainOriginFn, V);
658 Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
659 const DataLayout &DL = F.getParent()->getDataLayout();
660 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
661 if (IntptrSize == kOriginSize) return Origin;
662 assert(IntptrSize == kOriginSize * 2);
663 Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
664 return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
667 /// \brief Fill memory range with the given origin value.
668 void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
669 unsigned Size, unsigned Alignment) {
670 const DataLayout &DL = F.getParent()->getDataLayout();
671 unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
672 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
673 assert(IntptrAlignment >= kMinOriginAlignment);
674 assert(IntptrSize >= kOriginSize);
677 unsigned CurrentAlignment = Alignment;
678 if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
679 Value *IntptrOrigin = originToIntptr(IRB, Origin);
680 Value *IntptrOriginPtr =
681 IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
682 for (unsigned i = 0; i < Size / IntptrSize; ++i) {
683 Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
685 IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
686 Ofs += IntptrSize / kOriginSize;
687 CurrentAlignment = IntptrAlignment;
691 for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
693 i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
694 IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
695 CurrentAlignment = kMinOriginAlignment;
699 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
700 unsigned Alignment, bool AsCall) {
701 const DataLayout &DL = F.getParent()->getDataLayout();
702 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
703 unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
704 if (isa<StructType>(Shadow->getType())) {
705 paintOrigin(IRB, updateOrigin(Origin, IRB),
706 getOriginPtr(Addr, IRB, Alignment), StoreSize,
709 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
710 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
711 if (ConstantShadow) {
712 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
713 paintOrigin(IRB, updateOrigin(Origin, IRB),
714 getOriginPtr(Addr, IRB, Alignment), StoreSize,
719 unsigned TypeSizeInBits =
720 DL.getTypeSizeInBits(ConvertedShadow->getType());
721 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
722 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
723 Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
724 Value *ConvertedShadow2 = IRB.CreateZExt(
725 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
726 IRB.CreateCall(Fn, {ConvertedShadow2,
727 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
730 Value *Cmp = IRB.CreateICmpNE(
731 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
732 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
733 Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
734 IRBuilder<> IRBNew(CheckTerm);
735 paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
736 getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
742 void materializeStores(bool InstrumentWithCalls) {
743 for (auto Inst : StoreList) {
744 StoreInst &SI = *dyn_cast<StoreInst>(Inst);
746 IRBuilder<> IRB(&SI);
747 Value *Val = SI.getValueOperand();
748 Value *Addr = SI.getPointerOperand();
749 Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
750 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
753 IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
754 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
757 if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
759 if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
761 if (MS.TrackOrigins && !SI.isAtomic())
762 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI.getAlignment(),
763 InstrumentWithCalls);
767 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
769 IRBuilder<> IRB(OrigIns);
770 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
771 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
772 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
774 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
775 if (ConstantShadow) {
776 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
777 if (MS.TrackOrigins) {
778 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
781 IRB.CreateCall(MS.WarningFn, {});
782 IRB.CreateCall(MS.EmptyAsm, {});
783 // FIXME: Insert UnreachableInst if !ClKeepGoing?
784 // This may invalidate some of the following checks and needs to be done
790 const DataLayout &DL = OrigIns->getModule()->getDataLayout();
792 unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
793 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
794 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
795 Value *Fn = MS.MaybeWarningFn[SizeIndex];
796 Value *ConvertedShadow2 =
797 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
798 IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
800 : (Value *)IRB.getInt32(0)});
802 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
803 getCleanShadow(ConvertedShadow), "_mscmp");
804 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
806 /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
808 IRB.SetInsertPoint(CheckTerm);
809 if (MS.TrackOrigins) {
810 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
813 IRB.CreateCall(MS.WarningFn, {});
814 IRB.CreateCall(MS.EmptyAsm, {});
815 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
819 void materializeChecks(bool InstrumentWithCalls) {
820 for (const auto &ShadowData : InstrumentationList) {
821 Instruction *OrigIns = ShadowData.OrigIns;
822 Value *Shadow = ShadowData.Shadow;
823 Value *Origin = ShadowData.Origin;
824 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
826 DEBUG(dbgs() << "DONE:\n" << F);
829 /// \brief Add MemorySanitizer instrumentation to a function.
830 bool runOnFunction() {
831 MS.initializeCallbacks(*F.getParent());
833 // In the presence of unreachable blocks, we may see Phi nodes with
834 // incoming nodes from such blocks. Since InstVisitor skips unreachable
835 // blocks, such nodes will not have any shadow value associated with them.
836 // It's easier to remove unreachable blocks than deal with missing shadow.
837 removeUnreachableBlocks(F);
839 // Iterate all BBs in depth-first order and create shadow instructions
840 // for all instructions (where applicable).
841 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
842 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
846 // Finalize PHI nodes.
847 for (PHINode *PN : ShadowPHINodes) {
848 PHINode *PNS = cast<PHINode>(getShadow(PN));
849 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
850 size_t NumValues = PN->getNumIncomingValues();
851 for (size_t v = 0; v < NumValues; v++) {
852 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
853 if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
857 VAHelper->finalizeInstrumentation();
859 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
860 InstrumentationList.size() + StoreList.size() >
861 (unsigned)ClInstrumentationWithCallThreshold;
863 // Delayed instrumentation of StoreInst.
864 // This may add new checks to be inserted later.
865 materializeStores(InstrumentWithCalls);
867 // Insert shadow value checks.
868 materializeChecks(InstrumentWithCalls);
873 /// \brief Compute the shadow type that corresponds to a given Value.
874 Type *getShadowTy(Value *V) {
875 return getShadowTy(V->getType());
878 /// \brief Compute the shadow type that corresponds to a given Type.
879 Type *getShadowTy(Type *OrigTy) {
880 if (!OrigTy->isSized()) {
883 // For integer type, shadow is the same as the original type.
884 // This may return weird-sized types like i1.
885 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
887 const DataLayout &DL = F.getParent()->getDataLayout();
888 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
889 uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
890 return VectorType::get(IntegerType::get(*MS.C, EltSize),
891 VT->getNumElements());
893 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
894 return ArrayType::get(getShadowTy(AT->getElementType()),
895 AT->getNumElements());
897 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
898 SmallVector<Type*, 4> Elements;
899 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
900 Elements.push_back(getShadowTy(ST->getElementType(i)));
901 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
902 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
905 uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
906 return IntegerType::get(*MS.C, TypeSize);
909 /// \brief Flatten a vector type.
910 Type *getShadowTyNoVec(Type *ty) {
911 if (VectorType *vt = dyn_cast<VectorType>(ty))
912 return IntegerType::get(*MS.C, vt->getBitWidth());
916 /// \brief Convert a shadow value to it's flattened variant.
917 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
918 Type *Ty = V->getType();
919 Type *NoVecTy = getShadowTyNoVec(Ty);
920 if (Ty == NoVecTy) return V;
921 return IRB.CreateBitCast(V, NoVecTy);
924 /// \brief Compute the integer shadow offset that corresponds to a given
925 /// application address.
927 /// Offset = (Addr & ~AndMask) ^ XorMask
928 Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
929 uint64_t AndMask = MS.MapParams->AndMask;
930 assert(AndMask != 0 && "AndMask shall be specified");
932 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
933 ConstantInt::get(MS.IntptrTy, ~AndMask));
935 uint64_t XorMask = MS.MapParams->XorMask;
937 OffsetLong = IRB.CreateXor(OffsetLong,
938 ConstantInt::get(MS.IntptrTy, XorMask));
942 /// \brief Compute the shadow address that corresponds to a given application
945 /// Shadow = ShadowBase + Offset
946 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
948 Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
949 uint64_t ShadowBase = MS.MapParams->ShadowBase;
952 IRB.CreateAdd(ShadowLong,
953 ConstantInt::get(MS.IntptrTy, ShadowBase));
954 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
957 /// \brief Compute the origin address that corresponds to a given application
960 /// OriginAddr = (OriginBase + Offset) & ~3ULL
961 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
962 Value *OriginLong = getShadowPtrOffset(Addr, IRB);
963 uint64_t OriginBase = MS.MapParams->OriginBase;
966 IRB.CreateAdd(OriginLong,
967 ConstantInt::get(MS.IntptrTy, OriginBase));
968 if (Alignment < kMinOriginAlignment) {
969 uint64_t Mask = kMinOriginAlignment - 1;
970 OriginLong = IRB.CreateAnd(OriginLong,
971 ConstantInt::get(MS.IntptrTy, ~Mask));
973 return IRB.CreateIntToPtr(OriginLong,
974 PointerType::get(IRB.getInt32Ty(), 0));
977 /// \brief Compute the shadow address for a given function argument.
979 /// Shadow = ParamTLS+ArgOffset.
980 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
982 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
983 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
984 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
988 /// \brief Compute the origin address for a given function argument.
989 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
991 if (!MS.TrackOrigins) return nullptr;
992 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
993 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
994 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
998 /// \brief Compute the shadow address for a retval.
999 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
1000 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
1001 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
1005 /// \brief Compute the origin address for a retval.
1006 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
1007 // We keep a single origin for the entire retval. Might be too optimistic.
1008 return MS.RetvalOriginTLS;
1011 /// \brief Set SV to be the shadow value for V.
1012 void setShadow(Value *V, Value *SV) {
1013 assert(!ShadowMap.count(V) && "Values may only have one shadow");
1014 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
1017 /// \brief Set Origin to be the origin value for V.
1018 void setOrigin(Value *V, Value *Origin) {
1019 if (!MS.TrackOrigins) return;
1020 assert(!OriginMap.count(V) && "Values may only have one origin");
1021 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
1022 OriginMap[V] = Origin;
1025 /// \brief Create a clean shadow value for a given value.
1027 /// Clean shadow (all zeroes) means all bits of the value are defined
1029 Constant *getCleanShadow(Value *V) {
1030 Type *ShadowTy = getShadowTy(V);
1033 return Constant::getNullValue(ShadowTy);
1036 /// \brief Create a dirty shadow of a given shadow type.
1037 Constant *getPoisonedShadow(Type *ShadowTy) {
1039 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
1040 return Constant::getAllOnesValue(ShadowTy);
1041 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
1042 SmallVector<Constant *, 4> Vals(AT->getNumElements(),
1043 getPoisonedShadow(AT->getElementType()));
1044 return ConstantArray::get(AT, Vals);
1046 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
1047 SmallVector<Constant *, 4> Vals;
1048 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1049 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1050 return ConstantStruct::get(ST, Vals);
1052 llvm_unreachable("Unexpected shadow type");
1055 /// \brief Create a dirty shadow for a given value.
1056 Constant *getPoisonedShadow(Value *V) {
1057 Type *ShadowTy = getShadowTy(V);
1060 return getPoisonedShadow(ShadowTy);
1063 /// \brief Create a clean (zero) origin.
1064 Value *getCleanOrigin() {
1065 return Constant::getNullValue(MS.OriginTy);
1068 /// \brief Get the shadow value for a given Value.
1070 /// This function either returns the value set earlier with setShadow,
1071 /// or extracts if from ParamTLS (for function arguments).
1072 Value *getShadow(Value *V) {
1073 if (!PropagateShadow) return getCleanShadow(V);
1074 if (Instruction *I = dyn_cast<Instruction>(V)) {
1075 // For instructions the shadow is already stored in the map.
1076 Value *Shadow = ShadowMap[V];
1078 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
1080 assert(Shadow && "No shadow for a value");
1084 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
1085 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
1086 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
1090 if (Argument *A = dyn_cast<Argument>(V)) {
1091 // For arguments we compute the shadow on demand and store it in the map.
1092 Value **ShadowPtr = &ShadowMap[V];
1095 Function *F = A->getParent();
1096 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
1097 unsigned ArgOffset = 0;
1098 const DataLayout &DL = F->getParent()->getDataLayout();
1099 for (auto &FArg : F->args()) {
1100 if (!FArg.getType()->isSized()) {
1101 DEBUG(dbgs() << "Arg is not sized\n");
1106 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
1107 : DL.getTypeAllocSize(FArg.getType());
1109 bool Overflow = ArgOffset + Size > kParamTLSSize;
1110 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1111 if (FArg.hasByValAttr()) {
1112 // ByVal pointer itself has clean shadow. We copy the actual
1113 // argument shadow to the underlying memory.
1114 // Figure out maximal valid memcpy alignment.
1115 unsigned ArgAlign = FArg.getParamAlignment();
1116 if (ArgAlign == 0) {
1117 Type *EltType = A->getType()->getPointerElementType();
1118 ArgAlign = DL.getABITypeAlignment(EltType);
1121 // ParamTLS overflow.
1122 EntryIRB.CreateMemSet(
1123 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
1124 Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
1126 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1127 Value *Cpy = EntryIRB.CreateMemCpy(
1128 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
1130 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
1133 *ShadowPtr = getCleanShadow(V);
1136 // ParamTLS overflow.
1137 *ShadowPtr = getCleanShadow(V);
1140 EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1143 DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
1144 **ShadowPtr << "\n");
1145 if (MS.TrackOrigins && !Overflow) {
1147 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
1148 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
1150 setOrigin(A, getCleanOrigin());
1153 ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
1155 assert(*ShadowPtr && "Could not find shadow for an argument");
1158 // For everything else the shadow is zero.
1159 return getCleanShadow(V);
1162 /// \brief Get the shadow for i-th argument of the instruction I.
1163 Value *getShadow(Instruction *I, int i) {
1164 return getShadow(I->getOperand(i));
1167 /// \brief Get the origin for a value.
1168 Value *getOrigin(Value *V) {
1169 if (!MS.TrackOrigins) return nullptr;
1170 if (!PropagateShadow) return getCleanOrigin();
1171 if (isa<Constant>(V)) return getCleanOrigin();
1172 assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1173 "Unexpected value type in getOrigin()");
1174 Value *Origin = OriginMap[V];
1175 assert(Origin && "Missing origin");
1179 /// \brief Get the origin for i-th argument of the instruction I.
1180 Value *getOrigin(Instruction *I, int i) {
1181 return getOrigin(I->getOperand(i));
1184 /// \brief Remember the place where a shadow check should be inserted.
1186 /// This location will be later instrumented with a check that will print a
1187 /// UMR warning in runtime if the shadow value is not 0.
1188 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1190 if (!InsertChecks) return;
1192 Type *ShadowTy = Shadow->getType();
1193 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1194 "Can only insert checks for integer and vector shadow types");
1196 InstrumentationList.push_back(
1197 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1200 /// \brief Remember the place where a shadow check should be inserted.
1202 /// This location will be later instrumented with a check that will print a
1203 /// UMR warning in runtime if the value is not fully defined.
1204 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1206 Value *Shadow, *Origin;
1207 if (ClCheckConstantShadow) {
1208 Shadow = getShadow(Val);
1209 if (!Shadow) return;
1210 Origin = getOrigin(Val);
1212 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1213 if (!Shadow) return;
1214 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1216 insertShadowCheck(Shadow, Origin, OrigIns);
1219 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1228 case AcquireRelease:
1229 return AcquireRelease;
1230 case SequentiallyConsistent:
1231 return SequentiallyConsistent;
1233 llvm_unreachable("Unknown ordering");
1236 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1245 case AcquireRelease:
1246 return AcquireRelease;
1247 case SequentiallyConsistent:
1248 return SequentiallyConsistent;
1250 llvm_unreachable("Unknown ordering");
1253 // ------------------- Visitors.
1255 /// \brief Instrument LoadInst
1257 /// Loads the corresponding shadow and (optionally) origin.
1258 /// Optionally, checks that the load address is fully defined.
1259 void visitLoadInst(LoadInst &I) {
1260 assert(I.getType()->isSized() && "Load type must have size");
1261 IRBuilder<> IRB(I.getNextNode());
1262 Type *ShadowTy = getShadowTy(&I);
1263 Value *Addr = I.getPointerOperand();
1264 if (PropagateShadow && !I.getMetadata("nosanitize")) {
1265 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1267 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1269 setShadow(&I, getCleanShadow(&I));
1272 if (ClCheckAccessAddress)
1273 insertShadowCheck(I.getPointerOperand(), &I);
1276 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1278 if (MS.TrackOrigins) {
1279 if (PropagateShadow) {
1280 unsigned Alignment = I.getAlignment();
1281 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1282 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
1285 setOrigin(&I, getCleanOrigin());
1290 /// \brief Instrument StoreInst
1292 /// Stores the corresponding shadow and (optionally) origin.
1293 /// Optionally, checks that the store address is fully defined.
1294 void visitStoreInst(StoreInst &I) {
1295 StoreList.push_back(&I);
1298 void handleCASOrRMW(Instruction &I) {
1299 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1301 IRBuilder<> IRB(&I);
1302 Value *Addr = I.getOperand(0);
1303 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1305 if (ClCheckAccessAddress)
1306 insertShadowCheck(Addr, &I);
1308 // Only test the conditional argument of cmpxchg instruction.
1309 // The other argument can potentially be uninitialized, but we can not
1310 // detect this situation reliably without possible false positives.
1311 if (isa<AtomicCmpXchgInst>(I))
1312 insertShadowCheck(I.getOperand(1), &I);
1314 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1316 setShadow(&I, getCleanShadow(&I));
1317 setOrigin(&I, getCleanOrigin());
1320 void visitAtomicRMWInst(AtomicRMWInst &I) {
1322 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1325 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1327 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1330 // Vector manipulation.
1331 void visitExtractElementInst(ExtractElementInst &I) {
1332 insertShadowCheck(I.getOperand(1), &I);
1333 IRBuilder<> IRB(&I);
1334 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1336 setOrigin(&I, getOrigin(&I, 0));
1339 void visitInsertElementInst(InsertElementInst &I) {
1340 insertShadowCheck(I.getOperand(2), &I);
1341 IRBuilder<> IRB(&I);
1342 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1343 I.getOperand(2), "_msprop"));
1344 setOriginForNaryOp(I);
1347 void visitShuffleVectorInst(ShuffleVectorInst &I) {
1348 insertShadowCheck(I.getOperand(2), &I);
1349 IRBuilder<> IRB(&I);
1350 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1351 I.getOperand(2), "_msprop"));
1352 setOriginForNaryOp(I);
1356 void visitSExtInst(SExtInst &I) {
1357 IRBuilder<> IRB(&I);
1358 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1359 setOrigin(&I, getOrigin(&I, 0));
1362 void visitZExtInst(ZExtInst &I) {
1363 IRBuilder<> IRB(&I);
1364 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1365 setOrigin(&I, getOrigin(&I, 0));
1368 void visitTruncInst(TruncInst &I) {
1369 IRBuilder<> IRB(&I);
1370 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1371 setOrigin(&I, getOrigin(&I, 0));
1374 void visitBitCastInst(BitCastInst &I) {
1375 // Special case: if this is the bitcast (there is exactly 1 allowed) between
1376 // a musttail call and a ret, don't instrument. New instructions are not
1377 // allowed after a musttail call.
1378 if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
1379 if (CI->isMustTailCall())
1381 IRBuilder<> IRB(&I);
1382 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1383 setOrigin(&I, getOrigin(&I, 0));
1386 void visitPtrToIntInst(PtrToIntInst &I) {
1387 IRBuilder<> IRB(&I);
1388 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1389 "_msprop_ptrtoint"));
1390 setOrigin(&I, getOrigin(&I, 0));
1393 void visitIntToPtrInst(IntToPtrInst &I) {
1394 IRBuilder<> IRB(&I);
1395 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1396 "_msprop_inttoptr"));
1397 setOrigin(&I, getOrigin(&I, 0));
1400 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1401 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1402 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1403 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1404 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1405 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1407 /// \brief Propagate shadow for bitwise AND.
1409 /// This code is exact, i.e. if, for example, a bit in the left argument
1410 /// is defined and 0, then neither the value not definedness of the
1411 /// corresponding bit in B don't affect the resulting shadow.
1412 void visitAnd(BinaryOperator &I) {
1413 IRBuilder<> IRB(&I);
1414 // "And" of 0 and a poisoned value results in unpoisoned value.
1415 // 1&1 => 1; 0&1 => 0; p&1 => p;
1416 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1417 // 1&p => p; 0&p => 0; p&p => p;
1418 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1419 Value *S1 = getShadow(&I, 0);
1420 Value *S2 = getShadow(&I, 1);
1421 Value *V1 = I.getOperand(0);
1422 Value *V2 = I.getOperand(1);
1423 if (V1->getType() != S1->getType()) {
1424 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1425 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1427 Value *S1S2 = IRB.CreateAnd(S1, S2);
1428 Value *V1S2 = IRB.CreateAnd(V1, S2);
1429 Value *S1V2 = IRB.CreateAnd(S1, V2);
1430 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1431 setOriginForNaryOp(I);
1434 void visitOr(BinaryOperator &I) {
1435 IRBuilder<> IRB(&I);
1436 // "Or" of 1 and a poisoned value results in unpoisoned value.
1437 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1438 // 1|0 => 1; 0|0 => 0; p|0 => p;
1439 // 1|p => 1; 0|p => p; p|p => p;
1440 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1441 Value *S1 = getShadow(&I, 0);
1442 Value *S2 = getShadow(&I, 1);
1443 Value *V1 = IRB.CreateNot(I.getOperand(0));
1444 Value *V2 = IRB.CreateNot(I.getOperand(1));
1445 if (V1->getType() != S1->getType()) {
1446 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1447 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1449 Value *S1S2 = IRB.CreateAnd(S1, S2);
1450 Value *V1S2 = IRB.CreateAnd(V1, S2);
1451 Value *S1V2 = IRB.CreateAnd(S1, V2);
1452 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1453 setOriginForNaryOp(I);
1456 /// \brief Default propagation of shadow and/or origin.
1458 /// This class implements the general case of shadow propagation, used in all
1459 /// cases where we don't know and/or don't care about what the operation
1460 /// actually does. It converts all input shadow values to a common type
1461 /// (extending or truncating as necessary), and bitwise OR's them.
1463 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1464 /// fully initialized), and less prone to false positives.
1466 /// This class also implements the general case of origin propagation. For a
1467 /// Nary operation, result origin is set to the origin of an argument that is
1468 /// not entirely initialized. If there is more than one such arguments, the
1469 /// rightmost of them is picked. It does not matter which one is picked if all
1470 /// arguments are initialized.
1471 template <bool CombineShadow>
1476 MemorySanitizerVisitor *MSV;
1479 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1480 Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
1482 /// \brief Add a pair of shadow and origin values to the mix.
1483 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1484 if (CombineShadow) {
1489 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1490 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1494 if (MSV->MS.TrackOrigins) {
1499 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1500 // No point in adding something that might result in 0 origin value.
1501 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1502 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1504 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1505 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1512 /// \brief Add an application value to the mix.
1513 Combiner &Add(Value *V) {
1514 Value *OpShadow = MSV->getShadow(V);
1515 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
1516 return Add(OpShadow, OpOrigin);
1519 /// \brief Set the current combined values as the given instruction's shadow
1521 void Done(Instruction *I) {
1522 if (CombineShadow) {
1524 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1525 MSV->setShadow(I, Shadow);
1527 if (MSV->MS.TrackOrigins) {
1529 MSV->setOrigin(I, Origin);
1534 typedef Combiner<true> ShadowAndOriginCombiner;
1535 typedef Combiner<false> OriginCombiner;
1537 /// \brief Propagate origin for arbitrary operation.
1538 void setOriginForNaryOp(Instruction &I) {
1539 if (!MS.TrackOrigins) return;
1540 IRBuilder<> IRB(&I);
1541 OriginCombiner OC(this, IRB);
1542 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1547 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1548 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1549 "Vector of pointers is not a valid shadow type");
1550 return Ty->isVectorTy() ?
1551 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1552 Ty->getPrimitiveSizeInBits();
1555 /// \brief Cast between two shadow types, extending or truncating as
1557 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1558 bool Signed = false) {
1559 Type *srcTy = V->getType();
1560 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1561 return IRB.CreateIntCast(V, dstTy, Signed);
1562 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1563 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1564 return IRB.CreateIntCast(V, dstTy, Signed);
1565 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1566 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1567 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1569 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1570 return IRB.CreateBitCast(V2, dstTy);
1571 // TODO: handle struct types.
1574 /// \brief Cast an application value to the type of its own shadow.
1575 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1576 Type *ShadowTy = getShadowTy(V);
1577 if (V->getType() == ShadowTy)
1579 if (V->getType()->isPtrOrPtrVectorTy())
1580 return IRB.CreatePtrToInt(V, ShadowTy);
1582 return IRB.CreateBitCast(V, ShadowTy);
1585 /// \brief Propagate shadow for arbitrary operation.
1586 void handleShadowOr(Instruction &I) {
1587 IRBuilder<> IRB(&I);
1588 ShadowAndOriginCombiner SC(this, IRB);
1589 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1594 // \brief Handle multiplication by constant.
1596 // Handle a special case of multiplication by constant that may have one or
1597 // more zeros in the lower bits. This makes corresponding number of lower bits
1598 // of the result zero as well. We model it by shifting the other operand
1599 // shadow left by the required number of bits. Effectively, we transform
1600 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1601 // We use multiplication by 2**N instead of shift to cover the case of
1602 // multiplication by 0, which may occur in some elements of a vector operand.
1603 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1605 Constant *ShadowMul;
1606 Type *Ty = ConstArg->getType();
1607 if (Ty->isVectorTy()) {
1608 unsigned NumElements = Ty->getVectorNumElements();
1609 Type *EltTy = Ty->getSequentialElementType();
1610 SmallVector<Constant *, 16> Elements;
1611 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1613 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1614 APInt V = Elt->getValue();
1615 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1616 Elements.push_back(ConstantInt::get(EltTy, V2));
1618 ShadowMul = ConstantVector::get(Elements);
1620 ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1621 APInt V = Elt->getValue();
1622 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1623 ShadowMul = ConstantInt::get(Elt->getType(), V2);
1626 IRBuilder<> IRB(&I);
1628 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1629 setOrigin(&I, getOrigin(OtherArg));
1632 void visitMul(BinaryOperator &I) {
1633 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1634 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1635 if (constOp0 && !constOp1)
1636 handleMulByConstant(I, constOp0, I.getOperand(1));
1637 else if (constOp1 && !constOp0)
1638 handleMulByConstant(I, constOp1, I.getOperand(0));
1643 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1644 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1645 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1646 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1647 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1648 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1650 void handleDiv(Instruction &I) {
1651 IRBuilder<> IRB(&I);
1652 // Strict on the second argument.
1653 insertShadowCheck(I.getOperand(1), &I);
1654 setShadow(&I, getShadow(&I, 0));
1655 setOrigin(&I, getOrigin(&I, 0));
1658 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1659 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1660 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1661 void visitURem(BinaryOperator &I) { handleDiv(I); }
1662 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1663 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1665 /// \brief Instrument == and != comparisons.
1667 /// Sometimes the comparison result is known even if some of the bits of the
1668 /// arguments are not.
1669 void handleEqualityComparison(ICmpInst &I) {
1670 IRBuilder<> IRB(&I);
1671 Value *A = I.getOperand(0);
1672 Value *B = I.getOperand(1);
1673 Value *Sa = getShadow(A);
1674 Value *Sb = getShadow(B);
1676 // Get rid of pointers and vectors of pointers.
1677 // For ints (and vectors of ints), types of A and Sa match,
1678 // and this is a no-op.
1679 A = IRB.CreatePointerCast(A, Sa->getType());
1680 B = IRB.CreatePointerCast(B, Sb->getType());
1682 // A == B <==> (C = A^B) == 0
1683 // A != B <==> (C = A^B) != 0
1685 Value *C = IRB.CreateXor(A, B);
1686 Value *Sc = IRB.CreateOr(Sa, Sb);
1687 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1688 // Result is defined if one of the following is true
1689 // * there is a defined 1 bit in C
1690 // * C is fully defined
1691 // Si = !(C & ~Sc) && Sc
1692 Value *Zero = Constant::getNullValue(Sc->getType());
1693 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1695 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1697 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1698 Si->setName("_msprop_icmp");
1700 setOriginForNaryOp(I);
1703 /// \brief Build the lowest possible value of V, taking into account V's
1704 /// uninitialized bits.
1705 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1708 // Split shadow into sign bit and other bits.
1709 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1710 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1711 // Maximise the undefined shadow bit, minimize other undefined bits.
1713 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1715 // Minimize undefined bits.
1716 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1720 /// \brief Build the highest possible value of V, taking into account V's
1721 /// uninitialized bits.
1722 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1725 // Split shadow into sign bit and other bits.
1726 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1727 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1728 // Minimise the undefined shadow bit, maximise other undefined bits.
1730 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1732 // Maximize undefined bits.
1733 return IRB.CreateOr(A, Sa);
1737 /// \brief Instrument relational comparisons.
1739 /// This function does exact shadow propagation for all relational
1740 /// comparisons of integers, pointers and vectors of those.
1741 /// FIXME: output seems suboptimal when one of the operands is a constant
1742 void handleRelationalComparisonExact(ICmpInst &I) {
1743 IRBuilder<> IRB(&I);
1744 Value *A = I.getOperand(0);
1745 Value *B = I.getOperand(1);
1746 Value *Sa = getShadow(A);
1747 Value *Sb = getShadow(B);
1749 // Get rid of pointers and vectors of pointers.
1750 // For ints (and vectors of ints), types of A and Sa match,
1751 // and this is a no-op.
1752 A = IRB.CreatePointerCast(A, Sa->getType());
1753 B = IRB.CreatePointerCast(B, Sb->getType());
1755 // Let [a0, a1] be the interval of possible values of A, taking into account
1756 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1757 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1758 bool IsSigned = I.isSigned();
1759 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1760 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1761 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1762 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1763 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1764 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1765 Value *Si = IRB.CreateXor(S1, S2);
1767 setOriginForNaryOp(I);
1770 /// \brief Instrument signed relational comparisons.
1772 /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest
1773 /// bit of the shadow. Everything else is delegated to handleShadowOr().
1774 void handleSignedRelationalComparison(ICmpInst &I) {
1776 Value *op = nullptr;
1777 CmpInst::Predicate pre;
1778 if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) {
1779 op = I.getOperand(0);
1780 pre = I.getPredicate();
1781 } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) {
1782 op = I.getOperand(1);
1783 pre = I.getSwappedPredicate();
1789 if ((constOp->isNullValue() &&
1790 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) ||
1791 (constOp->isAllOnesValue() &&
1792 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) {
1793 IRBuilder<> IRB(&I);
1794 Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op),
1796 setShadow(&I, Shadow);
1797 setOrigin(&I, getOrigin(op));
1803 void visitICmpInst(ICmpInst &I) {
1804 if (!ClHandleICmp) {
1808 if (I.isEquality()) {
1809 handleEqualityComparison(I);
1813 assert(I.isRelational());
1814 if (ClHandleICmpExact) {
1815 handleRelationalComparisonExact(I);
1819 handleSignedRelationalComparison(I);
1823 assert(I.isUnsigned());
1824 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1825 handleRelationalComparisonExact(I);
1832 void visitFCmpInst(FCmpInst &I) {
1836 void handleShift(BinaryOperator &I) {
1837 IRBuilder<> IRB(&I);
1838 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1839 // Otherwise perform the same shift on S1.
1840 Value *S1 = getShadow(&I, 0);
1841 Value *S2 = getShadow(&I, 1);
1842 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1844 Value *V2 = I.getOperand(1);
1845 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1846 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1847 setOriginForNaryOp(I);
1850 void visitShl(BinaryOperator &I) { handleShift(I); }
1851 void visitAShr(BinaryOperator &I) { handleShift(I); }
1852 void visitLShr(BinaryOperator &I) { handleShift(I); }
1854 /// \brief Instrument llvm.memmove
1856 /// At this point we don't know if llvm.memmove will be inlined or not.
1857 /// If we don't instrument it and it gets inlined,
1858 /// our interceptor will not kick in and we will lose the memmove.
1859 /// If we instrument the call here, but it does not get inlined,
1860 /// we will memove the shadow twice: which is bad in case
1861 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1863 /// Similar situation exists for memcpy and memset.
1864 void visitMemMoveInst(MemMoveInst &I) {
1865 IRBuilder<> IRB(&I);
1868 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1869 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1870 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1871 I.eraseFromParent();
1874 // Similar to memmove: avoid copying shadow twice.
1875 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1876 // FIXME: consider doing manual inline for small constant sizes and proper
1878 void visitMemCpyInst(MemCpyInst &I) {
1879 IRBuilder<> IRB(&I);
1882 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1883 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1884 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1885 I.eraseFromParent();
1889 void visitMemSetInst(MemSetInst &I) {
1890 IRBuilder<> IRB(&I);
1893 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1894 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1895 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1896 I.eraseFromParent();
1899 void visitVAStartInst(VAStartInst &I) {
1900 VAHelper->visitVAStartInst(I);
1903 void visitVACopyInst(VACopyInst &I) {
1904 VAHelper->visitVACopyInst(I);
1907 enum IntrinsicKind {
1908 IK_DoesNotAccessMemory,
1913 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1914 const int FMRB_DoesNotAccessMemory = IK_DoesNotAccessMemory;
1915 const int FMRB_OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1916 const int FMRB_OnlyReadsMemory = IK_OnlyReadsMemory;
1917 const int FMRB_OnlyAccessesArgumentPointees = IK_WritesMemory;
1918 const int FMRB_UnknownModRefBehavior = IK_WritesMemory;
1919 #define GET_INTRINSIC_MODREF_BEHAVIOR
1920 #define FunctionModRefBehavior IntrinsicKind
1921 #include "llvm/IR/Intrinsics.gen"
1922 #undef FunctionModRefBehavior
1923 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1926 /// \brief Handle vector store-like intrinsics.
1928 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1929 /// has 1 pointer argument and 1 vector argument, returns void.
1930 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1931 IRBuilder<> IRB(&I);
1932 Value* Addr = I.getArgOperand(0);
1933 Value *Shadow = getShadow(&I, 1);
1934 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1936 // We don't know the pointer alignment (could be unaligned SSE store!).
1937 // Have to assume to worst case.
1938 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1940 if (ClCheckAccessAddress)
1941 insertShadowCheck(Addr, &I);
1943 // FIXME: use ClStoreCleanOrigin
1944 // FIXME: factor out common code from materializeStores
1945 if (MS.TrackOrigins)
1946 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
1950 /// \brief Handle vector load-like intrinsics.
1952 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1953 /// has 1 pointer argument, returns a vector.
1954 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1955 IRBuilder<> IRB(&I);
1956 Value *Addr = I.getArgOperand(0);
1958 Type *ShadowTy = getShadowTy(&I);
1959 if (PropagateShadow) {
1960 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1961 // We don't know the pointer alignment (could be unaligned SSE load!).
1962 // Have to assume to worst case.
1963 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1965 setShadow(&I, getCleanShadow(&I));
1968 if (ClCheckAccessAddress)
1969 insertShadowCheck(Addr, &I);
1971 if (MS.TrackOrigins) {
1972 if (PropagateShadow)
1973 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
1975 setOrigin(&I, getCleanOrigin());
1980 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1982 /// Instrument intrinsics with any number of arguments of the same type,
1983 /// equal to the return type. The type should be simple (no aggregates or
1984 /// pointers; vectors are fine).
1985 /// Caller guarantees that this intrinsic does not access memory.
1986 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1987 Type *RetTy = I.getType();
1988 if (!(RetTy->isIntOrIntVectorTy() ||
1989 RetTy->isFPOrFPVectorTy() ||
1990 RetTy->isX86_MMXTy()))
1993 unsigned NumArgOperands = I.getNumArgOperands();
1995 for (unsigned i = 0; i < NumArgOperands; ++i) {
1996 Type *Ty = I.getArgOperand(i)->getType();
2001 IRBuilder<> IRB(&I);
2002 ShadowAndOriginCombiner SC(this, IRB);
2003 for (unsigned i = 0; i < NumArgOperands; ++i)
2004 SC.Add(I.getArgOperand(i));
2010 /// \brief Heuristically instrument unknown intrinsics.
2012 /// The main purpose of this code is to do something reasonable with all
2013 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
2014 /// We recognize several classes of intrinsics by their argument types and
2015 /// ModRefBehaviour and apply special intrumentation when we are reasonably
2016 /// sure that we know what the intrinsic does.
2018 /// We special-case intrinsics where this approach fails. See llvm.bswap
2019 /// handling as an example of that.
2020 bool handleUnknownIntrinsic(IntrinsicInst &I) {
2021 unsigned NumArgOperands = I.getNumArgOperands();
2022 if (NumArgOperands == 0)
2025 Intrinsic::ID iid = I.getIntrinsicID();
2026 IntrinsicKind IK = getIntrinsicKind(iid);
2027 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
2028 bool WritesMemory = IK == IK_WritesMemory;
2029 assert(!(OnlyReadsMemory && WritesMemory));
2031 if (NumArgOperands == 2 &&
2032 I.getArgOperand(0)->getType()->isPointerTy() &&
2033 I.getArgOperand(1)->getType()->isVectorTy() &&
2034 I.getType()->isVoidTy() &&
2036 // This looks like a vector store.
2037 return handleVectorStoreIntrinsic(I);
2040 if (NumArgOperands == 1 &&
2041 I.getArgOperand(0)->getType()->isPointerTy() &&
2042 I.getType()->isVectorTy() &&
2044 // This looks like a vector load.
2045 return handleVectorLoadIntrinsic(I);
2048 if (!OnlyReadsMemory && !WritesMemory)
2049 if (maybeHandleSimpleNomemIntrinsic(I))
2052 // FIXME: detect and handle SSE maskstore/maskload
2056 void handleBswap(IntrinsicInst &I) {
2057 IRBuilder<> IRB(&I);
2058 Value *Op = I.getArgOperand(0);
2059 Type *OpType = Op->getType();
2060 Function *BswapFunc = Intrinsic::getDeclaration(
2061 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
2062 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2063 setOrigin(&I, getOrigin(Op));
2066 // \brief Instrument vector convert instrinsic.
2068 // This function instruments intrinsics like cvtsi2ss:
2069 // %Out = int_xxx_cvtyyy(%ConvertOp)
2071 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2072 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2073 // number \p Out elements, and (if has 2 arguments) copies the rest of the
2074 // elements from \p CopyOp.
2075 // In most cases conversion involves floating-point value which may trigger a
2076 // hardware exception when not fully initialized. For this reason we require
2077 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2078 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2079 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2080 // return a fully initialized value.
2081 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2082 IRBuilder<> IRB(&I);
2083 Value *CopyOp, *ConvertOp;
2085 switch (I.getNumArgOperands()) {
2087 assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
2089 CopyOp = I.getArgOperand(0);
2090 ConvertOp = I.getArgOperand(1);
2093 ConvertOp = I.getArgOperand(0);
2097 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2100 // The first *NumUsedElements* elements of ConvertOp are converted to the
2101 // same number of output elements. The rest of the output is copied from
2102 // CopyOp, or (if not available) filled with zeroes.
2103 // Combine shadow for elements of ConvertOp that are used in this operation,
2104 // and insert a check.
2105 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2106 // int->any conversion.
2107 Value *ConvertShadow = getShadow(ConvertOp);
2108 Value *AggShadow = nullptr;
2109 if (ConvertOp->getType()->isVectorTy()) {
2110 AggShadow = IRB.CreateExtractElement(
2111 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2112 for (int i = 1; i < NumUsedElements; ++i) {
2113 Value *MoreShadow = IRB.CreateExtractElement(
2114 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2115 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2118 AggShadow = ConvertShadow;
2120 assert(AggShadow->getType()->isIntegerTy());
2121 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2123 // Build result shadow by zero-filling parts of CopyOp shadow that come from
2126 assert(CopyOp->getType() == I.getType());
2127 assert(CopyOp->getType()->isVectorTy());
2128 Value *ResultShadow = getShadow(CopyOp);
2129 Type *EltTy = ResultShadow->getType()->getVectorElementType();
2130 for (int i = 0; i < NumUsedElements; ++i) {
2131 ResultShadow = IRB.CreateInsertElement(
2132 ResultShadow, ConstantInt::getNullValue(EltTy),
2133 ConstantInt::get(IRB.getInt32Ty(), i));
2135 setShadow(&I, ResultShadow);
2136 setOrigin(&I, getOrigin(CopyOp));
2138 setShadow(&I, getCleanShadow(&I));
2139 setOrigin(&I, getCleanOrigin());
2143 // Given a scalar or vector, extract lower 64 bits (or less), and return all
2144 // zeroes if it is zero, and all ones otherwise.
2145 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2146 if (S->getType()->isVectorTy())
2147 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2148 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2149 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2150 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2153 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2154 Type *T = S->getType();
2155 assert(T->isVectorTy());
2156 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2157 return IRB.CreateSExt(S2, T);
2160 // \brief Instrument vector shift instrinsic.
2162 // This function instruments intrinsics like int_x86_avx2_psll_w.
2163 // Intrinsic shifts %In by %ShiftSize bits.
2164 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2165 // size, and the rest is ignored. Behavior is defined even if shift size is
2166 // greater than register (or field) width.
2167 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2168 assert(I.getNumArgOperands() == 2);
2169 IRBuilder<> IRB(&I);
2170 // If any of the S2 bits are poisoned, the whole thing is poisoned.
2171 // Otherwise perform the same shift on S1.
2172 Value *S1 = getShadow(&I, 0);
2173 Value *S2 = getShadow(&I, 1);
2174 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2175 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2176 Value *V1 = I.getOperand(0);
2177 Value *V2 = I.getOperand(1);
2178 Value *Shift = IRB.CreateCall(I.getCalledValue(),
2179 {IRB.CreateBitCast(S1, V1->getType()), V2});
2180 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2181 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2182 setOriginForNaryOp(I);
2185 // \brief Get an X86_MMX-sized vector type.
2186 Type *getMMXVectorTy(unsigned EltSizeInBits) {
2187 const unsigned X86_MMXSizeInBits = 64;
2188 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2189 X86_MMXSizeInBits / EltSizeInBits);
2192 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2194 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2196 case llvm::Intrinsic::x86_sse2_packsswb_128:
2197 case llvm::Intrinsic::x86_sse2_packuswb_128:
2198 return llvm::Intrinsic::x86_sse2_packsswb_128;
2200 case llvm::Intrinsic::x86_sse2_packssdw_128:
2201 case llvm::Intrinsic::x86_sse41_packusdw:
2202 return llvm::Intrinsic::x86_sse2_packssdw_128;
2204 case llvm::Intrinsic::x86_avx2_packsswb:
2205 case llvm::Intrinsic::x86_avx2_packuswb:
2206 return llvm::Intrinsic::x86_avx2_packsswb;
2208 case llvm::Intrinsic::x86_avx2_packssdw:
2209 case llvm::Intrinsic::x86_avx2_packusdw:
2210 return llvm::Intrinsic::x86_avx2_packssdw;
2212 case llvm::Intrinsic::x86_mmx_packsswb:
2213 case llvm::Intrinsic::x86_mmx_packuswb:
2214 return llvm::Intrinsic::x86_mmx_packsswb;
2216 case llvm::Intrinsic::x86_mmx_packssdw:
2217 return llvm::Intrinsic::x86_mmx_packssdw;
2219 llvm_unreachable("unexpected intrinsic id");
2223 // \brief Instrument vector pack instrinsic.
2225 // This function instruments intrinsics like x86_mmx_packsswb, that
2226 // packs elements of 2 input vectors into half as many bits with saturation.
2227 // Shadow is propagated with the signed variant of the same intrinsic applied
2228 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2229 // EltSizeInBits is used only for x86mmx arguments.
2230 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
2231 assert(I.getNumArgOperands() == 2);
2232 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2233 IRBuilder<> IRB(&I);
2234 Value *S1 = getShadow(&I, 0);
2235 Value *S2 = getShadow(&I, 1);
2236 assert(isX86_MMX || S1->getType()->isVectorTy());
2238 // SExt and ICmpNE below must apply to individual elements of input vectors.
2239 // In case of x86mmx arguments, cast them to appropriate vector types and
2241 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2243 S1 = IRB.CreateBitCast(S1, T);
2244 S2 = IRB.CreateBitCast(S2, T);
2246 Value *S1_ext = IRB.CreateSExt(
2247 IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2248 Value *S2_ext = IRB.CreateSExt(
2249 IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
2251 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2252 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2253 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2256 Function *ShadowFn = Intrinsic::getDeclaration(
2257 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2260 IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
2261 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2263 setOriginForNaryOp(I);
2266 // \brief Instrument sum-of-absolute-differencies intrinsic.
2267 void handleVectorSadIntrinsic(IntrinsicInst &I) {
2268 const unsigned SignificantBitsPerResultElement = 16;
2269 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2270 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2271 unsigned ZeroBitsPerResultElement =
2272 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2274 IRBuilder<> IRB(&I);
2275 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2276 S = IRB.CreateBitCast(S, ResTy);
2277 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2279 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2280 S = IRB.CreateBitCast(S, getShadowTy(&I));
2282 setOriginForNaryOp(I);
2285 // \brief Instrument multiply-add intrinsic.
2286 void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2287 unsigned EltSizeInBits = 0) {
2288 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2289 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2290 IRBuilder<> IRB(&I);
2291 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2292 S = IRB.CreateBitCast(S, ResTy);
2293 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2295 S = IRB.CreateBitCast(S, getShadowTy(&I));
2297 setOriginForNaryOp(I);
2300 void visitIntrinsicInst(IntrinsicInst &I) {
2301 switch (I.getIntrinsicID()) {
2302 case llvm::Intrinsic::bswap:
2305 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2306 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2307 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2308 case llvm::Intrinsic::x86_avx512_cvtss2usi:
2309 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2310 case llvm::Intrinsic::x86_avx512_cvttss2usi:
2311 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2312 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2313 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2314 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2315 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2316 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2317 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2318 case llvm::Intrinsic::x86_sse2_cvtsd2si:
2319 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2320 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2321 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2322 case llvm::Intrinsic::x86_sse2_cvtss2sd:
2323 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2324 case llvm::Intrinsic::x86_sse2_cvttsd2si:
2325 case llvm::Intrinsic::x86_sse_cvtsi2ss:
2326 case llvm::Intrinsic::x86_sse_cvtsi642ss:
2327 case llvm::Intrinsic::x86_sse_cvtss2si64:
2328 case llvm::Intrinsic::x86_sse_cvtss2si:
2329 case llvm::Intrinsic::x86_sse_cvttss2si64:
2330 case llvm::Intrinsic::x86_sse_cvttss2si:
2331 handleVectorConvertIntrinsic(I, 1);
2333 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2334 case llvm::Intrinsic::x86_sse2_cvtps2pd:
2335 case llvm::Intrinsic::x86_sse_cvtps2pi:
2336 case llvm::Intrinsic::x86_sse_cvttps2pi:
2337 handleVectorConvertIntrinsic(I, 2);
2339 case llvm::Intrinsic::x86_avx2_psll_w:
2340 case llvm::Intrinsic::x86_avx2_psll_d:
2341 case llvm::Intrinsic::x86_avx2_psll_q:
2342 case llvm::Intrinsic::x86_avx2_pslli_w:
2343 case llvm::Intrinsic::x86_avx2_pslli_d:
2344 case llvm::Intrinsic::x86_avx2_pslli_q:
2345 case llvm::Intrinsic::x86_avx2_psrl_w:
2346 case llvm::Intrinsic::x86_avx2_psrl_d:
2347 case llvm::Intrinsic::x86_avx2_psrl_q:
2348 case llvm::Intrinsic::x86_avx2_psra_w:
2349 case llvm::Intrinsic::x86_avx2_psra_d:
2350 case llvm::Intrinsic::x86_avx2_psrli_w:
2351 case llvm::Intrinsic::x86_avx2_psrli_d:
2352 case llvm::Intrinsic::x86_avx2_psrli_q:
2353 case llvm::Intrinsic::x86_avx2_psrai_w:
2354 case llvm::Intrinsic::x86_avx2_psrai_d:
2355 case llvm::Intrinsic::x86_sse2_psll_w:
2356 case llvm::Intrinsic::x86_sse2_psll_d:
2357 case llvm::Intrinsic::x86_sse2_psll_q:
2358 case llvm::Intrinsic::x86_sse2_pslli_w:
2359 case llvm::Intrinsic::x86_sse2_pslli_d:
2360 case llvm::Intrinsic::x86_sse2_pslli_q:
2361 case llvm::Intrinsic::x86_sse2_psrl_w:
2362 case llvm::Intrinsic::x86_sse2_psrl_d:
2363 case llvm::Intrinsic::x86_sse2_psrl_q:
2364 case llvm::Intrinsic::x86_sse2_psra_w:
2365 case llvm::Intrinsic::x86_sse2_psra_d:
2366 case llvm::Intrinsic::x86_sse2_psrli_w:
2367 case llvm::Intrinsic::x86_sse2_psrli_d:
2368 case llvm::Intrinsic::x86_sse2_psrli_q:
2369 case llvm::Intrinsic::x86_sse2_psrai_w:
2370 case llvm::Intrinsic::x86_sse2_psrai_d:
2371 case llvm::Intrinsic::x86_mmx_psll_w:
2372 case llvm::Intrinsic::x86_mmx_psll_d:
2373 case llvm::Intrinsic::x86_mmx_psll_q:
2374 case llvm::Intrinsic::x86_mmx_pslli_w:
2375 case llvm::Intrinsic::x86_mmx_pslli_d:
2376 case llvm::Intrinsic::x86_mmx_pslli_q:
2377 case llvm::Intrinsic::x86_mmx_psrl_w:
2378 case llvm::Intrinsic::x86_mmx_psrl_d:
2379 case llvm::Intrinsic::x86_mmx_psrl_q:
2380 case llvm::Intrinsic::x86_mmx_psra_w:
2381 case llvm::Intrinsic::x86_mmx_psra_d:
2382 case llvm::Intrinsic::x86_mmx_psrli_w:
2383 case llvm::Intrinsic::x86_mmx_psrli_d:
2384 case llvm::Intrinsic::x86_mmx_psrli_q:
2385 case llvm::Intrinsic::x86_mmx_psrai_w:
2386 case llvm::Intrinsic::x86_mmx_psrai_d:
2387 handleVectorShiftIntrinsic(I, /* Variable */ false);
2389 case llvm::Intrinsic::x86_avx2_psllv_d:
2390 case llvm::Intrinsic::x86_avx2_psllv_d_256:
2391 case llvm::Intrinsic::x86_avx2_psllv_q:
2392 case llvm::Intrinsic::x86_avx2_psllv_q_256:
2393 case llvm::Intrinsic::x86_avx2_psrlv_d:
2394 case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2395 case llvm::Intrinsic::x86_avx2_psrlv_q:
2396 case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2397 case llvm::Intrinsic::x86_avx2_psrav_d:
2398 case llvm::Intrinsic::x86_avx2_psrav_d_256:
2399 handleVectorShiftIntrinsic(I, /* Variable */ true);
2402 case llvm::Intrinsic::x86_sse2_packsswb_128:
2403 case llvm::Intrinsic::x86_sse2_packssdw_128:
2404 case llvm::Intrinsic::x86_sse2_packuswb_128:
2405 case llvm::Intrinsic::x86_sse41_packusdw:
2406 case llvm::Intrinsic::x86_avx2_packsswb:
2407 case llvm::Intrinsic::x86_avx2_packssdw:
2408 case llvm::Intrinsic::x86_avx2_packuswb:
2409 case llvm::Intrinsic::x86_avx2_packusdw:
2410 handleVectorPackIntrinsic(I);
2413 case llvm::Intrinsic::x86_mmx_packsswb:
2414 case llvm::Intrinsic::x86_mmx_packuswb:
2415 handleVectorPackIntrinsic(I, 16);
2418 case llvm::Intrinsic::x86_mmx_packssdw:
2419 handleVectorPackIntrinsic(I, 32);
2422 case llvm::Intrinsic::x86_mmx_psad_bw:
2423 case llvm::Intrinsic::x86_sse2_psad_bw:
2424 case llvm::Intrinsic::x86_avx2_psad_bw:
2425 handleVectorSadIntrinsic(I);
2428 case llvm::Intrinsic::x86_sse2_pmadd_wd:
2429 case llvm::Intrinsic::x86_avx2_pmadd_wd:
2430 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2431 case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2432 handleVectorPmaddIntrinsic(I);
2435 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2436 handleVectorPmaddIntrinsic(I, 8);
2439 case llvm::Intrinsic::x86_mmx_pmadd_wd:
2440 handleVectorPmaddIntrinsic(I, 16);
2444 if (!handleUnknownIntrinsic(I))
2445 visitInstruction(I);
2450 void visitCallSite(CallSite CS) {
2451 Instruction &I = *CS.getInstruction();
2452 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2454 CallInst *Call = cast<CallInst>(&I);
2456 // For inline asm, do the usual thing: check argument shadow and mark all
2457 // outputs as clean. Note that any side effects of the inline asm that are
2458 // not immediately visible in its constraints are not handled.
2459 if (Call->isInlineAsm()) {
2460 visitInstruction(I);
2464 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
2466 // We are going to insert code that relies on the fact that the callee
2467 // will become a non-readonly function after it is instrumented by us. To
2468 // prevent this code from being optimized out, mark that function
2469 // non-readonly in advance.
2470 if (Function *Func = Call->getCalledFunction()) {
2471 // Clear out readonly/readnone attributes.
2473 B.addAttribute(Attribute::ReadOnly)
2474 .addAttribute(Attribute::ReadNone);
2475 Func->removeAttributes(AttributeSet::FunctionIndex,
2476 AttributeSet::get(Func->getContext(),
2477 AttributeSet::FunctionIndex,
2481 IRBuilder<> IRB(&I);
2483 unsigned ArgOffset = 0;
2484 DEBUG(dbgs() << " CallSite: " << I << "\n");
2485 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2486 ArgIt != End; ++ArgIt) {
2488 unsigned i = ArgIt - CS.arg_begin();
2489 if (!A->getType()->isSized()) {
2490 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2494 Value *Store = nullptr;
2495 // Compute the Shadow for arg even if it is ByVal, because
2496 // in that case getShadow() will copy the actual arg shadow to
2497 // __msan_param_tls.
2498 Value *ArgShadow = getShadow(A);
2499 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2500 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2501 " Shadow: " << *ArgShadow << "\n");
2502 bool ArgIsInitialized = false;
2503 const DataLayout &DL = F.getParent()->getDataLayout();
2504 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
2505 assert(A->getType()->isPointerTy() &&
2506 "ByVal argument is not a pointer!");
2507 Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
2508 if (ArgOffset + Size > kParamTLSSize) break;
2509 unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2510 unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
2511 Store = IRB.CreateMemCpy(ArgShadowBase,
2512 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2515 Size = DL.getTypeAllocSize(A->getType());
2516 if (ArgOffset + Size > kParamTLSSize) break;
2517 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2518 kShadowTLSAlignment);
2519 Constant *Cst = dyn_cast<Constant>(ArgShadow);
2520 if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
2522 if (MS.TrackOrigins && !ArgIsInitialized)
2523 IRB.CreateStore(getOrigin(A),
2524 getOriginPtrForArgument(A, IRB, ArgOffset));
2526 assert(Size != 0 && Store != nullptr);
2527 DEBUG(dbgs() << " Param:" << *Store << "\n");
2528 ArgOffset += RoundUpToAlignment(Size, 8);
2530 DEBUG(dbgs() << " done with call args\n");
2533 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
2534 if (FT->isVarArg()) {
2535 VAHelper->visitCallSite(CS, IRB);
2538 // Now, get the shadow for the RetVal.
2539 if (!I.getType()->isSized()) return;
2540 // Don't emit the epilogue for musttail call returns.
2541 if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
2542 IRBuilder<> IRBBefore(&I);
2543 // Until we have full dynamic coverage, make sure the retval shadow is 0.
2544 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
2545 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
2546 Instruction *NextInsn = nullptr;
2548 NextInsn = I.getNextNode();
2550 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2551 if (!NormalDest->getSinglePredecessor()) {
2552 // FIXME: this case is tricky, so we are just conservative here.
2553 // Perhaps we need to split the edge between this BB and NormalDest,
2554 // but a naive attempt to use SplitEdge leads to a crash.
2555 setShadow(&I, getCleanShadow(&I));
2556 setOrigin(&I, getCleanOrigin());
2559 NextInsn = NormalDest->getFirstInsertionPt();
2561 "Could not find insertion point for retval shadow load");
2563 IRBuilder<> IRBAfter(NextInsn);
2564 Value *RetvalShadow =
2565 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2566 kShadowTLSAlignment, "_msret");
2567 setShadow(&I, RetvalShadow);
2568 if (MS.TrackOrigins)
2569 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2572 bool isAMustTailRetVal(Value *RetVal) {
2573 if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
2574 RetVal = I->getOperand(0);
2576 if (auto *I = dyn_cast<CallInst>(RetVal)) {
2577 return I->isMustTailCall();
2582 void visitReturnInst(ReturnInst &I) {
2583 IRBuilder<> IRB(&I);
2584 Value *RetVal = I.getReturnValue();
2585 if (!RetVal) return;
2586 // Don't emit the epilogue for musttail call returns.
2587 if (isAMustTailRetVal(RetVal)) return;
2588 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2589 if (CheckReturnValue) {
2590 insertShadowCheck(RetVal, &I);
2591 Value *Shadow = getCleanShadow(RetVal);
2592 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2594 Value *Shadow = getShadow(RetVal);
2595 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2596 // FIXME: make it conditional if ClStoreCleanOrigin==0
2597 if (MS.TrackOrigins)
2598 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2602 void visitPHINode(PHINode &I) {
2603 IRBuilder<> IRB(&I);
2604 if (!PropagateShadow) {
2605 setShadow(&I, getCleanShadow(&I));
2606 setOrigin(&I, getCleanOrigin());
2610 ShadowPHINodes.push_back(&I);
2611 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2613 if (MS.TrackOrigins)
2614 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2618 void visitAllocaInst(AllocaInst &I) {
2619 setShadow(&I, getCleanShadow(&I));
2620 setOrigin(&I, getCleanOrigin());
2621 IRBuilder<> IRB(I.getNextNode());
2622 const DataLayout &DL = F.getParent()->getDataLayout();
2623 uint64_t Size = DL.getTypeAllocSize(I.getAllocatedType());
2624 if (PoisonStack && ClPoisonStackWithCall) {
2625 IRB.CreateCall(MS.MsanPoisonStackFn,
2626 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2627 ConstantInt::get(MS.IntptrTy, Size)});
2629 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2630 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2631 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2634 if (PoisonStack && MS.TrackOrigins) {
2635 SmallString<2048> StackDescriptionStorage;
2636 raw_svector_ostream StackDescription(StackDescriptionStorage);
2637 // We create a string with a description of the stack allocation and
2638 // pass it into __msan_set_alloca_origin.
2639 // It will be printed by the run-time if stack-originated UMR is found.
2640 // The first 4 bytes of the string are set to '----' and will be replaced
2641 // by __msan_va_arg_overflow_size_tls at the first call.
2642 StackDescription << "----" << I.getName() << "@" << F.getName();
2644 createPrivateNonConstGlobalForString(*F.getParent(),
2645 StackDescription.str());
2647 IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
2648 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2649 ConstantInt::get(MS.IntptrTy, Size),
2650 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2651 IRB.CreatePointerCast(&F, MS.IntptrTy)});
2655 void visitSelectInst(SelectInst& I) {
2656 IRBuilder<> IRB(&I);
2657 // a = select b, c, d
2658 Value *B = I.getCondition();
2659 Value *C = I.getTrueValue();
2660 Value *D = I.getFalseValue();
2661 Value *Sb = getShadow(B);
2662 Value *Sc = getShadow(C);
2663 Value *Sd = getShadow(D);
2665 // Result shadow if condition shadow is 0.
2666 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2668 if (I.getType()->isAggregateType()) {
2669 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2670 // an extra "select". This results in much more compact IR.
2671 // Sa = select Sb, poisoned, (select b, Sc, Sd)
2672 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
2674 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2675 // If Sb (condition is poisoned), look for bits in c and d that are equal
2676 // and both unpoisoned.
2677 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2679 // Cast arguments to shadow-compatible type.
2680 C = CreateAppToShadowCast(IRB, C);
2681 D = CreateAppToShadowCast(IRB, D);
2683 // Result shadow if condition shadow is 1.
2684 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
2686 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2688 if (MS.TrackOrigins) {
2689 // Origins are always i32, so any vector conditions must be flattened.
2690 // FIXME: consider tracking vector origins for app vectors?
2691 if (B->getType()->isVectorTy()) {
2692 Type *FlatTy = getShadowTyNoVec(B->getType());
2693 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
2694 ConstantInt::getNullValue(FlatTy));
2695 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
2696 ConstantInt::getNullValue(FlatTy));
2698 // a = select b, c, d
2699 // Oa = Sb ? Ob : (b ? Oc : Od)
2701 &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2702 IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2703 getOrigin(I.getFalseValue()))));
2707 void visitLandingPadInst(LandingPadInst &I) {
2709 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2710 setShadow(&I, getCleanShadow(&I));
2711 setOrigin(&I, getCleanOrigin());
2714 void visitCleanupPadInst(CleanupPadInst &I) {
2715 setShadow(&I, getCleanShadow(&I));
2716 setOrigin(&I, getCleanOrigin());
2719 void visitCatchPad(CatchPadInst &I) {
2720 setShadow(&I, getCleanShadow(&I));
2721 setOrigin(&I, getCleanOrigin());
2724 void visitTerminatePad(TerminatePadInst &I) {
2725 DEBUG(dbgs() << "TerminatePad: " << I << "\n");
2726 // Nothing to do here.
2729 void visitCatchEndPadInst(CatchEndPadInst &I) {
2730 DEBUG(dbgs() << "CatchEndPad: " << I << "\n");
2731 // Nothing to do here.
2734 void visitCleanupEndPadInst(CleanupEndPadInst &I) {
2735 DEBUG(dbgs() << "CleanupEndPad: " << I << "\n");
2736 // Nothing to do here.
2739 void visitGetElementPtrInst(GetElementPtrInst &I) {
2743 void visitExtractValueInst(ExtractValueInst &I) {
2744 IRBuilder<> IRB(&I);
2745 Value *Agg = I.getAggregateOperand();
2746 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2747 Value *AggShadow = getShadow(Agg);
2748 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2749 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2750 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2751 setShadow(&I, ResShadow);
2752 setOriginForNaryOp(I);
2755 void visitInsertValueInst(InsertValueInst &I) {
2756 IRBuilder<> IRB(&I);
2757 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2758 Value *AggShadow = getShadow(I.getAggregateOperand());
2759 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2760 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2761 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2762 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2763 DEBUG(dbgs() << " Res: " << *Res << "\n");
2765 setOriginForNaryOp(I);
2768 void dumpInst(Instruction &I) {
2769 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2770 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2772 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2774 errs() << "QQQ " << I << "\n";
2777 void visitResumeInst(ResumeInst &I) {
2778 DEBUG(dbgs() << "Resume: " << I << "\n");
2779 // Nothing to do here.
2782 void visitCleanupReturnInst(CleanupReturnInst &CRI) {
2783 DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
2784 // Nothing to do here.
2787 void visitCatchReturnInst(CatchReturnInst &CRI) {
2788 DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
2789 // Nothing to do here.
2792 void visitInstruction(Instruction &I) {
2793 // Everything else: stop propagating and check for poisoned shadow.
2794 if (ClDumpStrictInstructions)
2796 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2797 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2798 insertShadowCheck(I.getOperand(i), &I);
2799 setShadow(&I, getCleanShadow(&I));
2800 setOrigin(&I, getCleanOrigin());
2804 /// \brief AMD64-specific implementation of VarArgHelper.
2805 struct VarArgAMD64Helper : public VarArgHelper {
2806 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2807 // See a comment in visitCallSite for more details.
2808 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
2809 static const unsigned AMD64FpEndOffset = 176;
2812 MemorySanitizer &MS;
2813 MemorySanitizerVisitor &MSV;
2814 Value *VAArgTLSCopy;
2815 Value *VAArgOverflowSize;
2817 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2819 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2820 MemorySanitizerVisitor &MSV)
2821 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2822 VAArgOverflowSize(nullptr) {}
2824 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2826 ArgKind classifyArgument(Value* arg) {
2827 // A very rough approximation of X86_64 argument classification rules.
2828 Type *T = arg->getType();
2829 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2830 return AK_FloatingPoint;
2831 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2832 return AK_GeneralPurpose;
2833 if (T->isPointerTy())
2834 return AK_GeneralPurpose;
2838 // For VarArg functions, store the argument shadow in an ABI-specific format
2839 // that corresponds to va_list layout.
2840 // We do this because Clang lowers va_arg in the frontend, and this pass
2841 // only sees the low level code that deals with va_list internals.
2842 // A much easier alternative (provided that Clang emits va_arg instructions)
2843 // would have been to associate each live instance of va_list with a copy of
2844 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2846 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2847 unsigned GpOffset = 0;
2848 unsigned FpOffset = AMD64GpEndOffset;
2849 unsigned OverflowOffset = AMD64FpEndOffset;
2850 const DataLayout &DL = F.getParent()->getDataLayout();
2851 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2852 ArgIt != End; ++ArgIt) {
2854 unsigned ArgNo = CS.getArgumentNo(ArgIt);
2855 bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2857 // ByVal arguments always go to the overflow area.
2858 assert(A->getType()->isPointerTy());
2859 Type *RealTy = A->getType()->getPointerElementType();
2860 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
2861 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
2862 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2863 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2864 ArgSize, kShadowTLSAlignment);
2866 ArgKind AK = classifyArgument(A);
2867 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2869 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2873 case AK_GeneralPurpose:
2874 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2877 case AK_FloatingPoint:
2878 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2882 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
2883 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2884 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2886 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2889 Constant *OverflowSize =
2890 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2891 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2894 /// \brief Compute the shadow address for a given va_arg.
2895 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2897 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2898 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2899 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2903 void visitVAStartInst(VAStartInst &I) override {
2904 if (F.getCallingConv() == CallingConv::X86_64_Win64)
2906 IRBuilder<> IRB(&I);
2907 VAStartInstrumentationList.push_back(&I);
2908 Value *VAListTag = I.getArgOperand(0);
2909 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2911 // Unpoison the whole __va_list_tag.
2912 // FIXME: magic ABI constants.
2913 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2914 /* size */24, /* alignment */8, false);
2917 void visitVACopyInst(VACopyInst &I) override {
2918 if (F.getCallingConv() == CallingConv::X86_64_Win64)
2920 IRBuilder<> IRB(&I);
2921 Value *VAListTag = I.getArgOperand(0);
2922 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2924 // Unpoison the whole __va_list_tag.
2925 // FIXME: magic ABI constants.
2926 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2927 /* size */24, /* alignment */8, false);
2930 void finalizeInstrumentation() override {
2931 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2932 "finalizeInstrumentation called twice");
2933 if (!VAStartInstrumentationList.empty()) {
2934 // If there is a va_start in this function, make a backup copy of
2935 // va_arg_tls somewhere in the function entry block.
2936 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2937 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2939 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2941 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2942 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2945 // Instrument va_start.
2946 // Copy va_list shadow from the backup copy of the TLS contents.
2947 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2948 CallInst *OrigInst = VAStartInstrumentationList[i];
2949 IRBuilder<> IRB(OrigInst->getNextNode());
2950 Value *VAListTag = OrigInst->getArgOperand(0);
2952 Value *RegSaveAreaPtrPtr =
2954 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2955 ConstantInt::get(MS.IntptrTy, 16)),
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,
2961 AMD64FpEndOffset, 16);
2963 Value *OverflowArgAreaPtrPtr =
2965 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2966 ConstantInt::get(MS.IntptrTy, 8)),
2967 Type::getInt64PtrTy(*MS.C));
2968 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2969 Value *OverflowArgAreaShadowPtr =
2970 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2971 Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
2973 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2978 /// \brief MIPS64-specific implementation of VarArgHelper.
2979 struct VarArgMIPS64Helper : public VarArgHelper {
2981 MemorySanitizer &MS;
2982 MemorySanitizerVisitor &MSV;
2983 Value *VAArgTLSCopy;
2986 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2988 VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
2989 MemorySanitizerVisitor &MSV)
2990 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2991 VAArgSize(nullptr) {}
2993 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2994 unsigned VAArgOffset = 0;
2995 const DataLayout &DL = F.getParent()->getDataLayout();
2996 for (CallSite::arg_iterator ArgIt = CS.arg_begin() + 1, End = CS.arg_end();
2997 ArgIt != End; ++ArgIt) {
3000 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
3001 #if defined(__MIPSEB__) || defined(MIPSEB)
3002 // Adjusting the shadow for argument with size < 8 to match the placement
3003 // of bits in big endian system
3005 VAArgOffset += (8 - ArgSize);
3007 Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
3008 VAArgOffset += ArgSize;
3009 VAArgOffset = RoundUpToAlignment(VAArgOffset, 8);
3010 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
3013 Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
3014 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
3015 // a new class member i.e. it is the total size of all VarArgs.
3016 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
3019 /// \brief Compute the shadow address for a given va_arg.
3020 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3022 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3023 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3024 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3028 void visitVAStartInst(VAStartInst &I) override {
3029 IRBuilder<> IRB(&I);
3030 VAStartInstrumentationList.push_back(&I);
3031 Value *VAListTag = I.getArgOperand(0);
3032 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3033 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3034 /* size */8, /* alignment */8, false);
3037 void visitVACopyInst(VACopyInst &I) override {
3038 IRBuilder<> IRB(&I);
3039 Value *VAListTag = I.getArgOperand(0);
3040 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3041 // Unpoison the whole __va_list_tag.
3042 // FIXME: magic ABI constants.
3043 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3044 /* size */8, /* alignment */8, false);
3047 void finalizeInstrumentation() override {
3048 assert(!VAArgSize && !VAArgTLSCopy &&
3049 "finalizeInstrumentation called twice");
3050 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
3051 VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3052 Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
3055 if (!VAStartInstrumentationList.empty()) {
3056 // If there is a va_start in this function, make a backup copy of
3057 // va_arg_tls somewhere in the function entry block.
3058 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3059 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
3062 // Instrument va_start.
3063 // Copy va_list shadow from the backup copy of the TLS contents.
3064 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3065 CallInst *OrigInst = VAStartInstrumentationList[i];
3066 IRBuilder<> IRB(OrigInst->getNextNode());
3067 Value *VAListTag = OrigInst->getArgOperand(0);
3068 Value *RegSaveAreaPtrPtr =
3069 IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3070 Type::getInt64PtrTy(*MS.C));
3071 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3072 Value *RegSaveAreaShadowPtr =
3073 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
3074 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
3079 /// \brief A no-op implementation of VarArgHelper.
3080 struct VarArgNoOpHelper : public VarArgHelper {
3081 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
3082 MemorySanitizerVisitor &MSV) {}
3084 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
3086 void visitVAStartInst(VAStartInst &I) override {}
3088 void visitVACopyInst(VACopyInst &I) override {}
3090 void finalizeInstrumentation() override {}
3093 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
3094 MemorySanitizerVisitor &Visitor) {
3095 // VarArg handling is only implemented on AMD64. False positives are possible
3096 // on other platforms.
3097 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
3098 if (TargetTriple.getArch() == llvm::Triple::x86_64)
3099 return new VarArgAMD64Helper(Func, Msan, Visitor);
3100 else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
3101 TargetTriple.getArch() == llvm::Triple::mips64el)
3102 return new VarArgMIPS64Helper(Func, Msan, Visitor);
3104 return new VarArgNoOpHelper(Func, Msan, Visitor);
3107 } // anonymous namespace
3109 bool MemorySanitizer::runOnFunction(Function &F) {
3110 if (&F == MsanCtorFunction)
3112 MemorySanitizerVisitor Visitor(F, *this);
3114 // Clear out readonly/readnone attributes.
3116 B.addAttribute(Attribute::ReadOnly)
3117 .addAttribute(Attribute::ReadNone);
3118 F.removeAttributes(AttributeSet::FunctionIndex,
3119 AttributeSet::get(F.getContext(),
3120 AttributeSet::FunctionIndex, B));
3122 return Visitor.runOnFunction();