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