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