LLVM API Documentation

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