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