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