LLVM  mainline
MemorySanitizer.cpp
Go to the documentation of this file.
00001 //===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 /// This file is a part of MemorySanitizer, a detector of uninitialized
00011 /// reads.
00012 ///
00013 /// The algorithm of the tool is similar to Memcheck
00014 /// (http://goo.gl/QKbem). We associate a few shadow bits with every
00015 /// byte of the application memory, poison the shadow of the malloc-ed
00016 /// or alloca-ed memory, load the shadow bits on every memory read,
00017 /// propagate the shadow bits through some of the arithmetic
00018 /// instruction (including MOV), store the shadow bits on every memory
00019 /// write, report a bug on some other instructions (e.g. JMP) if the
00020 /// associated shadow is poisoned.
00021 ///
00022 /// But there are differences too. The first and the major one:
00023 /// compiler instrumentation instead of binary instrumentation. This
00024 /// gives us much better register allocation, possible compiler
00025 /// optimizations and a fast start-up. But this brings the major issue
00026 /// as well: msan needs to see all program events, including system
00027 /// calls and reads/writes in system libraries, so we either need to
00028 /// compile *everything* with msan or use a binary translation
00029 /// component (e.g. DynamoRIO) to instrument pre-built libraries.
00030 /// Another difference from Memcheck is that we use 8 shadow bits per
00031 /// byte of application memory and use a direct shadow mapping. This
00032 /// greatly simplifies the instrumentation code and avoids races on
00033 /// shadow updates (Memcheck is single-threaded so races are not a
00034 /// concern there. Memcheck uses 2 shadow bits per byte with a slow
00035 /// path storage that uses 8 bits per byte).
00036 ///
00037 /// The default value of shadow is 0, which means "clean" (not poisoned).
00038 ///
00039 /// Every module initializer should call __msan_init to ensure that the
00040 /// shadow memory is ready. On error, __msan_warning is called. Since
00041 /// parameters and return values may be passed via registers, we have a
00042 /// specialized thread-local shadow for return values
00043 /// (__msan_retval_tls) and parameters (__msan_param_tls).
00044 ///
00045 ///                           Origin tracking.
00046 ///
00047 /// MemorySanitizer can track origins (allocation points) of all uninitialized
00048 /// values. This behavior is controlled with a flag (msan-track-origins) and is
00049 /// disabled by default.
00050 ///
00051 /// Origins are 4-byte values created and interpreted by the runtime library.
00052 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
00053 /// of application memory. Propagation of origins is basically a bunch of
00054 /// "select" instructions that pick the origin of a dirty argument, if an
00055 /// instruction has one.
00056 ///
00057 /// Every 4 aligned, consecutive bytes of application memory have one origin
00058 /// value associated with them. If these bytes contain uninitialized data
00059 /// coming from 2 different allocations, the last store wins. Because of this,
00060 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
00061 /// practice.
00062 ///
00063 /// Origins are meaningless for fully initialized values, so MemorySanitizer
00064 /// avoids storing origin to memory when a fully initialized value is stored.
00065 /// This way it avoids needless overwritting origin of the 4-byte region on
00066 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
00067 ///
00068 ///                            Atomic handling.
00069 ///
00070 /// Ideally, every atomic store of application value should update the
00071 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
00072 /// of two disjoint locations can not be done without severe slowdown.
00073 ///
00074 /// Therefore, we implement an approximation that may err on the safe side.
00075 /// In this implementation, every atomically accessed location in the program
00076 /// may only change from (partially) uninitialized to fully initialized, but
00077 /// not the other way around. We load the shadow _after_ the application load,
00078 /// and we store the shadow _before_ the app store. Also, we always store clean
00079 /// shadow (if the application store is atomic). This way, if the store-load
00080 /// pair constitutes a happens-before arc, shadow store and load are correctly
00081 /// ordered such that the load will get either the value that was stored, or
00082 /// some later value (which is always clean).
00083 ///
00084 /// This does not work very well with Compare-And-Swap (CAS) and
00085 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
00086 /// must store the new shadow before the app operation, and load the shadow
00087 /// after the app operation. Computers don't work this way. Current
00088 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
00089 /// value. It implements the store part as a simple atomic store by storing a
00090 /// clean shadow.
00091 
00092 //===----------------------------------------------------------------------===//
00093 
00094 #include "llvm/Transforms/Instrumentation.h"
00095 #include "llvm/ADT/DepthFirstIterator.h"
00096 #include "llvm/ADT/SmallString.h"
00097 #include "llvm/ADT/SmallVector.h"
00098 #include "llvm/ADT/StringExtras.h"
00099 #include "llvm/ADT/Triple.h"
00100 #include "llvm/IR/DataLayout.h"
00101 #include "llvm/IR/Function.h"
00102 #include "llvm/IR/IRBuilder.h"
00103 #include "llvm/IR/InlineAsm.h"
00104 #include "llvm/IR/InstVisitor.h"
00105 #include "llvm/IR/IntrinsicInst.h"
00106 #include "llvm/IR/LLVMContext.h"
00107 #include "llvm/IR/MDBuilder.h"
00108 #include "llvm/IR/Module.h"
00109 #include "llvm/IR/Type.h"
00110 #include "llvm/IR/ValueMap.h"
00111 #include "llvm/Support/CommandLine.h"
00112 #include "llvm/Support/Compiler.h"
00113 #include "llvm/Support/Debug.h"
00114 #include "llvm/Support/raw_ostream.h"
00115 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00116 #include "llvm/Transforms/Utils/Local.h"
00117 #include "llvm/Transforms/Utils/ModuleUtils.h"
00118 
00119 using namespace llvm;
00120 
00121 #define DEBUG_TYPE "msan"
00122 
00123 static const unsigned kOriginSize = 4;
00124 static const unsigned kMinOriginAlignment = 4;
00125 static const unsigned kShadowTLSAlignment = 8;
00126 
00127 // These constants must be kept in sync with the ones in msan.h.
00128 static const unsigned kParamTLSSize = 800;
00129 static const unsigned kRetvalTLSSize = 800;
00130 
00131 // Accesses sizes are powers of two: 1, 2, 4, 8.
00132 static const size_t kNumberOfAccessSizes = 4;
00133 
00134 /// \brief Track origins of uninitialized values.
00135 ///
00136 /// Adds a section to MemorySanitizer report that points to the allocation
00137 /// (stack or heap) the uninitialized bits came from originally.
00138 static cl::opt<int> ClTrackOrigins("msan-track-origins",
00139        cl::desc("Track origins (allocation sites) of poisoned memory"),
00140        cl::Hidden, cl::init(0));
00141 static cl::opt<bool> ClKeepGoing("msan-keep-going",
00142        cl::desc("keep going after reporting a UMR"),
00143        cl::Hidden, cl::init(false));
00144 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
00145        cl::desc("poison uninitialized stack variables"),
00146        cl::Hidden, cl::init(true));
00147 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
00148        cl::desc("poison uninitialized stack variables with a call"),
00149        cl::Hidden, cl::init(false));
00150 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
00151        cl::desc("poison uninitialized stack variables with the given patter"),
00152        cl::Hidden, cl::init(0xff));
00153 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
00154        cl::desc("poison undef temps"),
00155        cl::Hidden, cl::init(true));
00156 
00157 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
00158        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
00159        cl::Hidden, cl::init(true));
00160 
00161 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
00162        cl::desc("exact handling of relational integer ICmp"),
00163        cl::Hidden, cl::init(false));
00164 
00165 // This flag controls whether we check the shadow of the address
00166 // operand of load or store. Such bugs are very rare, since load from
00167 // a garbage address typically results in SEGV, but still happen
00168 // (e.g. only lower bits of address are garbage, or the access happens
00169 // early at program startup where malloc-ed memory is more likely to
00170 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
00171 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
00172        cl::desc("report accesses through a pointer which has poisoned shadow"),
00173        cl::Hidden, cl::init(true));
00174 
00175 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
00176        cl::desc("print out instructions with default strict semantics"),
00177        cl::Hidden, cl::init(false));
00178 
00179 static cl::opt<int> ClInstrumentationWithCallThreshold(
00180     "msan-instrumentation-with-call-threshold",
00181     cl::desc(
00182         "If the function being instrumented requires more than "
00183         "this number of checks and origin stores, use callbacks instead of "
00184         "inline checks (-1 means never use callbacks)."),
00185     cl::Hidden, cl::init(3500));
00186 
00187 // This is an experiment to enable handling of cases where shadow is a non-zero
00188 // compile-time constant. For some unexplainable reason they were silently
00189 // ignored in the instrumentation.
00190 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
00191        cl::desc("Insert checks for constant shadow values"),
00192        cl::Hidden, cl::init(false));
00193 
00194 static const char *const kMsanModuleCtorName = "msan.module_ctor";
00195 static const char *const kMsanInitName = "__msan_init";
00196 
00197 namespace {
00198 
00199 // Memory map parameters used in application-to-shadow address calculation.
00200 // Offset = (Addr & ~AndMask) ^ XorMask
00201 // Shadow = ShadowBase + Offset
00202 // Origin = OriginBase + Offset
00203 struct MemoryMapParams {
00204   uint64_t AndMask;
00205   uint64_t XorMask;
00206   uint64_t ShadowBase;
00207   uint64_t OriginBase;
00208 };
00209 
00210 struct PlatformMemoryMapParams {
00211   const MemoryMapParams *bits32;
00212   const MemoryMapParams *bits64;
00213 };
00214 
00215 // i386 Linux
00216 static const MemoryMapParams Linux_I386_MemoryMapParams = {
00217   0x000080000000,  // AndMask
00218   0,               // XorMask (not used)
00219   0,               // ShadowBase (not used)
00220   0x000040000000,  // OriginBase
00221 };
00222 
00223 // x86_64 Linux
00224 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
00225   0x400000000000,  // AndMask
00226   0,               // XorMask (not used)
00227   0,               // ShadowBase (not used)
00228   0x200000000000,  // OriginBase
00229 };
00230 
00231 // mips64 Linux
00232 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
00233   0x004000000000,  // AndMask
00234   0,               // XorMask (not used)
00235   0,               // ShadowBase (not used)
00236   0x002000000000,  // OriginBase
00237 };
00238 
00239 // i386 FreeBSD
00240 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
00241   0x000180000000,  // AndMask
00242   0x000040000000,  // XorMask
00243   0x000020000000,  // ShadowBase
00244   0x000700000000,  // OriginBase
00245 };
00246 
00247 // x86_64 FreeBSD
00248 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
00249   0xc00000000000,  // AndMask
00250   0x200000000000,  // XorMask
00251   0x100000000000,  // ShadowBase
00252   0x380000000000,  // OriginBase
00253 };
00254 
00255 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
00256   &Linux_I386_MemoryMapParams,
00257   &Linux_X86_64_MemoryMapParams,
00258 };
00259 
00260 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
00261   NULL,
00262   &Linux_MIPS64_MemoryMapParams,
00263 };
00264 
00265 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
00266   &FreeBSD_I386_MemoryMapParams,
00267   &FreeBSD_X86_64_MemoryMapParams,
00268 };
00269 
00270 /// \brief An instrumentation pass implementing detection of uninitialized
00271 /// reads.
00272 ///
00273 /// MemorySanitizer: instrument the code in module to find
00274 /// uninitialized reads.
00275 class MemorySanitizer : public FunctionPass {
00276  public:
00277   MemorySanitizer(int TrackOrigins = 0)
00278       : FunctionPass(ID),
00279         TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
00280         WarningFn(nullptr) {}
00281   const char *getPassName() const override { return "MemorySanitizer"; }
00282   bool runOnFunction(Function &F) override;
00283   bool doInitialization(Module &M) override;
00284   static char ID;  // Pass identification, replacement for typeid.
00285 
00286  private:
00287   void initializeCallbacks(Module &M);
00288 
00289   /// \brief Track origins (allocation points) of uninitialized values.
00290   int TrackOrigins;
00291 
00292   LLVMContext *C;
00293   Type *IntptrTy;
00294   Type *OriginTy;
00295   /// \brief Thread-local shadow storage for function parameters.
00296   GlobalVariable *ParamTLS;
00297   /// \brief Thread-local origin storage for function parameters.
00298   GlobalVariable *ParamOriginTLS;
00299   /// \brief Thread-local shadow storage for function return value.
00300   GlobalVariable *RetvalTLS;
00301   /// \brief Thread-local origin storage for function return value.
00302   GlobalVariable *RetvalOriginTLS;
00303   /// \brief Thread-local shadow storage for in-register va_arg function
00304   /// parameters (x86_64-specific).
00305   GlobalVariable *VAArgTLS;
00306   /// \brief Thread-local shadow storage for va_arg overflow area
00307   /// (x86_64-specific).
00308   GlobalVariable *VAArgOverflowSizeTLS;
00309   /// \brief Thread-local space used to pass origin value to the UMR reporting
00310   /// function.
00311   GlobalVariable *OriginTLS;
00312 
00313   /// \brief The run-time callback to print a warning.
00314   Value *WarningFn;
00315   // These arrays are indexed by log2(AccessSize).
00316   Value *MaybeWarningFn[kNumberOfAccessSizes];
00317   Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
00318 
00319   /// \brief Run-time helper that generates a new origin value for a stack
00320   /// allocation.
00321   Value *MsanSetAllocaOrigin4Fn;
00322   /// \brief Run-time helper that poisons stack on function entry.
00323   Value *MsanPoisonStackFn;
00324   /// \brief Run-time helper that records a store (or any event) of an
00325   /// uninitialized value and returns an updated origin id encoding this info.
00326   Value *MsanChainOriginFn;
00327   /// \brief MSan runtime replacements for memmove, memcpy and memset.
00328   Value *MemmoveFn, *MemcpyFn, *MemsetFn;
00329 
00330   /// \brief Memory map parameters used in application-to-shadow calculation.
00331   const MemoryMapParams *MapParams;
00332 
00333   MDNode *ColdCallWeights;
00334   /// \brief Branch weights for origin store.
00335   MDNode *OriginStoreWeights;
00336   /// \brief An empty volatile inline asm that prevents callback merge.
00337   InlineAsm *EmptyAsm;
00338   Function *MsanCtorFunction;
00339 
00340   friend struct MemorySanitizerVisitor;
00341   friend struct VarArgAMD64Helper;
00342   friend struct VarArgMIPS64Helper;
00343 };
00344 }  // namespace
00345 
00346 char MemorySanitizer::ID = 0;
00347 INITIALIZE_PASS(MemorySanitizer, "msan",
00348                 "MemorySanitizer: detects uninitialized reads.",
00349                 false, false)
00350 
00351 FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
00352   return new MemorySanitizer(TrackOrigins);
00353 }
00354 
00355 /// \brief Create a non-const global initialized with the given string.
00356 ///
00357 /// Creates a writable global for Str so that we can pass it to the
00358 /// run-time lib. Runtime uses first 4 bytes of the string to store the
00359 /// frame ID, so the string needs to be mutable.
00360 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
00361                                                             StringRef Str) {
00362   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
00363   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
00364                             GlobalValue::PrivateLinkage, StrConst, "");
00365 }
00366 
00367 
00368 /// \brief Insert extern declaration of runtime-provided functions and globals.
00369 void MemorySanitizer::initializeCallbacks(Module &M) {
00370   // Only do this once.
00371   if (WarningFn)
00372     return;
00373 
00374   IRBuilder<> IRB(*C);
00375   // Create the callback.
00376   // FIXME: this function should have "Cold" calling conv,
00377   // which is not yet implemented.
00378   StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
00379                                         : "__msan_warning_noreturn";
00380   WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
00381 
00382   for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
00383        AccessSizeIndex++) {
00384     unsigned AccessSize = 1 << AccessSizeIndex;
00385     std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
00386     MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
00387         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
00388         IRB.getInt32Ty(), nullptr);
00389 
00390     FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
00391     MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
00392         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
00393         IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
00394   }
00395 
00396   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
00397     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
00398     IRB.getInt8PtrTy(), IntptrTy, nullptr);
00399   MsanPoisonStackFn =
00400       M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
00401                             IRB.getInt8PtrTy(), IntptrTy, nullptr);
00402   MsanChainOriginFn = M.getOrInsertFunction(
00403     "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
00404   MemmoveFn = M.getOrInsertFunction(
00405     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
00406     IRB.getInt8PtrTy(), IntptrTy, nullptr);
00407   MemcpyFn = M.getOrInsertFunction(
00408     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
00409     IntptrTy, nullptr);
00410   MemsetFn = M.getOrInsertFunction(
00411     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
00412     IntptrTy, nullptr);
00413 
00414   // Create globals.
00415   RetvalTLS = new GlobalVariable(
00416     M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
00417     GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
00418     GlobalVariable::InitialExecTLSModel);
00419   RetvalOriginTLS = new GlobalVariable(
00420     M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
00421     "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
00422 
00423   ParamTLS = new GlobalVariable(
00424     M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
00425     GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
00426     GlobalVariable::InitialExecTLSModel);
00427   ParamOriginTLS = new GlobalVariable(
00428     M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
00429     GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
00430     nullptr, GlobalVariable::InitialExecTLSModel);
00431 
00432   VAArgTLS = new GlobalVariable(
00433     M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
00434     GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
00435     GlobalVariable::InitialExecTLSModel);
00436   VAArgOverflowSizeTLS = new GlobalVariable(
00437     M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
00438     "__msan_va_arg_overflow_size_tls", nullptr,
00439     GlobalVariable::InitialExecTLSModel);
00440   OriginTLS = new GlobalVariable(
00441     M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
00442     "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
00443 
00444   // We insert an empty inline asm after __msan_report* to avoid callback merge.
00445   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
00446                             StringRef(""), StringRef(""),
00447                             /*hasSideEffects=*/true);
00448 }
00449 
00450 /// \brief Module-level initialization.
00451 ///
00452 /// inserts a call to __msan_init to the module's constructor list.
00453 bool MemorySanitizer::doInitialization(Module &M) {
00454   auto &DL = M.getDataLayout();
00455 
00456   Triple TargetTriple(M.getTargetTriple());
00457   switch (TargetTriple.getOS()) {
00458     case Triple::FreeBSD:
00459       switch (TargetTriple.getArch()) {
00460         case Triple::x86_64:
00461           MapParams = FreeBSD_X86_MemoryMapParams.bits64;
00462           break;
00463         case Triple::x86:
00464           MapParams = FreeBSD_X86_MemoryMapParams.bits32;
00465           break;
00466         default:
00467           report_fatal_error("unsupported architecture");
00468       }
00469       break;
00470     case Triple::Linux:
00471       switch (TargetTriple.getArch()) {
00472         case Triple::x86_64:
00473           MapParams = Linux_X86_MemoryMapParams.bits64;
00474           break;
00475         case Triple::x86:
00476           MapParams = Linux_X86_MemoryMapParams.bits32;
00477           break;
00478         case Triple::mips64:
00479         case Triple::mips64el:
00480           MapParams = Linux_MIPS_MemoryMapParams.bits64;
00481           break;
00482         default:
00483           report_fatal_error("unsupported architecture");
00484       }
00485       break;
00486     default:
00487       report_fatal_error("unsupported operating system");
00488   }
00489 
00490   C = &(M.getContext());
00491   IRBuilder<> IRB(*C);
00492   IntptrTy = IRB.getIntPtrTy(DL);
00493   OriginTy = IRB.getInt32Ty();
00494 
00495   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
00496   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
00497 
00498   std::tie(MsanCtorFunction, std::ignore) =
00499       createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
00500                                           /*InitArgTypes=*/{},
00501                                           /*InitArgs=*/{});
00502 
00503   appendToGlobalCtors(M, MsanCtorFunction, 0);
00504 
00505   if (TrackOrigins)
00506     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
00507                        IRB.getInt32(TrackOrigins), "__msan_track_origins");
00508 
00509   if (ClKeepGoing)
00510     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
00511                        IRB.getInt32(ClKeepGoing), "__msan_keep_going");
00512 
00513   return true;
00514 }
00515 
00516 namespace {
00517 
00518 /// \brief A helper class that handles instrumentation of VarArg
00519 /// functions on a particular platform.
00520 ///
00521 /// Implementations are expected to insert the instrumentation
00522 /// necessary to propagate argument shadow through VarArg function
00523 /// calls. Visit* methods are called during an InstVisitor pass over
00524 /// the function, and should avoid creating new basic blocks. A new
00525 /// instance of this class is created for each instrumented function.
00526 struct VarArgHelper {
00527   /// \brief Visit a CallSite.
00528   virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
00529 
00530   /// \brief Visit a va_start call.
00531   virtual void visitVAStartInst(VAStartInst &I) = 0;
00532 
00533   /// \brief Visit a va_copy call.
00534   virtual void visitVACopyInst(VACopyInst &I) = 0;
00535 
00536   /// \brief Finalize function instrumentation.
00537   ///
00538   /// This method is called after visiting all interesting (see above)
00539   /// instructions in a function.
00540   virtual void finalizeInstrumentation() = 0;
00541 
00542   virtual ~VarArgHelper() {}
00543 };
00544 
00545 struct MemorySanitizerVisitor;
00546 
00547 VarArgHelper*
00548 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
00549                    MemorySanitizerVisitor &Visitor);
00550 
00551 unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
00552   if (TypeSize <= 8) return 0;
00553   return Log2_32_Ceil(TypeSize / 8);
00554 }
00555 
00556 /// This class does all the work for a given function. Store and Load
00557 /// instructions store and load corresponding shadow and origin
00558 /// values. Most instructions propagate shadow from arguments to their
00559 /// return values. Certain instructions (most importantly, BranchInst)
00560 /// test their argument shadow and print reports (with a runtime call) if it's
00561 /// non-zero.
00562 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
00563   Function &F;
00564   MemorySanitizer &MS;
00565   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
00566   ValueMap<Value*, Value*> ShadowMap, OriginMap;
00567   std::unique_ptr<VarArgHelper> VAHelper;
00568 
00569   // The following flags disable parts of MSan instrumentation based on
00570   // blacklist contents and command-line options.
00571   bool InsertChecks;
00572   bool PropagateShadow;
00573   bool PoisonStack;
00574   bool PoisonUndef;
00575   bool CheckReturnValue;
00576 
00577   struct ShadowOriginAndInsertPoint {
00578     Value *Shadow;
00579     Value *Origin;
00580     Instruction *OrigIns;
00581     ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
00582       : Shadow(S), Origin(O), OrigIns(I) { }
00583   };
00584   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
00585   SmallVector<Instruction*, 16> StoreList;
00586 
00587   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
00588       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
00589     bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
00590     InsertChecks = SanitizeFunction;
00591     PropagateShadow = SanitizeFunction;
00592     PoisonStack = SanitizeFunction && ClPoisonStack;
00593     PoisonUndef = SanitizeFunction && ClPoisonUndef;
00594     // FIXME: Consider using SpecialCaseList to specify a list of functions that
00595     // must always return fully initialized values. For now, we hardcode "main".
00596     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
00597 
00598     DEBUG(if (!InsertChecks)
00599           dbgs() << "MemorySanitizer is not inserting checks into '"
00600                  << F.getName() << "'\n");
00601   }
00602 
00603   Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
00604     if (MS.TrackOrigins <= 1) return V;
00605     return IRB.CreateCall(MS.MsanChainOriginFn, V);
00606   }
00607 
00608   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
00609     const DataLayout &DL = F.getParent()->getDataLayout();
00610     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
00611     if (IntptrSize == kOriginSize) return Origin;
00612     assert(IntptrSize == kOriginSize * 2);
00613     Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
00614     return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
00615   }
00616 
00617   /// \brief Fill memory range with the given origin value.
00618   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
00619                    unsigned Size, unsigned Alignment) {
00620     const DataLayout &DL = F.getParent()->getDataLayout();
00621     unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
00622     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
00623     assert(IntptrAlignment >= kMinOriginAlignment);
00624     assert(IntptrSize >= kOriginSize);
00625 
00626     unsigned Ofs = 0;
00627     unsigned CurrentAlignment = Alignment;
00628     if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
00629       Value *IntptrOrigin = originToIntptr(IRB, Origin);
00630       Value *IntptrOriginPtr =
00631           IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
00632       for (unsigned i = 0; i < Size / IntptrSize; ++i) {
00633         Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
00634                        : IntptrOriginPtr;
00635         IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
00636         Ofs += IntptrSize / kOriginSize;
00637         CurrentAlignment = IntptrAlignment;
00638       }
00639     }
00640 
00641     for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
00642       Value *GEP =
00643           i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
00644       IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
00645       CurrentAlignment = kMinOriginAlignment;
00646     }
00647   }
00648 
00649   void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
00650                    unsigned Alignment, bool AsCall) {
00651     const DataLayout &DL = F.getParent()->getDataLayout();
00652     unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
00653     unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
00654     if (isa<StructType>(Shadow->getType())) {
00655       paintOrigin(IRB, updateOrigin(Origin, IRB),
00656                   getOriginPtr(Addr, IRB, Alignment), StoreSize,
00657                   OriginAlignment);
00658     } else {
00659       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
00660       Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
00661       if (ConstantShadow) {
00662         if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
00663           paintOrigin(IRB, updateOrigin(Origin, IRB),
00664                       getOriginPtr(Addr, IRB, Alignment), StoreSize,
00665                       OriginAlignment);
00666         return;
00667       }
00668 
00669       unsigned TypeSizeInBits =
00670           DL.getTypeSizeInBits(ConvertedShadow->getType());
00671       unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
00672       if (AsCall && SizeIndex < kNumberOfAccessSizes) {
00673         Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
00674         Value *ConvertedShadow2 = IRB.CreateZExt(
00675             ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
00676         IRB.CreateCall(Fn, {ConvertedShadow2,
00677                             IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
00678                             Origin});
00679       } else {
00680         Value *Cmp = IRB.CreateICmpNE(
00681             ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
00682         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
00683             Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
00684         IRBuilder<> IRBNew(CheckTerm);
00685         paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
00686                     getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
00687                     OriginAlignment);
00688       }
00689     }
00690   }
00691 
00692   void materializeStores(bool InstrumentWithCalls) {
00693     for (auto Inst : StoreList) {
00694       StoreInst &SI = *dyn_cast<StoreInst>(Inst);
00695 
00696       IRBuilder<> IRB(&SI);
00697       Value *Val = SI.getValueOperand();
00698       Value *Addr = SI.getPointerOperand();
00699       Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
00700       Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
00701 
00702       StoreInst *NewSI =
00703           IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
00704       DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
00705       (void)NewSI;
00706 
00707       if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
00708 
00709       if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
00710 
00711       if (MS.TrackOrigins && !SI.isAtomic())
00712         storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI.getAlignment(),
00713                     InstrumentWithCalls);
00714     }
00715   }
00716 
00717   void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
00718                            bool AsCall) {
00719     IRBuilder<> IRB(OrigIns);
00720     DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
00721     Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
00722     DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
00723 
00724     Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
00725     if (ConstantShadow) {
00726       if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
00727         if (MS.TrackOrigins) {
00728           IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
00729                           MS.OriginTLS);
00730         }
00731         IRB.CreateCall(MS.WarningFn, {});
00732         IRB.CreateCall(MS.EmptyAsm, {});
00733         // FIXME: Insert UnreachableInst if !ClKeepGoing?
00734         // This may invalidate some of the following checks and needs to be done
00735         // at the very end.
00736       }
00737       return;
00738     }
00739 
00740     const DataLayout &DL = OrigIns->getModule()->getDataLayout();
00741 
00742     unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
00743     unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
00744     if (AsCall && SizeIndex < kNumberOfAccessSizes) {
00745       Value *Fn = MS.MaybeWarningFn[SizeIndex];
00746       Value *ConvertedShadow2 =
00747           IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
00748       IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
00749                                                 ? Origin
00750                                                 : (Value *)IRB.getInt32(0)});
00751     } else {
00752       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
00753                                     getCleanShadow(ConvertedShadow), "_mscmp");
00754       Instruction *CheckTerm = SplitBlockAndInsertIfThen(
00755           Cmp, OrigIns,
00756           /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
00757 
00758       IRB.SetInsertPoint(CheckTerm);
00759       if (MS.TrackOrigins) {
00760         IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
00761                         MS.OriginTLS);
00762       }
00763       IRB.CreateCall(MS.WarningFn, {});
00764       IRB.CreateCall(MS.EmptyAsm, {});
00765       DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
00766     }
00767   }
00768 
00769   void materializeChecks(bool InstrumentWithCalls) {
00770     for (const auto &ShadowData : InstrumentationList) {
00771       Instruction *OrigIns = ShadowData.OrigIns;
00772       Value *Shadow = ShadowData.Shadow;
00773       Value *Origin = ShadowData.Origin;
00774       materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
00775     }
00776     DEBUG(dbgs() << "DONE:\n" << F);
00777   }
00778 
00779   /// \brief Add MemorySanitizer instrumentation to a function.
00780   bool runOnFunction() {
00781     MS.initializeCallbacks(*F.getParent());
00782 
00783     // In the presence of unreachable blocks, we may see Phi nodes with
00784     // incoming nodes from such blocks. Since InstVisitor skips unreachable
00785     // blocks, such nodes will not have any shadow value associated with them.
00786     // It's easier to remove unreachable blocks than deal with missing shadow.
00787     removeUnreachableBlocks(F);
00788 
00789     // Iterate all BBs in depth-first order and create shadow instructions
00790     // for all instructions (where applicable).
00791     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
00792     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
00793       visit(*BB);
00794 
00795 
00796     // Finalize PHI nodes.
00797     for (PHINode *PN : ShadowPHINodes) {
00798       PHINode *PNS = cast<PHINode>(getShadow(PN));
00799       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
00800       size_t NumValues = PN->getNumIncomingValues();
00801       for (size_t v = 0; v < NumValues; v++) {
00802         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
00803         if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
00804       }
00805     }
00806 
00807     VAHelper->finalizeInstrumentation();
00808 
00809     bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
00810                                InstrumentationList.size() + StoreList.size() >
00811                                    (unsigned)ClInstrumentationWithCallThreshold;
00812 
00813     // Delayed instrumentation of StoreInst.
00814     // This may add new checks to be inserted later.
00815     materializeStores(InstrumentWithCalls);
00816 
00817     // Insert shadow value checks.
00818     materializeChecks(InstrumentWithCalls);
00819 
00820     return true;
00821   }
00822 
00823   /// \brief Compute the shadow type that corresponds to a given Value.
00824   Type *getShadowTy(Value *V) {
00825     return getShadowTy(V->getType());
00826   }
00827 
00828   /// \brief Compute the shadow type that corresponds to a given Type.
00829   Type *getShadowTy(Type *OrigTy) {
00830     if (!OrigTy->isSized()) {
00831       return nullptr;
00832     }
00833     // For integer type, shadow is the same as the original type.
00834     // This may return weird-sized types like i1.
00835     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
00836       return IT;
00837     const DataLayout &DL = F.getParent()->getDataLayout();
00838     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
00839       uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
00840       return VectorType::get(IntegerType::get(*MS.C, EltSize),
00841                              VT->getNumElements());
00842     }
00843     if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
00844       return ArrayType::get(getShadowTy(AT->getElementType()),
00845                             AT->getNumElements());
00846     }
00847     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
00848       SmallVector<Type*, 4> Elements;
00849       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
00850         Elements.push_back(getShadowTy(ST->getElementType(i)));
00851       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
00852       DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
00853       return Res;
00854     }
00855     uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
00856     return IntegerType::get(*MS.C, TypeSize);
00857   }
00858 
00859   /// \brief Flatten a vector type.
00860   Type *getShadowTyNoVec(Type *ty) {
00861     if (VectorType *vt = dyn_cast<VectorType>(ty))
00862       return IntegerType::get(*MS.C, vt->getBitWidth());
00863     return ty;
00864   }
00865 
00866   /// \brief Convert a shadow value to it's flattened variant.
00867   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
00868     Type *Ty = V->getType();
00869     Type *NoVecTy = getShadowTyNoVec(Ty);
00870     if (Ty == NoVecTy) return V;
00871     return IRB.CreateBitCast(V, NoVecTy);
00872   }
00873 
00874   /// \brief Compute the integer shadow offset that corresponds to a given
00875   /// application address.
00876   ///
00877   /// Offset = (Addr & ~AndMask) ^ XorMask
00878   Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
00879     uint64_t AndMask = MS.MapParams->AndMask;
00880     assert(AndMask != 0 && "AndMask shall be specified");
00881     Value *OffsetLong =
00882       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
00883                     ConstantInt::get(MS.IntptrTy, ~AndMask));
00884 
00885     uint64_t XorMask = MS.MapParams->XorMask;
00886     if (XorMask != 0)
00887       OffsetLong = IRB.CreateXor(OffsetLong,
00888                                  ConstantInt::get(MS.IntptrTy, XorMask));
00889     return OffsetLong;
00890   }
00891 
00892   /// \brief Compute the shadow address that corresponds to a given application
00893   /// address.
00894   ///
00895   /// Shadow = ShadowBase + Offset
00896   Value *getShadowPtr(Value *Addr, Type *ShadowTy,
00897                       IRBuilder<> &IRB) {
00898     Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
00899     uint64_t ShadowBase = MS.MapParams->ShadowBase;
00900     if (ShadowBase != 0)
00901       ShadowLong =
00902         IRB.CreateAdd(ShadowLong,
00903                       ConstantInt::get(MS.IntptrTy, ShadowBase));
00904     return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
00905   }
00906 
00907   /// \brief Compute the origin address that corresponds to a given application
00908   /// address.
00909   ///
00910   /// OriginAddr = (OriginBase + Offset) & ~3ULL
00911   Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
00912     Value *OriginLong = getShadowPtrOffset(Addr, IRB);
00913     uint64_t OriginBase = MS.MapParams->OriginBase;
00914     if (OriginBase != 0)
00915       OriginLong =
00916         IRB.CreateAdd(OriginLong,
00917                       ConstantInt::get(MS.IntptrTy, OriginBase));
00918     if (Alignment < kMinOriginAlignment) {
00919       uint64_t Mask = kMinOriginAlignment - 1;
00920       OriginLong = IRB.CreateAnd(OriginLong,
00921                                  ConstantInt::get(MS.IntptrTy, ~Mask));
00922     }
00923     return IRB.CreateIntToPtr(OriginLong,
00924                               PointerType::get(IRB.getInt32Ty(), 0));
00925   }
00926 
00927   /// \brief Compute the shadow address for a given function argument.
00928   ///
00929   /// Shadow = ParamTLS+ArgOffset.
00930   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
00931                                  int ArgOffset) {
00932     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
00933     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
00934     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
00935                               "_msarg");
00936   }
00937 
00938   /// \brief Compute the origin address for a given function argument.
00939   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
00940                                  int ArgOffset) {
00941     if (!MS.TrackOrigins) return nullptr;
00942     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
00943     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
00944     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
00945                               "_msarg_o");
00946   }
00947 
00948   /// \brief Compute the shadow address for a retval.
00949   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
00950     Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
00951     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
00952                               "_msret");
00953   }
00954 
00955   /// \brief Compute the origin address for a retval.
00956   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
00957     // We keep a single origin for the entire retval. Might be too optimistic.
00958     return MS.RetvalOriginTLS;
00959   }
00960 
00961   /// \brief Set SV to be the shadow value for V.
00962   void setShadow(Value *V, Value *SV) {
00963     assert(!ShadowMap.count(V) && "Values may only have one shadow");
00964     ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
00965   }
00966 
00967   /// \brief Set Origin to be the origin value for V.
00968   void setOrigin(Value *V, Value *Origin) {
00969     if (!MS.TrackOrigins) return;
00970     assert(!OriginMap.count(V) && "Values may only have one origin");
00971     DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
00972     OriginMap[V] = Origin;
00973   }
00974 
00975   /// \brief Create a clean shadow value for a given value.
00976   ///
00977   /// Clean shadow (all zeroes) means all bits of the value are defined
00978   /// (initialized).
00979   Constant *getCleanShadow(Value *V) {
00980     Type *ShadowTy = getShadowTy(V);
00981     if (!ShadowTy)
00982       return nullptr;
00983     return Constant::getNullValue(ShadowTy);
00984   }
00985 
00986   /// \brief Create a dirty shadow of a given shadow type.
00987   Constant *getPoisonedShadow(Type *ShadowTy) {
00988     assert(ShadowTy);
00989     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
00990       return Constant::getAllOnesValue(ShadowTy);
00991     if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
00992       SmallVector<Constant *, 4> Vals(AT->getNumElements(),
00993                                       getPoisonedShadow(AT->getElementType()));
00994       return ConstantArray::get(AT, Vals);
00995     }
00996     if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
00997       SmallVector<Constant *, 4> Vals;
00998       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
00999         Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
01000       return ConstantStruct::get(ST, Vals);
01001     }
01002     llvm_unreachable("Unexpected shadow type");
01003   }
01004 
01005   /// \brief Create a dirty shadow for a given value.
01006   Constant *getPoisonedShadow(Value *V) {
01007     Type *ShadowTy = getShadowTy(V);
01008     if (!ShadowTy)
01009       return nullptr;
01010     return getPoisonedShadow(ShadowTy);
01011   }
01012 
01013   /// \brief Create a clean (zero) origin.
01014   Value *getCleanOrigin() {
01015     return Constant::getNullValue(MS.OriginTy);
01016   }
01017 
01018   /// \brief Get the shadow value for a given Value.
01019   ///
01020   /// This function either returns the value set earlier with setShadow,
01021   /// or extracts if from ParamTLS (for function arguments).
01022   Value *getShadow(Value *V) {
01023     if (!PropagateShadow) return getCleanShadow(V);
01024     if (Instruction *I = dyn_cast<Instruction>(V)) {
01025       // For instructions the shadow is already stored in the map.
01026       Value *Shadow = ShadowMap[V];
01027       if (!Shadow) {
01028         DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
01029         (void)I;
01030         assert(Shadow && "No shadow for a value");
01031       }
01032       return Shadow;
01033     }
01034     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
01035       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
01036       DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
01037       (void)U;
01038       return AllOnes;
01039     }
01040     if (Argument *A = dyn_cast<Argument>(V)) {
01041       // For arguments we compute the shadow on demand and store it in the map.
01042       Value **ShadowPtr = &ShadowMap[V];
01043       if (*ShadowPtr)
01044         return *ShadowPtr;
01045       Function *F = A->getParent();
01046       IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
01047       unsigned ArgOffset = 0;
01048       const DataLayout &DL = F->getParent()->getDataLayout();
01049       for (auto &FArg : F->args()) {
01050         if (!FArg.getType()->isSized()) {
01051           DEBUG(dbgs() << "Arg is not sized\n");
01052           continue;
01053         }
01054         unsigned Size =
01055             FArg.hasByValAttr()
01056                 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
01057                 : DL.getTypeAllocSize(FArg.getType());
01058         if (A == &FArg) {
01059           bool Overflow = ArgOffset + Size > kParamTLSSize;
01060           Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
01061           if (FArg.hasByValAttr()) {
01062             // ByVal pointer itself has clean shadow. We copy the actual
01063             // argument shadow to the underlying memory.
01064             // Figure out maximal valid memcpy alignment.
01065             unsigned ArgAlign = FArg.getParamAlignment();
01066             if (ArgAlign == 0) {
01067               Type *EltType = A->getType()->getPointerElementType();
01068               ArgAlign = DL.getABITypeAlignment(EltType);
01069             }
01070             if (Overflow) {
01071               // ParamTLS overflow.
01072               EntryIRB.CreateMemSet(
01073                   getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
01074                   Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
01075             } else {
01076               unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
01077               Value *Cpy = EntryIRB.CreateMemCpy(
01078                   getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
01079                   CopyAlign);
01080               DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
01081               (void)Cpy;
01082             }
01083             *ShadowPtr = getCleanShadow(V);
01084           } else {
01085             if (Overflow) {
01086               // ParamTLS overflow.
01087               *ShadowPtr = getCleanShadow(V);
01088             } else {
01089               *ShadowPtr =
01090                   EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
01091             }
01092           }
01093           DEBUG(dbgs() << "  ARG:    "  << FArg << " ==> " <<
01094                 **ShadowPtr << "\n");
01095           if (MS.TrackOrigins && !Overflow) {
01096             Value *OriginPtr =
01097                 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
01098             setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
01099           } else {
01100             setOrigin(A, getCleanOrigin());
01101           }
01102         }
01103         ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
01104       }
01105       assert(*ShadowPtr && "Could not find shadow for an argument");
01106       return *ShadowPtr;
01107     }
01108     // For everything else the shadow is zero.
01109     return getCleanShadow(V);
01110   }
01111 
01112   /// \brief Get the shadow for i-th argument of the instruction I.
01113   Value *getShadow(Instruction *I, int i) {
01114     return getShadow(I->getOperand(i));
01115   }
01116 
01117   /// \brief Get the origin for a value.
01118   Value *getOrigin(Value *V) {
01119     if (!MS.TrackOrigins) return nullptr;
01120     if (!PropagateShadow) return getCleanOrigin();
01121     if (isa<Constant>(V)) return getCleanOrigin();
01122     assert((isa<Instruction>(V) || isa<Argument>(V)) &&
01123            "Unexpected value type in getOrigin()");
01124     Value *Origin = OriginMap[V];
01125     assert(Origin && "Missing origin");
01126     return Origin;
01127   }
01128 
01129   /// \brief Get the origin for i-th argument of the instruction I.
01130   Value *getOrigin(Instruction *I, int i) {
01131     return getOrigin(I->getOperand(i));
01132   }
01133 
01134   /// \brief Remember the place where a shadow check should be inserted.
01135   ///
01136   /// This location will be later instrumented with a check that will print a
01137   /// UMR warning in runtime if the shadow value is not 0.
01138   void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
01139     assert(Shadow);
01140     if (!InsertChecks) return;
01141 #ifndef NDEBUG
01142     Type *ShadowTy = Shadow->getType();
01143     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
01144            "Can only insert checks for integer and vector shadow types");
01145 #endif
01146     InstrumentationList.push_back(
01147         ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
01148   }
01149 
01150   /// \brief Remember the place where a shadow check should be inserted.
01151   ///
01152   /// This location will be later instrumented with a check that will print a
01153   /// UMR warning in runtime if the value is not fully defined.
01154   void insertShadowCheck(Value *Val, Instruction *OrigIns) {
01155     assert(Val);
01156     Value *Shadow, *Origin;
01157     if (ClCheckConstantShadow) {
01158       Shadow = getShadow(Val);
01159       if (!Shadow) return;
01160       Origin = getOrigin(Val);
01161     } else {
01162       Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
01163       if (!Shadow) return;
01164       Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
01165     }
01166     insertShadowCheck(Shadow, Origin, OrigIns);
01167   }
01168 
01169   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
01170     switch (a) {
01171       case NotAtomic:
01172         return NotAtomic;
01173       case Unordered:
01174       case Monotonic:
01175       case Release:
01176         return Release;
01177       case Acquire:
01178       case AcquireRelease:
01179         return AcquireRelease;
01180       case SequentiallyConsistent:
01181         return SequentiallyConsistent;
01182     }
01183     llvm_unreachable("Unknown ordering");
01184   }
01185 
01186   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
01187     switch (a) {
01188       case NotAtomic:
01189         return NotAtomic;
01190       case Unordered:
01191       case Monotonic:
01192       case Acquire:
01193         return Acquire;
01194       case Release:
01195       case AcquireRelease:
01196         return AcquireRelease;
01197       case SequentiallyConsistent:
01198         return SequentiallyConsistent;
01199     }
01200     llvm_unreachable("Unknown ordering");
01201   }
01202 
01203   // ------------------- Visitors.
01204 
01205   /// \brief Instrument LoadInst
01206   ///
01207   /// Loads the corresponding shadow and (optionally) origin.
01208   /// Optionally, checks that the load address is fully defined.
01209   void visitLoadInst(LoadInst &I) {
01210     assert(I.getType()->isSized() && "Load type must have size");
01211     IRBuilder<> IRB(I.getNextNode());
01212     Type *ShadowTy = getShadowTy(&I);
01213     Value *Addr = I.getPointerOperand();
01214     if (PropagateShadow && !I.getMetadata("nosanitize")) {
01215       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
01216       setShadow(&I,
01217                 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
01218     } else {
01219       setShadow(&I, getCleanShadow(&I));
01220     }
01221 
01222     if (ClCheckAccessAddress)
01223       insertShadowCheck(I.getPointerOperand(), &I);
01224 
01225     if (I.isAtomic())
01226       I.setOrdering(addAcquireOrdering(I.getOrdering()));
01227 
01228     if (MS.TrackOrigins) {
01229       if (PropagateShadow) {
01230         unsigned Alignment = I.getAlignment();
01231         unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
01232         setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
01233                                             OriginAlignment));
01234       } else {
01235         setOrigin(&I, getCleanOrigin());
01236       }
01237     }
01238   }
01239 
01240   /// \brief Instrument StoreInst
01241   ///
01242   /// Stores the corresponding shadow and (optionally) origin.
01243   /// Optionally, checks that the store address is fully defined.
01244   void visitStoreInst(StoreInst &I) {
01245     StoreList.push_back(&I);
01246   }
01247 
01248   void handleCASOrRMW(Instruction &I) {
01249     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
01250 
01251     IRBuilder<> IRB(&I);
01252     Value *Addr = I.getOperand(0);
01253     Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
01254 
01255     if (ClCheckAccessAddress)
01256       insertShadowCheck(Addr, &I);
01257 
01258     // Only test the conditional argument of cmpxchg instruction.
01259     // The other argument can potentially be uninitialized, but we can not
01260     // detect this situation reliably without possible false positives.
01261     if (isa<AtomicCmpXchgInst>(I))
01262       insertShadowCheck(I.getOperand(1), &I);
01263 
01264     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
01265 
01266     setShadow(&I, getCleanShadow(&I));
01267     setOrigin(&I, getCleanOrigin());
01268   }
01269 
01270   void visitAtomicRMWInst(AtomicRMWInst &I) {
01271     handleCASOrRMW(I);
01272     I.setOrdering(addReleaseOrdering(I.getOrdering()));
01273   }
01274 
01275   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
01276     handleCASOrRMW(I);
01277     I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
01278   }
01279 
01280   // Vector manipulation.
01281   void visitExtractElementInst(ExtractElementInst &I) {
01282     insertShadowCheck(I.getOperand(1), &I);
01283     IRBuilder<> IRB(&I);
01284     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
01285               "_msprop"));
01286     setOrigin(&I, getOrigin(&I, 0));
01287   }
01288 
01289   void visitInsertElementInst(InsertElementInst &I) {
01290     insertShadowCheck(I.getOperand(2), &I);
01291     IRBuilder<> IRB(&I);
01292     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
01293               I.getOperand(2), "_msprop"));
01294     setOriginForNaryOp(I);
01295   }
01296 
01297   void visitShuffleVectorInst(ShuffleVectorInst &I) {
01298     insertShadowCheck(I.getOperand(2), &I);
01299     IRBuilder<> IRB(&I);
01300     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
01301               I.getOperand(2), "_msprop"));
01302     setOriginForNaryOp(I);
01303   }
01304 
01305   // Casts.
01306   void visitSExtInst(SExtInst &I) {
01307     IRBuilder<> IRB(&I);
01308     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
01309     setOrigin(&I, getOrigin(&I, 0));
01310   }
01311 
01312   void visitZExtInst(ZExtInst &I) {
01313     IRBuilder<> IRB(&I);
01314     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
01315     setOrigin(&I, getOrigin(&I, 0));
01316   }
01317 
01318   void visitTruncInst(TruncInst &I) {
01319     IRBuilder<> IRB(&I);
01320     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
01321     setOrigin(&I, getOrigin(&I, 0));
01322   }
01323 
01324   void visitBitCastInst(BitCastInst &I) {
01325     IRBuilder<> IRB(&I);
01326     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
01327     setOrigin(&I, getOrigin(&I, 0));
01328   }
01329 
01330   void visitPtrToIntInst(PtrToIntInst &I) {
01331     IRBuilder<> IRB(&I);
01332     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
01333              "_msprop_ptrtoint"));
01334     setOrigin(&I, getOrigin(&I, 0));
01335   }
01336 
01337   void visitIntToPtrInst(IntToPtrInst &I) {
01338     IRBuilder<> IRB(&I);
01339     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
01340              "_msprop_inttoptr"));
01341     setOrigin(&I, getOrigin(&I, 0));
01342   }
01343 
01344   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
01345   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
01346   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
01347   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
01348   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
01349   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
01350 
01351   /// \brief Propagate shadow for bitwise AND.
01352   ///
01353   /// This code is exact, i.e. if, for example, a bit in the left argument
01354   /// is defined and 0, then neither the value not definedness of the
01355   /// corresponding bit in B don't affect the resulting shadow.
01356   void visitAnd(BinaryOperator &I) {
01357     IRBuilder<> IRB(&I);
01358     //  "And" of 0 and a poisoned value results in unpoisoned value.
01359     //  1&1 => 1;     0&1 => 0;     p&1 => p;
01360     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
01361     //  1&p => p;     0&p => 0;     p&p => p;
01362     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
01363     Value *S1 = getShadow(&I, 0);
01364     Value *S2 = getShadow(&I, 1);
01365     Value *V1 = I.getOperand(0);
01366     Value *V2 = I.getOperand(1);
01367     if (V1->getType() != S1->getType()) {
01368       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
01369       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
01370     }
01371     Value *S1S2 = IRB.CreateAnd(S1, S2);
01372     Value *V1S2 = IRB.CreateAnd(V1, S2);
01373     Value *S1V2 = IRB.CreateAnd(S1, V2);
01374     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
01375     setOriginForNaryOp(I);
01376   }
01377 
01378   void visitOr(BinaryOperator &I) {
01379     IRBuilder<> IRB(&I);
01380     //  "Or" of 1 and a poisoned value results in unpoisoned value.
01381     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
01382     //  1|0 => 1;     0|0 => 0;     p|0 => p;
01383     //  1|p => 1;     0|p => p;     p|p => p;
01384     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
01385     Value *S1 = getShadow(&I, 0);
01386     Value *S2 = getShadow(&I, 1);
01387     Value *V1 = IRB.CreateNot(I.getOperand(0));
01388     Value *V2 = IRB.CreateNot(I.getOperand(1));
01389     if (V1->getType() != S1->getType()) {
01390       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
01391       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
01392     }
01393     Value *S1S2 = IRB.CreateAnd(S1, S2);
01394     Value *V1S2 = IRB.CreateAnd(V1, S2);
01395     Value *S1V2 = IRB.CreateAnd(S1, V2);
01396     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
01397     setOriginForNaryOp(I);
01398   }
01399 
01400   /// \brief Default propagation of shadow and/or origin.
01401   ///
01402   /// This class implements the general case of shadow propagation, used in all
01403   /// cases where we don't know and/or don't care about what the operation
01404   /// actually does. It converts all input shadow values to a common type
01405   /// (extending or truncating as necessary), and bitwise OR's them.
01406   ///
01407   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
01408   /// fully initialized), and less prone to false positives.
01409   ///
01410   /// This class also implements the general case of origin propagation. For a
01411   /// Nary operation, result origin is set to the origin of an argument that is
01412   /// not entirely initialized. If there is more than one such arguments, the
01413   /// rightmost of them is picked. It does not matter which one is picked if all
01414   /// arguments are initialized.
01415   template <bool CombineShadow>
01416   class Combiner {
01417     Value *Shadow;
01418     Value *Origin;
01419     IRBuilder<> &IRB;
01420     MemorySanitizerVisitor *MSV;
01421 
01422   public:
01423     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
01424       Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
01425 
01426     /// \brief Add a pair of shadow and origin values to the mix.
01427     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
01428       if (CombineShadow) {
01429         assert(OpShadow);
01430         if (!Shadow)
01431           Shadow = OpShadow;
01432         else {
01433           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
01434           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
01435         }
01436       }
01437 
01438       if (MSV->MS.TrackOrigins) {
01439         assert(OpOrigin);
01440         if (!Origin) {
01441           Origin = OpOrigin;
01442         } else {
01443           Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
01444           // No point in adding something that might result in 0 origin value.
01445           if (!ConstOrigin || !ConstOrigin->isNullValue()) {
01446             Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
01447             Value *Cond =
01448                 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
01449             Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
01450           }
01451         }
01452       }
01453       return *this;
01454     }
01455 
01456     /// \brief Add an application value to the mix.
01457     Combiner &Add(Value *V) {
01458       Value *OpShadow = MSV->getShadow(V);
01459       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
01460       return Add(OpShadow, OpOrigin);
01461     }
01462 
01463     /// \brief Set the current combined values as the given instruction's shadow
01464     /// and origin.
01465     void Done(Instruction *I) {
01466       if (CombineShadow) {
01467         assert(Shadow);
01468         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
01469         MSV->setShadow(I, Shadow);
01470       }
01471       if (MSV->MS.TrackOrigins) {
01472         assert(Origin);
01473         MSV->setOrigin(I, Origin);
01474       }
01475     }
01476   };
01477 
01478   typedef Combiner<true> ShadowAndOriginCombiner;
01479   typedef Combiner<false> OriginCombiner;
01480 
01481   /// \brief Propagate origin for arbitrary operation.
01482   void setOriginForNaryOp(Instruction &I) {
01483     if (!MS.TrackOrigins) return;
01484     IRBuilder<> IRB(&I);
01485     OriginCombiner OC(this, IRB);
01486     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
01487       OC.Add(OI->get());
01488     OC.Done(&I);
01489   }
01490 
01491   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
01492     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
01493            "Vector of pointers is not a valid shadow type");
01494     return Ty->isVectorTy() ?
01495       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
01496       Ty->getPrimitiveSizeInBits();
01497   }
01498 
01499   /// \brief Cast between two shadow types, extending or truncating as
01500   /// necessary.
01501   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
01502                           bool Signed = false) {
01503     Type *srcTy = V->getType();
01504     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
01505       return IRB.CreateIntCast(V, dstTy, Signed);
01506     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
01507         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
01508       return IRB.CreateIntCast(V, dstTy, Signed);
01509     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
01510     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
01511     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
01512     Value *V2 =
01513       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
01514     return IRB.CreateBitCast(V2, dstTy);
01515     // TODO: handle struct types.
01516   }
01517 
01518   /// \brief Cast an application value to the type of its own shadow.
01519   Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
01520     Type *ShadowTy = getShadowTy(V);
01521     if (V->getType() == ShadowTy)
01522       return V;
01523     if (V->getType()->isPtrOrPtrVectorTy())
01524       return IRB.CreatePtrToInt(V, ShadowTy);
01525     else
01526       return IRB.CreateBitCast(V, ShadowTy);
01527   }
01528 
01529   /// \brief Propagate shadow for arbitrary operation.
01530   void handleShadowOr(Instruction &I) {
01531     IRBuilder<> IRB(&I);
01532     ShadowAndOriginCombiner SC(this, IRB);
01533     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
01534       SC.Add(OI->get());
01535     SC.Done(&I);
01536   }
01537 
01538   // \brief Handle multiplication by constant.
01539   //
01540   // Handle a special case of multiplication by constant that may have one or
01541   // more zeros in the lower bits. This makes corresponding number of lower bits
01542   // of the result zero as well. We model it by shifting the other operand
01543   // shadow left by the required number of bits. Effectively, we transform
01544   // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
01545   // We use multiplication by 2**N instead of shift to cover the case of
01546   // multiplication by 0, which may occur in some elements of a vector operand.
01547   void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
01548                            Value *OtherArg) {
01549     Constant *ShadowMul;
01550     Type *Ty = ConstArg->getType();
01551     if (Ty->isVectorTy()) {
01552       unsigned NumElements = Ty->getVectorNumElements();
01553       Type *EltTy = Ty->getSequentialElementType();
01554       SmallVector<Constant *, 16> Elements;
01555       for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
01556         ConstantInt *Elt =
01557             dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
01558         APInt V = Elt->getValue();
01559         APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
01560         Elements.push_back(ConstantInt::get(EltTy, V2));
01561       }
01562       ShadowMul = ConstantVector::get(Elements);
01563     } else {
01564       ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
01565       APInt V = Elt->getValue();
01566       APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
01567       ShadowMul = ConstantInt::get(Elt->getType(), V2);
01568     }
01569 
01570     IRBuilder<> IRB(&I);
01571     setShadow(&I,
01572               IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
01573     setOrigin(&I, getOrigin(OtherArg));
01574   }
01575 
01576   void visitMul(BinaryOperator &I) {
01577     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
01578     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
01579     if (constOp0 && !constOp1)
01580       handleMulByConstant(I, constOp0, I.getOperand(1));
01581     else if (constOp1 && !constOp0)
01582       handleMulByConstant(I, constOp1, I.getOperand(0));
01583     else
01584       handleShadowOr(I);
01585   }
01586 
01587   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
01588   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
01589   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
01590   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
01591   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
01592   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
01593 
01594   void handleDiv(Instruction &I) {
01595     IRBuilder<> IRB(&I);
01596     // Strict on the second argument.
01597     insertShadowCheck(I.getOperand(1), &I);
01598     setShadow(&I, getShadow(&I, 0));
01599     setOrigin(&I, getOrigin(&I, 0));
01600   }
01601 
01602   void visitUDiv(BinaryOperator &I) { handleDiv(I); }
01603   void visitSDiv(BinaryOperator &I) { handleDiv(I); }
01604   void visitFDiv(BinaryOperator &I) { handleDiv(I); }
01605   void visitURem(BinaryOperator &I) { handleDiv(I); }
01606   void visitSRem(BinaryOperator &I) { handleDiv(I); }
01607   void visitFRem(BinaryOperator &I) { handleDiv(I); }
01608 
01609   /// \brief Instrument == and != comparisons.
01610   ///
01611   /// Sometimes the comparison result is known even if some of the bits of the
01612   /// arguments are not.
01613   void handleEqualityComparison(ICmpInst &I) {
01614     IRBuilder<> IRB(&I);
01615     Value *A = I.getOperand(0);
01616     Value *B = I.getOperand(1);
01617     Value *Sa = getShadow(A);
01618     Value *Sb = getShadow(B);
01619 
01620     // Get rid of pointers and vectors of pointers.
01621     // For ints (and vectors of ints), types of A and Sa match,
01622     // and this is a no-op.
01623     A = IRB.CreatePointerCast(A, Sa->getType());
01624     B = IRB.CreatePointerCast(B, Sb->getType());
01625 
01626     // A == B  <==>  (C = A^B) == 0
01627     // A != B  <==>  (C = A^B) != 0
01628     // Sc = Sa | Sb
01629     Value *C = IRB.CreateXor(A, B);
01630     Value *Sc = IRB.CreateOr(Sa, Sb);
01631     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
01632     // Result is defined if one of the following is true
01633     // * there is a defined 1 bit in C
01634     // * C is fully defined
01635     // Si = !(C & ~Sc) && Sc
01636     Value *Zero = Constant::getNullValue(Sc->getType());
01637     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
01638     Value *Si =
01639       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
01640                     IRB.CreateICmpEQ(
01641                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
01642     Si->setName("_msprop_icmp");
01643     setShadow(&I, Si);
01644     setOriginForNaryOp(I);
01645   }
01646 
01647   /// \brief Build the lowest possible value of V, taking into account V's
01648   ///        uninitialized bits.
01649   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
01650                                 bool isSigned) {
01651     if (isSigned) {
01652       // Split shadow into sign bit and other bits.
01653       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
01654       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
01655       // Maximise the undefined shadow bit, minimize other undefined bits.
01656       return
01657         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
01658     } else {
01659       // Minimize undefined bits.
01660       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
01661     }
01662   }
01663 
01664   /// \brief Build the highest possible value of V, taking into account V's
01665   ///        uninitialized bits.
01666   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
01667                                 bool isSigned) {
01668     if (isSigned) {
01669       // Split shadow into sign bit and other bits.
01670       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
01671       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
01672       // Minimise the undefined shadow bit, maximise other undefined bits.
01673       return
01674         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
01675     } else {
01676       // Maximize undefined bits.
01677       return IRB.CreateOr(A, Sa);
01678     }
01679   }
01680 
01681   /// \brief Instrument relational comparisons.
01682   ///
01683   /// This function does exact shadow propagation for all relational
01684   /// comparisons of integers, pointers and vectors of those.
01685   /// FIXME: output seems suboptimal when one of the operands is a constant
01686   void handleRelationalComparisonExact(ICmpInst &I) {
01687     IRBuilder<> IRB(&I);
01688     Value *A = I.getOperand(0);
01689     Value *B = I.getOperand(1);
01690     Value *Sa = getShadow(A);
01691     Value *Sb = getShadow(B);
01692 
01693     // Get rid of pointers and vectors of pointers.
01694     // For ints (and vectors of ints), types of A and Sa match,
01695     // and this is a no-op.
01696     A = IRB.CreatePointerCast(A, Sa->getType());
01697     B = IRB.CreatePointerCast(B, Sb->getType());
01698 
01699     // Let [a0, a1] be the interval of possible values of A, taking into account
01700     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
01701     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
01702     bool IsSigned = I.isSigned();
01703     Value *S1 = IRB.CreateICmp(I.getPredicate(),
01704                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
01705                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
01706     Value *S2 = IRB.CreateICmp(I.getPredicate(),
01707                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
01708                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
01709     Value *Si = IRB.CreateXor(S1, S2);
01710     setShadow(&I, Si);
01711     setOriginForNaryOp(I);
01712   }
01713 
01714   /// \brief Instrument signed relational comparisons.
01715   ///
01716   /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
01717   /// propagating the highest bit of the shadow. Everything else is delegated
01718   /// to handleShadowOr().
01719   void handleSignedRelationalComparison(ICmpInst &I) {
01720     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
01721     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
01722     Value* op = nullptr;
01723     CmpInst::Predicate pre = I.getPredicate();
01724     if (constOp0 && constOp0->isNullValue() &&
01725         (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
01726       op = I.getOperand(1);
01727     } else if (constOp1 && constOp1->isNullValue() &&
01728                (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
01729       op = I.getOperand(0);
01730     }
01731     if (op) {
01732       IRBuilder<> IRB(&I);
01733       Value* Shadow =
01734         IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
01735       setShadow(&I, Shadow);
01736       setOrigin(&I, getOrigin(op));
01737     } else {
01738       handleShadowOr(I);
01739     }
01740   }
01741 
01742   void visitICmpInst(ICmpInst &I) {
01743     if (!ClHandleICmp) {
01744       handleShadowOr(I);
01745       return;
01746     }
01747     if (I.isEquality()) {
01748       handleEqualityComparison(I);
01749       return;
01750     }
01751 
01752     assert(I.isRelational());
01753     if (ClHandleICmpExact) {
01754       handleRelationalComparisonExact(I);
01755       return;
01756     }
01757     if (I.isSigned()) {
01758       handleSignedRelationalComparison(I);
01759       return;
01760     }
01761 
01762     assert(I.isUnsigned());
01763     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
01764       handleRelationalComparisonExact(I);
01765       return;
01766     }
01767 
01768     handleShadowOr(I);
01769   }
01770 
01771   void visitFCmpInst(FCmpInst &I) {
01772     handleShadowOr(I);
01773   }
01774 
01775   void handleShift(BinaryOperator &I) {
01776     IRBuilder<> IRB(&I);
01777     // If any of the S2 bits are poisoned, the whole thing is poisoned.
01778     // Otherwise perform the same shift on S1.
01779     Value *S1 = getShadow(&I, 0);
01780     Value *S2 = getShadow(&I, 1);
01781     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
01782                                    S2->getType());
01783     Value *V2 = I.getOperand(1);
01784     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
01785     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
01786     setOriginForNaryOp(I);
01787   }
01788 
01789   void visitShl(BinaryOperator &I) { handleShift(I); }
01790   void visitAShr(BinaryOperator &I) { handleShift(I); }
01791   void visitLShr(BinaryOperator &I) { handleShift(I); }
01792 
01793   /// \brief Instrument llvm.memmove
01794   ///
01795   /// At this point we don't know if llvm.memmove will be inlined or not.
01796   /// If we don't instrument it and it gets inlined,
01797   /// our interceptor will not kick in and we will lose the memmove.
01798   /// If we instrument the call here, but it does not get inlined,
01799   /// we will memove the shadow twice: which is bad in case
01800   /// of overlapping regions. So, we simply lower the intrinsic to a call.
01801   ///
01802   /// Similar situation exists for memcpy and memset.
01803   void visitMemMoveInst(MemMoveInst &I) {
01804     IRBuilder<> IRB(&I);
01805     IRB.CreateCall(
01806         MS.MemmoveFn,
01807         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
01808          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
01809          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
01810     I.eraseFromParent();
01811   }
01812 
01813   // Similar to memmove: avoid copying shadow twice.
01814   // This is somewhat unfortunate as it may slowdown small constant memcpys.
01815   // FIXME: consider doing manual inline for small constant sizes and proper
01816   // alignment.
01817   void visitMemCpyInst(MemCpyInst &I) {
01818     IRBuilder<> IRB(&I);
01819     IRB.CreateCall(
01820         MS.MemcpyFn,
01821         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
01822          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
01823          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
01824     I.eraseFromParent();
01825   }
01826 
01827   // Same as memcpy.
01828   void visitMemSetInst(MemSetInst &I) {
01829     IRBuilder<> IRB(&I);
01830     IRB.CreateCall(
01831         MS.MemsetFn,
01832         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
01833          IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
01834          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
01835     I.eraseFromParent();
01836   }
01837 
01838   void visitVAStartInst(VAStartInst &I) {
01839     VAHelper->visitVAStartInst(I);
01840   }
01841 
01842   void visitVACopyInst(VACopyInst &I) {
01843     VAHelper->visitVACopyInst(I);
01844   }
01845 
01846   enum IntrinsicKind {
01847     IK_DoesNotAccessMemory,
01848     IK_OnlyReadsMemory,
01849     IK_WritesMemory
01850   };
01851 
01852   static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
01853     const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
01854     const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
01855     const int OnlyReadsMemory = IK_OnlyReadsMemory;
01856     const int OnlyAccessesArgumentPointees = IK_WritesMemory;
01857     const int UnknownModRefBehavior = IK_WritesMemory;
01858 #define GET_INTRINSIC_MODREF_BEHAVIOR
01859 #define ModRefBehavior IntrinsicKind
01860 #include "llvm/IR/Intrinsics.gen"
01861 #undef ModRefBehavior
01862 #undef GET_INTRINSIC_MODREF_BEHAVIOR
01863   }
01864 
01865   /// \brief Handle vector store-like intrinsics.
01866   ///
01867   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
01868   /// has 1 pointer argument and 1 vector argument, returns void.
01869   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
01870     IRBuilder<> IRB(&I);
01871     Value* Addr = I.getArgOperand(0);
01872     Value *Shadow = getShadow(&I, 1);
01873     Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
01874 
01875     // We don't know the pointer alignment (could be unaligned SSE store!).
01876     // Have to assume to worst case.
01877     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
01878 
01879     if (ClCheckAccessAddress)
01880       insertShadowCheck(Addr, &I);
01881 
01882     // FIXME: use ClStoreCleanOrigin
01883     // FIXME: factor out common code from materializeStores
01884     if (MS.TrackOrigins)
01885       IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
01886     return true;
01887   }
01888 
01889   /// \brief Handle vector load-like intrinsics.
01890   ///
01891   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
01892   /// has 1 pointer argument, returns a vector.
01893   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
01894     IRBuilder<> IRB(&I);
01895     Value *Addr = I.getArgOperand(0);
01896 
01897     Type *ShadowTy = getShadowTy(&I);
01898     if (PropagateShadow) {
01899       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
01900       // We don't know the pointer alignment (could be unaligned SSE load!).
01901       // Have to assume to worst case.
01902       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
01903     } else {
01904       setShadow(&I, getCleanShadow(&I));
01905     }
01906 
01907     if (ClCheckAccessAddress)
01908       insertShadowCheck(Addr, &I);
01909 
01910     if (MS.TrackOrigins) {
01911       if (PropagateShadow)
01912         setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
01913       else
01914         setOrigin(&I, getCleanOrigin());
01915     }
01916     return true;
01917   }
01918 
01919   /// \brief Handle (SIMD arithmetic)-like intrinsics.
01920   ///
01921   /// Instrument intrinsics with any number of arguments of the same type,
01922   /// equal to the return type. The type should be simple (no aggregates or
01923   /// pointers; vectors are fine).
01924   /// Caller guarantees that this intrinsic does not access memory.
01925   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
01926     Type *RetTy = I.getType();
01927     if (!(RetTy->isIntOrIntVectorTy() ||
01928           RetTy->isFPOrFPVectorTy() ||
01929           RetTy->isX86_MMXTy()))
01930       return false;
01931 
01932     unsigned NumArgOperands = I.getNumArgOperands();
01933 
01934     for (unsigned i = 0; i < NumArgOperands; ++i) {
01935       Type *Ty = I.getArgOperand(i)->getType();
01936       if (Ty != RetTy)
01937         return false;
01938     }
01939 
01940     IRBuilder<> IRB(&I);
01941     ShadowAndOriginCombiner SC(this, IRB);
01942     for (unsigned i = 0; i < NumArgOperands; ++i)
01943       SC.Add(I.getArgOperand(i));
01944     SC.Done(&I);
01945 
01946     return true;
01947   }
01948 
01949   /// \brief Heuristically instrument unknown intrinsics.
01950   ///
01951   /// The main purpose of this code is to do something reasonable with all
01952   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
01953   /// We recognize several classes of intrinsics by their argument types and
01954   /// ModRefBehaviour and apply special intrumentation when we are reasonably
01955   /// sure that we know what the intrinsic does.
01956   ///
01957   /// We special-case intrinsics where this approach fails. See llvm.bswap
01958   /// handling as an example of that.
01959   bool handleUnknownIntrinsic(IntrinsicInst &I) {
01960     unsigned NumArgOperands = I.getNumArgOperands();
01961     if (NumArgOperands == 0)
01962       return false;
01963 
01964     Intrinsic::ID iid = I.getIntrinsicID();
01965     IntrinsicKind IK = getIntrinsicKind(iid);
01966     bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
01967     bool WritesMemory = IK == IK_WritesMemory;
01968     assert(!(OnlyReadsMemory && WritesMemory));
01969 
01970     if (NumArgOperands == 2 &&
01971         I.getArgOperand(0)->getType()->isPointerTy() &&
01972         I.getArgOperand(1)->getType()->isVectorTy() &&
01973         I.getType()->isVoidTy() &&
01974         WritesMemory) {
01975       // This looks like a vector store.
01976       return handleVectorStoreIntrinsic(I);
01977     }
01978 
01979     if (NumArgOperands == 1 &&
01980         I.getArgOperand(0)->getType()->isPointerTy() &&
01981         I.getType()->isVectorTy() &&
01982         OnlyReadsMemory) {
01983       // This looks like a vector load.
01984       return handleVectorLoadIntrinsic(I);
01985     }
01986 
01987     if (!OnlyReadsMemory && !WritesMemory)
01988       if (maybeHandleSimpleNomemIntrinsic(I))
01989         return true;
01990 
01991     // FIXME: detect and handle SSE maskstore/maskload
01992     return false;
01993   }
01994 
01995   void handleBswap(IntrinsicInst &I) {
01996     IRBuilder<> IRB(&I);
01997     Value *Op = I.getArgOperand(0);
01998     Type *OpType = Op->getType();
01999     Function *BswapFunc = Intrinsic::getDeclaration(
02000       F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
02001     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
02002     setOrigin(&I, getOrigin(Op));
02003   }
02004 
02005   // \brief Instrument vector convert instrinsic.
02006   //
02007   // This function instruments intrinsics like cvtsi2ss:
02008   // %Out = int_xxx_cvtyyy(%ConvertOp)
02009   // or
02010   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
02011   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
02012   // number \p Out elements, and (if has 2 arguments) copies the rest of the
02013   // elements from \p CopyOp.
02014   // In most cases conversion involves floating-point value which may trigger a
02015   // hardware exception when not fully initialized. For this reason we require
02016   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
02017   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
02018   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
02019   // return a fully initialized value.
02020   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
02021     IRBuilder<> IRB(&I);
02022     Value *CopyOp, *ConvertOp;
02023 
02024     switch (I.getNumArgOperands()) {
02025     case 3:
02026       assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
02027     case 2:
02028       CopyOp = I.getArgOperand(0);
02029       ConvertOp = I.getArgOperand(1);
02030       break;
02031     case 1:
02032       ConvertOp = I.getArgOperand(0);
02033       CopyOp = nullptr;
02034       break;
02035     default:
02036       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
02037     }
02038 
02039     // The first *NumUsedElements* elements of ConvertOp are converted to the
02040     // same number of output elements. The rest of the output is copied from
02041     // CopyOp, or (if not available) filled with zeroes.
02042     // Combine shadow for elements of ConvertOp that are used in this operation,
02043     // and insert a check.
02044     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
02045     // int->any conversion.
02046     Value *ConvertShadow = getShadow(ConvertOp);
02047     Value *AggShadow = nullptr;
02048     if (ConvertOp->getType()->isVectorTy()) {
02049       AggShadow = IRB.CreateExtractElement(
02050           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
02051       for (int i = 1; i < NumUsedElements; ++i) {
02052         Value *MoreShadow = IRB.CreateExtractElement(
02053             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
02054         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
02055       }
02056     } else {
02057       AggShadow = ConvertShadow;
02058     }
02059     assert(AggShadow->getType()->isIntegerTy());
02060     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
02061 
02062     // Build result shadow by zero-filling parts of CopyOp shadow that come from
02063     // ConvertOp.
02064     if (CopyOp) {
02065       assert(CopyOp->getType() == I.getType());
02066       assert(CopyOp->getType()->isVectorTy());
02067       Value *ResultShadow = getShadow(CopyOp);
02068       Type *EltTy = ResultShadow->getType()->getVectorElementType();
02069       for (int i = 0; i < NumUsedElements; ++i) {
02070         ResultShadow = IRB.CreateInsertElement(
02071             ResultShadow, ConstantInt::getNullValue(EltTy),
02072             ConstantInt::get(IRB.getInt32Ty(), i));
02073       }
02074       setShadow(&I, ResultShadow);
02075       setOrigin(&I, getOrigin(CopyOp));
02076     } else {
02077       setShadow(&I, getCleanShadow(&I));
02078       setOrigin(&I, getCleanOrigin());
02079     }
02080   }
02081 
02082   // Given a scalar or vector, extract lower 64 bits (or less), and return all
02083   // zeroes if it is zero, and all ones otherwise.
02084   Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
02085     if (S->getType()->isVectorTy())
02086       S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
02087     assert(S->getType()->getPrimitiveSizeInBits() <= 64);
02088     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
02089     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
02090   }
02091 
02092   Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
02093     Type *T = S->getType();
02094     assert(T->isVectorTy());
02095     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
02096     return IRB.CreateSExt(S2, T);
02097   }
02098 
02099   // \brief Instrument vector shift instrinsic.
02100   //
02101   // This function instruments intrinsics like int_x86_avx2_psll_w.
02102   // Intrinsic shifts %In by %ShiftSize bits.
02103   // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
02104   // size, and the rest is ignored. Behavior is defined even if shift size is
02105   // greater than register (or field) width.
02106   void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
02107     assert(I.getNumArgOperands() == 2);
02108     IRBuilder<> IRB(&I);
02109     // If any of the S2 bits are poisoned, the whole thing is poisoned.
02110     // Otherwise perform the same shift on S1.
02111     Value *S1 = getShadow(&I, 0);
02112     Value *S2 = getShadow(&I, 1);
02113     Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
02114                              : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
02115     Value *V1 = I.getOperand(0);
02116     Value *V2 = I.getOperand(1);
02117     Value *Shift = IRB.CreateCall(I.getCalledValue(),
02118                                   {IRB.CreateBitCast(S1, V1->getType()), V2});
02119     Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
02120     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
02121     setOriginForNaryOp(I);
02122   }
02123 
02124   // \brief Get an X86_MMX-sized vector type.
02125   Type *getMMXVectorTy(unsigned EltSizeInBits) {
02126     const unsigned X86_MMXSizeInBits = 64;
02127     return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
02128                            X86_MMXSizeInBits / EltSizeInBits);
02129   }
02130 
02131   // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
02132   // intrinsic.
02133   Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
02134     switch (id) {
02135       case llvm::Intrinsic::x86_sse2_packsswb_128:
02136       case llvm::Intrinsic::x86_sse2_packuswb_128:
02137         return llvm::Intrinsic::x86_sse2_packsswb_128;
02138 
02139       case llvm::Intrinsic::x86_sse2_packssdw_128:
02140       case llvm::Intrinsic::x86_sse41_packusdw:
02141         return llvm::Intrinsic::x86_sse2_packssdw_128;
02142 
02143       case llvm::Intrinsic::x86_avx2_packsswb:
02144       case llvm::Intrinsic::x86_avx2_packuswb:
02145         return llvm::Intrinsic::x86_avx2_packsswb;
02146 
02147       case llvm::Intrinsic::x86_avx2_packssdw:
02148       case llvm::Intrinsic::x86_avx2_packusdw:
02149         return llvm::Intrinsic::x86_avx2_packssdw;
02150 
02151       case llvm::Intrinsic::x86_mmx_packsswb:
02152       case llvm::Intrinsic::x86_mmx_packuswb:
02153         return llvm::Intrinsic::x86_mmx_packsswb;
02154 
02155       case llvm::Intrinsic::x86_mmx_packssdw:
02156         return llvm::Intrinsic::x86_mmx_packssdw;
02157       default:
02158         llvm_unreachable("unexpected intrinsic id");
02159     }
02160   }
02161 
02162   // \brief Instrument vector pack instrinsic.
02163   //
02164   // This function instruments intrinsics like x86_mmx_packsswb, that
02165   // packs elements of 2 input vectors into half as many bits with saturation.
02166   // Shadow is propagated with the signed variant of the same intrinsic applied
02167   // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
02168   // EltSizeInBits is used only for x86mmx arguments.
02169   void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
02170     assert(I.getNumArgOperands() == 2);
02171     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
02172     IRBuilder<> IRB(&I);
02173     Value *S1 = getShadow(&I, 0);
02174     Value *S2 = getShadow(&I, 1);
02175     assert(isX86_MMX || S1->getType()->isVectorTy());
02176 
02177     // SExt and ICmpNE below must apply to individual elements of input vectors.
02178     // In case of x86mmx arguments, cast them to appropriate vector types and
02179     // back.
02180     Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
02181     if (isX86_MMX) {
02182       S1 = IRB.CreateBitCast(S1, T);
02183       S2 = IRB.CreateBitCast(S2, T);
02184     }
02185     Value *S1_ext = IRB.CreateSExt(
02186         IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
02187     Value *S2_ext = IRB.CreateSExt(
02188         IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
02189     if (isX86_MMX) {
02190       Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
02191       S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
02192       S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
02193     }
02194 
02195     Function *ShadowFn = Intrinsic::getDeclaration(
02196         F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
02197 
02198     Value *S =
02199         IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
02200     if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
02201     setShadow(&I, S);
02202     setOriginForNaryOp(I);
02203   }
02204 
02205   // \brief Instrument sum-of-absolute-differencies intrinsic.
02206   void handleVectorSadIntrinsic(IntrinsicInst &I) {
02207     const unsigned SignificantBitsPerResultElement = 16;
02208     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
02209     Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
02210     unsigned ZeroBitsPerResultElement =
02211         ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
02212 
02213     IRBuilder<> IRB(&I);
02214     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
02215     S = IRB.CreateBitCast(S, ResTy);
02216     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
02217                        ResTy);
02218     S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
02219     S = IRB.CreateBitCast(S, getShadowTy(&I));
02220     setShadow(&I, S);
02221     setOriginForNaryOp(I);
02222   }
02223 
02224   // \brief Instrument multiply-add intrinsic.
02225   void handleVectorPmaddIntrinsic(IntrinsicInst &I,
02226                                   unsigned EltSizeInBits = 0) {
02227     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
02228     Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
02229     IRBuilder<> IRB(&I);
02230     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
02231     S = IRB.CreateBitCast(S, ResTy);
02232     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
02233                        ResTy);
02234     S = IRB.CreateBitCast(S, getShadowTy(&I));
02235     setShadow(&I, S);
02236     setOriginForNaryOp(I);
02237   }
02238 
02239   void visitIntrinsicInst(IntrinsicInst &I) {
02240     switch (I.getIntrinsicID()) {
02241     case llvm::Intrinsic::bswap:
02242       handleBswap(I);
02243       break;
02244     case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
02245     case llvm::Intrinsic::x86_avx512_cvtsd2usi:
02246     case llvm::Intrinsic::x86_avx512_cvtss2usi64:
02247     case llvm::Intrinsic::x86_avx512_cvtss2usi:
02248     case llvm::Intrinsic::x86_avx512_cvttss2usi64:
02249     case llvm::Intrinsic::x86_avx512_cvttss2usi:
02250     case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
02251     case llvm::Intrinsic::x86_avx512_cvttsd2usi:
02252     case llvm::Intrinsic::x86_avx512_cvtusi2sd:
02253     case llvm::Intrinsic::x86_avx512_cvtusi2ss:
02254     case llvm::Intrinsic::x86_avx512_cvtusi642sd:
02255     case llvm::Intrinsic::x86_avx512_cvtusi642ss:
02256     case llvm::Intrinsic::x86_sse2_cvtsd2si64:
02257     case llvm::Intrinsic::x86_sse2_cvtsd2si:
02258     case llvm::Intrinsic::x86_sse2_cvtsd2ss:
02259     case llvm::Intrinsic::x86_sse2_cvtsi2sd:
02260     case llvm::Intrinsic::x86_sse2_cvtsi642sd:
02261     case llvm::Intrinsic::x86_sse2_cvtss2sd:
02262     case llvm::Intrinsic::x86_sse2_cvttsd2si64:
02263     case llvm::Intrinsic::x86_sse2_cvttsd2si:
02264     case llvm::Intrinsic::x86_sse_cvtsi2ss:
02265     case llvm::Intrinsic::x86_sse_cvtsi642ss:
02266     case llvm::Intrinsic::x86_sse_cvtss2si64:
02267     case llvm::Intrinsic::x86_sse_cvtss2si:
02268     case llvm::Intrinsic::x86_sse_cvttss2si64:
02269     case llvm::Intrinsic::x86_sse_cvttss2si:
02270       handleVectorConvertIntrinsic(I, 1);
02271       break;
02272     case llvm::Intrinsic::x86_sse2_cvtdq2pd:
02273     case llvm::Intrinsic::x86_sse2_cvtps2pd:
02274     case llvm::Intrinsic::x86_sse_cvtps2pi:
02275     case llvm::Intrinsic::x86_sse_cvttps2pi:
02276       handleVectorConvertIntrinsic(I, 2);
02277       break;
02278     case llvm::Intrinsic::x86_avx2_psll_w:
02279     case llvm::Intrinsic::x86_avx2_psll_d:
02280     case llvm::Intrinsic::x86_avx2_psll_q:
02281     case llvm::Intrinsic::x86_avx2_pslli_w:
02282     case llvm::Intrinsic::x86_avx2_pslli_d:
02283     case llvm::Intrinsic::x86_avx2_pslli_q:
02284     case llvm::Intrinsic::x86_avx2_psrl_w:
02285     case llvm::Intrinsic::x86_avx2_psrl_d:
02286     case llvm::Intrinsic::x86_avx2_psrl_q:
02287     case llvm::Intrinsic::x86_avx2_psra_w:
02288     case llvm::Intrinsic::x86_avx2_psra_d:
02289     case llvm::Intrinsic::x86_avx2_psrli_w:
02290     case llvm::Intrinsic::x86_avx2_psrli_d:
02291     case llvm::Intrinsic::x86_avx2_psrli_q:
02292     case llvm::Intrinsic::x86_avx2_psrai_w:
02293     case llvm::Intrinsic::x86_avx2_psrai_d:
02294     case llvm::Intrinsic::x86_sse2_psll_w:
02295     case llvm::Intrinsic::x86_sse2_psll_d:
02296     case llvm::Intrinsic::x86_sse2_psll_q:
02297     case llvm::Intrinsic::x86_sse2_pslli_w:
02298     case llvm::Intrinsic::x86_sse2_pslli_d:
02299     case llvm::Intrinsic::x86_sse2_pslli_q:
02300     case llvm::Intrinsic::x86_sse2_psrl_w:
02301     case llvm::Intrinsic::x86_sse2_psrl_d:
02302     case llvm::Intrinsic::x86_sse2_psrl_q:
02303     case llvm::Intrinsic::x86_sse2_psra_w:
02304     case llvm::Intrinsic::x86_sse2_psra_d:
02305     case llvm::Intrinsic::x86_sse2_psrli_w:
02306     case llvm::Intrinsic::x86_sse2_psrli_d:
02307     case llvm::Intrinsic::x86_sse2_psrli_q:
02308     case llvm::Intrinsic::x86_sse2_psrai_w:
02309     case llvm::Intrinsic::x86_sse2_psrai_d:
02310     case llvm::Intrinsic::x86_mmx_psll_w:
02311     case llvm::Intrinsic::x86_mmx_psll_d:
02312     case llvm::Intrinsic::x86_mmx_psll_q:
02313     case llvm::Intrinsic::x86_mmx_pslli_w:
02314     case llvm::Intrinsic::x86_mmx_pslli_d:
02315     case llvm::Intrinsic::x86_mmx_pslli_q:
02316     case llvm::Intrinsic::x86_mmx_psrl_w:
02317     case llvm::Intrinsic::x86_mmx_psrl_d:
02318     case llvm::Intrinsic::x86_mmx_psrl_q:
02319     case llvm::Intrinsic::x86_mmx_psra_w:
02320     case llvm::Intrinsic::x86_mmx_psra_d:
02321     case llvm::Intrinsic::x86_mmx_psrli_w:
02322     case llvm::Intrinsic::x86_mmx_psrli_d:
02323     case llvm::Intrinsic::x86_mmx_psrli_q:
02324     case llvm::Intrinsic::x86_mmx_psrai_w:
02325     case llvm::Intrinsic::x86_mmx_psrai_d:
02326       handleVectorShiftIntrinsic(I, /* Variable */ false);
02327       break;
02328     case llvm::Intrinsic::x86_avx2_psllv_d:
02329     case llvm::Intrinsic::x86_avx2_psllv_d_256:
02330     case llvm::Intrinsic::x86_avx2_psllv_q:
02331     case llvm::Intrinsic::x86_avx2_psllv_q_256:
02332     case llvm::Intrinsic::x86_avx2_psrlv_d:
02333     case llvm::Intrinsic::x86_avx2_psrlv_d_256:
02334     case llvm::Intrinsic::x86_avx2_psrlv_q:
02335     case llvm::Intrinsic::x86_avx2_psrlv_q_256:
02336     case llvm::Intrinsic::x86_avx2_psrav_d:
02337     case llvm::Intrinsic::x86_avx2_psrav_d_256:
02338       handleVectorShiftIntrinsic(I, /* Variable */ true);
02339       break;
02340 
02341     case llvm::Intrinsic::x86_sse2_packsswb_128:
02342     case llvm::Intrinsic::x86_sse2_packssdw_128:
02343     case llvm::Intrinsic::x86_sse2_packuswb_128:
02344     case llvm::Intrinsic::x86_sse41_packusdw:
02345     case llvm::Intrinsic::x86_avx2_packsswb:
02346     case llvm::Intrinsic::x86_avx2_packssdw:
02347     case llvm::Intrinsic::x86_avx2_packuswb:
02348     case llvm::Intrinsic::x86_avx2_packusdw:
02349       handleVectorPackIntrinsic(I);
02350       break;
02351 
02352     case llvm::Intrinsic::x86_mmx_packsswb:
02353     case llvm::Intrinsic::x86_mmx_packuswb:
02354       handleVectorPackIntrinsic(I, 16);
02355       break;
02356 
02357     case llvm::Intrinsic::x86_mmx_packssdw:
02358       handleVectorPackIntrinsic(I, 32);
02359       break;
02360 
02361     case llvm::Intrinsic::x86_mmx_psad_bw:
02362     case llvm::Intrinsic::x86_sse2_psad_bw:
02363     case llvm::Intrinsic::x86_avx2_psad_bw:
02364       handleVectorSadIntrinsic(I);
02365       break;
02366 
02367     case llvm::Intrinsic::x86_sse2_pmadd_wd:
02368     case llvm::Intrinsic::x86_avx2_pmadd_wd:
02369     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
02370     case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
02371       handleVectorPmaddIntrinsic(I);
02372       break;
02373 
02374     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
02375       handleVectorPmaddIntrinsic(I, 8);
02376       break;
02377 
02378     case llvm::Intrinsic::x86_mmx_pmadd_wd:
02379       handleVectorPmaddIntrinsic(I, 16);
02380       break;
02381 
02382     default:
02383       if (!handleUnknownIntrinsic(I))
02384         visitInstruction(I);
02385       break;
02386     }
02387   }
02388 
02389   void visitCallSite(CallSite CS) {
02390     Instruction &I = *CS.getInstruction();
02391     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
02392     if (CS.isCall()) {
02393       CallInst *Call = cast<CallInst>(&I);
02394 
02395       // For inline asm, do the usual thing: check argument shadow and mark all
02396       // outputs as clean. Note that any side effects of the inline asm that are
02397       // not immediately visible in its constraints are not handled.
02398       if (Call->isInlineAsm()) {
02399         visitInstruction(I);
02400         return;
02401       }
02402 
02403       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
02404 
02405       // We are going to insert code that relies on the fact that the callee
02406       // will become a non-readonly function after it is instrumented by us. To
02407       // prevent this code from being optimized out, mark that function
02408       // non-readonly in advance.
02409       if (Function *Func = Call->getCalledFunction()) {
02410         // Clear out readonly/readnone attributes.
02411         AttrBuilder B;
02412         B.addAttribute(Attribute::ReadOnly)
02413           .addAttribute(Attribute::ReadNone);
02414         Func->removeAttributes(AttributeSet::FunctionIndex,
02415                                AttributeSet::get(Func->getContext(),
02416                                                  AttributeSet::FunctionIndex,
02417                                                  B));
02418       }
02419     }
02420     IRBuilder<> IRB(&I);
02421 
02422     unsigned ArgOffset = 0;
02423     DEBUG(dbgs() << "  CallSite: " << I << "\n");
02424     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
02425          ArgIt != End; ++ArgIt) {
02426       Value *A = *ArgIt;
02427       unsigned i = ArgIt - CS.arg_begin();
02428       if (!A->getType()->isSized()) {
02429         DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
02430         continue;
02431       }
02432       unsigned Size = 0;
02433       Value *Store = nullptr;
02434       // Compute the Shadow for arg even if it is ByVal, because
02435       // in that case getShadow() will copy the actual arg shadow to
02436       // __msan_param_tls.
02437       Value *ArgShadow = getShadow(A);
02438       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
02439       DEBUG(dbgs() << "  Arg#" << i << ": " << *A <<
02440             " Shadow: " << *ArgShadow << "\n");
02441       bool ArgIsInitialized = false;
02442       const DataLayout &DL = F.getParent()->getDataLayout();
02443       if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
02444         assert(A->getType()->isPointerTy() &&
02445                "ByVal argument is not a pointer!");
02446         Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
02447         if (ArgOffset + Size > kParamTLSSize) break;
02448         unsigned ParamAlignment = CS.getParamAlignment(i + 1);
02449         unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
02450         Store = IRB.CreateMemCpy(ArgShadowBase,
02451                                  getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
02452                                  Size, Alignment);
02453       } else {
02454         Size = DL.getTypeAllocSize(A->getType());
02455         if (ArgOffset + Size > kParamTLSSize) break;
02456         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
02457                                        kShadowTLSAlignment);
02458         Constant *Cst = dyn_cast<Constant>(ArgShadow);
02459         if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
02460       }
02461       if (MS.TrackOrigins && !ArgIsInitialized)
02462         IRB.CreateStore(getOrigin(A),
02463                         getOriginPtrForArgument(A, IRB, ArgOffset));
02464       (void)Store;
02465       assert(Size != 0 && Store != nullptr);
02466       DEBUG(dbgs() << "  Param:" << *Store << "\n");
02467       ArgOffset += RoundUpToAlignment(Size, 8);
02468     }
02469     DEBUG(dbgs() << "  done with call args\n");
02470 
02471     FunctionType *FT =
02472       cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
02473     if (FT->isVarArg()) {
02474       VAHelper->visitCallSite(CS, IRB);
02475     }
02476 
02477     // Now, get the shadow for the RetVal.
02478     if (!I.getType()->isSized()) return;
02479     IRBuilder<> IRBBefore(&I);
02480     // Until we have full dynamic coverage, make sure the retval shadow is 0.
02481     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
02482     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
02483     Instruction *NextInsn = nullptr;
02484     if (CS.isCall()) {
02485       NextInsn = I.getNextNode();
02486     } else {
02487       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
02488       if (!NormalDest->getSinglePredecessor()) {
02489         // FIXME: this case is tricky, so we are just conservative here.
02490         // Perhaps we need to split the edge between this BB and NormalDest,
02491         // but a naive attempt to use SplitEdge leads to a crash.
02492         setShadow(&I, getCleanShadow(&I));
02493         setOrigin(&I, getCleanOrigin());
02494         return;
02495       }
02496       NextInsn = NormalDest->getFirstInsertionPt();
02497       assert(NextInsn &&
02498              "Could not find insertion point for retval shadow load");
02499     }
02500     IRBuilder<> IRBAfter(NextInsn);
02501     Value *RetvalShadow =
02502       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
02503                                  kShadowTLSAlignment, "_msret");
02504     setShadow(&I, RetvalShadow);
02505     if (MS.TrackOrigins)
02506       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
02507   }
02508 
02509   void visitReturnInst(ReturnInst &I) {
02510     IRBuilder<> IRB(&I);
02511     Value *RetVal = I.getReturnValue();
02512     if (!RetVal) return;
02513     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
02514     if (CheckReturnValue) {
02515       insertShadowCheck(RetVal, &I);
02516       Value *Shadow = getCleanShadow(RetVal);
02517       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
02518     } else {
02519       Value *Shadow = getShadow(RetVal);
02520       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
02521       // FIXME: make it conditional if ClStoreCleanOrigin==0
02522       if (MS.TrackOrigins)
02523         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
02524     }
02525   }
02526 
02527   void visitPHINode(PHINode &I) {
02528     IRBuilder<> IRB(&I);
02529     if (!PropagateShadow) {
02530       setShadow(&I, getCleanShadow(&I));
02531       setOrigin(&I, getCleanOrigin());
02532       return;
02533     }
02534 
02535     ShadowPHINodes.push_back(&I);
02536     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
02537                                 "_msphi_s"));
02538     if (MS.TrackOrigins)
02539       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
02540                                   "_msphi_o"));
02541   }
02542 
02543   void visitAllocaInst(AllocaInst &I) {
02544     setShadow(&I, getCleanShadow(&I));
02545     setOrigin(&I, getCleanOrigin());
02546     IRBuilder<> IRB(I.getNextNode());
02547     const DataLayout &DL = F.getParent()->getDataLayout();
02548     uint64_t Size = DL.getTypeAllocSize(I.getAllocatedType());
02549     if (PoisonStack && ClPoisonStackWithCall) {
02550       IRB.CreateCall(MS.MsanPoisonStackFn,
02551                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
02552                       ConstantInt::get(MS.IntptrTy, Size)});
02553     } else {
02554       Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
02555       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
02556       IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
02557     }
02558 
02559     if (PoisonStack && MS.TrackOrigins) {
02560       SmallString<2048> StackDescriptionStorage;
02561       raw_svector_ostream StackDescription(StackDescriptionStorage);
02562       // We create a string with a description of the stack allocation and
02563       // pass it into __msan_set_alloca_origin.
02564       // It will be printed by the run-time if stack-originated UMR is found.
02565       // The first 4 bytes of the string are set to '----' and will be replaced
02566       // by __msan_va_arg_overflow_size_tls at the first call.
02567       StackDescription << "----" << I.getName() << "@" << F.getName();
02568       Value *Descr =
02569           createPrivateNonConstGlobalForString(*F.getParent(),
02570                                                StackDescription.str());
02571 
02572       IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
02573                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
02574                       ConstantInt::get(MS.IntptrTy, Size),
02575                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
02576                       IRB.CreatePointerCast(&F, MS.IntptrTy)});
02577     }
02578   }
02579 
02580   void visitSelectInst(SelectInst& I) {
02581     IRBuilder<> IRB(&I);
02582     // a = select b, c, d
02583     Value *B = I.getCondition();
02584     Value *C = I.getTrueValue();
02585     Value *D = I.getFalseValue();
02586     Value *Sb = getShadow(B);
02587     Value *Sc = getShadow(C);
02588     Value *Sd = getShadow(D);
02589 
02590     // Result shadow if condition shadow is 0.
02591     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
02592     Value *Sa1;
02593     if (I.getType()->isAggregateType()) {
02594       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
02595       // an extra "select". This results in much more compact IR.
02596       // Sa = select Sb, poisoned, (select b, Sc, Sd)
02597       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
02598     } else {
02599       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
02600       // If Sb (condition is poisoned), look for bits in c and d that are equal
02601       // and both unpoisoned.
02602       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
02603 
02604       // Cast arguments to shadow-compatible type.
02605       C = CreateAppToShadowCast(IRB, C);
02606       D = CreateAppToShadowCast(IRB, D);
02607 
02608       // Result shadow if condition shadow is 1.
02609       Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
02610     }
02611     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
02612     setShadow(&I, Sa);
02613     if (MS.TrackOrigins) {
02614       // Origins are always i32, so any vector conditions must be flattened.
02615       // FIXME: consider tracking vector origins for app vectors?
02616       if (B->getType()->isVectorTy()) {
02617         Type *FlatTy = getShadowTyNoVec(B->getType());
02618         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
02619                                 ConstantInt::getNullValue(FlatTy));
02620         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
02621                                       ConstantInt::getNullValue(FlatTy));
02622       }
02623       // a = select b, c, d
02624       // Oa = Sb ? Ob : (b ? Oc : Od)
02625       setOrigin(
02626           &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
02627                                IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
02628                                                 getOrigin(I.getFalseValue()))));
02629     }
02630   }
02631 
02632   void visitLandingPadInst(LandingPadInst &I) {
02633     // Do nothing.
02634     // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
02635     setShadow(&I, getCleanShadow(&I));
02636     setOrigin(&I, getCleanOrigin());
02637   }
02638 
02639   void visitGetElementPtrInst(GetElementPtrInst &I) {
02640     handleShadowOr(I);
02641   }
02642 
02643   void visitExtractValueInst(ExtractValueInst &I) {
02644     IRBuilder<> IRB(&I);
02645     Value *Agg = I.getAggregateOperand();
02646     DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
02647     Value *AggShadow = getShadow(Agg);
02648     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
02649     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
02650     DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
02651     setShadow(&I, ResShadow);
02652     setOriginForNaryOp(I);
02653   }
02654 
02655   void visitInsertValueInst(InsertValueInst &I) {
02656     IRBuilder<> IRB(&I);
02657     DEBUG(dbgs() << "InsertValue:  " << I << "\n");
02658     Value *AggShadow = getShadow(I.getAggregateOperand());
02659     Value *InsShadow = getShadow(I.getInsertedValueOperand());
02660     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
02661     DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
02662     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
02663     DEBUG(dbgs() << "   Res:        " << *Res << "\n");
02664     setShadow(&I, Res);
02665     setOriginForNaryOp(I);
02666   }
02667 
02668   void dumpInst(Instruction &I) {
02669     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
02670       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
02671     } else {
02672       errs() << "ZZZ " << I.getOpcodeName() << "\n";
02673     }
02674     errs() << "QQQ " << I << "\n";
02675   }
02676 
02677   void visitResumeInst(ResumeInst &I) {
02678     DEBUG(dbgs() << "Resume: " << I << "\n");
02679     // Nothing to do here.
02680   }
02681 
02682   void visitInstruction(Instruction &I) {
02683     // Everything else: stop propagating and check for poisoned shadow.
02684     if (ClDumpStrictInstructions)
02685       dumpInst(I);
02686     DEBUG(dbgs() << "DEFAULT: " << I << "\n");
02687     for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
02688       insertShadowCheck(I.getOperand(i), &I);
02689     setShadow(&I, getCleanShadow(&I));
02690     setOrigin(&I, getCleanOrigin());
02691   }
02692 };
02693 
02694 /// \brief AMD64-specific implementation of VarArgHelper.
02695 struct VarArgAMD64Helper : public VarArgHelper {
02696   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
02697   // See a comment in visitCallSite for more details.
02698   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
02699   static const unsigned AMD64FpEndOffset = 176;
02700 
02701   Function &F;
02702   MemorySanitizer &MS;
02703   MemorySanitizerVisitor &MSV;
02704   Value *VAArgTLSCopy;
02705   Value *VAArgOverflowSize;
02706 
02707   SmallVector<CallInst*, 16> VAStartInstrumentationList;
02708 
02709   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
02710                     MemorySanitizerVisitor &MSV)
02711     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
02712       VAArgOverflowSize(nullptr) {}
02713 
02714   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
02715 
02716   ArgKind classifyArgument(Value* arg) {
02717     // A very rough approximation of X86_64 argument classification rules.
02718     Type *T = arg->getType();
02719     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
02720       return AK_FloatingPoint;
02721     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
02722       return AK_GeneralPurpose;
02723     if (T->isPointerTy())
02724       return AK_GeneralPurpose;
02725     return AK_Memory;
02726   }
02727 
02728   // For VarArg functions, store the argument shadow in an ABI-specific format
02729   // that corresponds to va_list layout.
02730   // We do this because Clang lowers va_arg in the frontend, and this pass
02731   // only sees the low level code that deals with va_list internals.
02732   // A much easier alternative (provided that Clang emits va_arg instructions)
02733   // would have been to associate each live instance of va_list with a copy of
02734   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
02735   // order.
02736   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
02737     unsigned GpOffset = 0;
02738     unsigned FpOffset = AMD64GpEndOffset;
02739     unsigned OverflowOffset = AMD64FpEndOffset;
02740     const DataLayout &DL = F.getParent()->getDataLayout();
02741     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
02742          ArgIt != End; ++ArgIt) {
02743       Value *A = *ArgIt;
02744       unsigned ArgNo = CS.getArgumentNo(ArgIt);
02745       bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
02746       if (IsByVal) {
02747         // ByVal arguments always go to the overflow area.
02748         assert(A->getType()->isPointerTy());
02749         Type *RealTy = A->getType()->getPointerElementType();
02750         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
02751         Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
02752         OverflowOffset += RoundUpToAlignment(ArgSize, 8);
02753         IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
02754                          ArgSize, kShadowTLSAlignment);
02755       } else {
02756         ArgKind AK = classifyArgument(A);
02757         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
02758           AK = AK_Memory;
02759         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
02760           AK = AK_Memory;
02761         Value *Base;
02762         switch (AK) {
02763           case AK_GeneralPurpose:
02764             Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
02765             GpOffset += 8;
02766             break;
02767           case AK_FloatingPoint:
02768             Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
02769             FpOffset += 16;
02770             break;
02771           case AK_Memory:
02772             uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
02773             Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
02774             OverflowOffset += RoundUpToAlignment(ArgSize, 8);
02775         }
02776         IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
02777       }
02778     }
02779     Constant *OverflowSize =
02780       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
02781     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
02782   }
02783 
02784   /// \brief Compute the shadow address for a given va_arg.
02785   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
02786                                    int ArgOffset) {
02787     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
02788     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
02789     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
02790                               "_msarg");
02791   }
02792 
02793   void visitVAStartInst(VAStartInst &I) override {
02794     IRBuilder<> IRB(&I);
02795     VAStartInstrumentationList.push_back(&I);
02796     Value *VAListTag = I.getArgOperand(0);
02797     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
02798 
02799     // Unpoison the whole __va_list_tag.
02800     // FIXME: magic ABI constants.
02801     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
02802                      /* size */24, /* alignment */8, false);
02803   }
02804 
02805   void visitVACopyInst(VACopyInst &I) override {
02806     IRBuilder<> IRB(&I);
02807     Value *VAListTag = I.getArgOperand(0);
02808     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
02809 
02810     // Unpoison the whole __va_list_tag.
02811     // FIXME: magic ABI constants.
02812     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
02813                      /* size */24, /* alignment */8, false);
02814   }
02815 
02816   void finalizeInstrumentation() override {
02817     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
02818            "finalizeInstrumentation called twice");
02819     if (!VAStartInstrumentationList.empty()) {
02820       // If there is a va_start in this function, make a backup copy of
02821       // va_arg_tls somewhere in the function entry block.
02822       IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
02823       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
02824       Value *CopySize =
02825         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
02826                       VAArgOverflowSize);
02827       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
02828       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
02829     }
02830 
02831     // Instrument va_start.
02832     // Copy va_list shadow from the backup copy of the TLS contents.
02833     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
02834       CallInst *OrigInst = VAStartInstrumentationList[i];
02835       IRBuilder<> IRB(OrigInst->getNextNode());
02836       Value *VAListTag = OrigInst->getArgOperand(0);
02837 
02838       Value *RegSaveAreaPtrPtr =
02839         IRB.CreateIntToPtr(
02840           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
02841                         ConstantInt::get(MS.IntptrTy, 16)),
02842           Type::getInt64PtrTy(*MS.C));
02843       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
02844       Value *RegSaveAreaShadowPtr =
02845         MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
02846       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
02847                        AMD64FpEndOffset, 16);
02848 
02849       Value *OverflowArgAreaPtrPtr =
02850         IRB.CreateIntToPtr(
02851           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
02852                         ConstantInt::get(MS.IntptrTy, 8)),
02853           Type::getInt64PtrTy(*MS.C));
02854       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
02855       Value *OverflowArgAreaShadowPtr =
02856         MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
02857       Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
02858                                              AMD64FpEndOffset);
02859       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
02860     }
02861   }
02862 };
02863 
02864 /// \brief MIPS64-specific implementation of VarArgHelper.
02865 struct VarArgMIPS64Helper : public VarArgHelper {
02866   Function &F;
02867   MemorySanitizer &MS;
02868   MemorySanitizerVisitor &MSV;
02869   Value *VAArgTLSCopy;
02870   Value *VAArgSize;
02871 
02872   SmallVector<CallInst*, 16> VAStartInstrumentationList;
02873 
02874   VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
02875                     MemorySanitizerVisitor &MSV)
02876     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
02877       VAArgSize(nullptr) {}
02878 
02879   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
02880     unsigned VAArgOffset = 0;
02881     const DataLayout &DL = F.getParent()->getDataLayout();
02882     for (CallSite::arg_iterator ArgIt = CS.arg_begin() + 1, End = CS.arg_end();
02883          ArgIt != End; ++ArgIt) {
02884       Value *A = *ArgIt;
02885       Value *Base;
02886       uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
02887 #if defined(__MIPSEB__) || defined(MIPSEB)
02888       // Adjusting the shadow for argument with size < 8 to match the placement
02889       // of bits in big endian system
02890       if (ArgSize < 8)
02891         VAArgOffset += (8 - ArgSize);
02892 #endif
02893       Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
02894       VAArgOffset += ArgSize;
02895       VAArgOffset = RoundUpToAlignment(VAArgOffset, 8);
02896       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
02897     }
02898 
02899     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
02900     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
02901     // a new class member i.e. it is the total size of all VarArgs.
02902     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
02903   }
02904 
02905   /// \brief Compute the shadow address for a given va_arg.
02906   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
02907                                    int ArgOffset) {
02908     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
02909     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
02910     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
02911                               "_msarg");
02912   }
02913 
02914   void visitVAStartInst(VAStartInst &I) override {
02915     IRBuilder<> IRB(&I);
02916     VAStartInstrumentationList.push_back(&I);
02917     Value *VAListTag = I.getArgOperand(0);
02918     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
02919     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
02920                      /* size */8, /* alignment */8, false);
02921   }
02922 
02923   void visitVACopyInst(VACopyInst &I) override {
02924     IRBuilder<> IRB(&I);
02925     Value *VAListTag = I.getArgOperand(0);
02926     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
02927     // Unpoison the whole __va_list_tag.
02928     // FIXME: magic ABI constants.
02929     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
02930                      /* size */8, /* alignment */8, false);
02931   }
02932 
02933   void finalizeInstrumentation() override {
02934     assert(!VAArgSize && !VAArgTLSCopy &&
02935            "finalizeInstrumentation called twice");
02936     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
02937     VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
02938     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
02939                                     VAArgSize);
02940 
02941     if (!VAStartInstrumentationList.empty()) {
02942       // If there is a va_start in this function, make a backup copy of
02943       // va_arg_tls somewhere in the function entry block.
02944       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
02945       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
02946     }
02947 
02948     // Instrument va_start.
02949     // Copy va_list shadow from the backup copy of the TLS contents.
02950     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
02951       CallInst *OrigInst = VAStartInstrumentationList[i];
02952       IRBuilder<> IRB(OrigInst->getNextNode());
02953       Value *VAListTag = OrigInst->getArgOperand(0);
02954       Value *RegSaveAreaPtrPtr =
02955         IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
02956                         Type::getInt64PtrTy(*MS.C));
02957       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
02958       Value *RegSaveAreaShadowPtr =
02959       MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
02960       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
02961     }
02962   }
02963 };
02964 
02965 /// \brief A no-op implementation of VarArgHelper.
02966 struct VarArgNoOpHelper : public VarArgHelper {
02967   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
02968                    MemorySanitizerVisitor &MSV) {}
02969 
02970   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
02971 
02972   void visitVAStartInst(VAStartInst &I) override {}
02973 
02974   void visitVACopyInst(VACopyInst &I) override {}
02975 
02976   void finalizeInstrumentation() override {}
02977 };
02978 
02979 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
02980                                  MemorySanitizerVisitor &Visitor) {
02981   // VarArg handling is only implemented on AMD64. False positives are possible
02982   // on other platforms.
02983   llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
02984   if (TargetTriple.getArch() == llvm::Triple::x86_64)
02985     return new VarArgAMD64Helper(Func, Msan, Visitor);
02986   else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
02987            TargetTriple.getArch() == llvm::Triple::mips64el)
02988     return new VarArgMIPS64Helper(Func, Msan, Visitor);
02989   else
02990     return new VarArgNoOpHelper(Func, Msan, Visitor);
02991 }
02992 
02993 }  // namespace
02994 
02995 bool MemorySanitizer::runOnFunction(Function &F) {
02996   if (&F == MsanCtorFunction)
02997     return false;
02998   MemorySanitizerVisitor Visitor(F, *this);
02999 
03000   // Clear out readonly/readnone attributes.
03001   AttrBuilder B;
03002   B.addAttribute(Attribute::ReadOnly)
03003     .addAttribute(Attribute::ReadNone);
03004   F.removeAttributes(AttributeSet::FunctionIndex,
03005                      AttributeSet::get(F.getContext(),
03006                                        AttributeSet::FunctionIndex, B));
03007 
03008   return Visitor.runOnFunction();
03009 }