Implement depth_first and inverse_depth_first range factory functions.
[oota-llvm.git] / lib / Transforms / Instrumentation / MemorySanitizer.cpp
1 //===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file is a part of MemorySanitizer, a detector of uninitialized
11 /// reads.
12 ///
13 /// Status: early prototype.
14 ///
15 /// The algorithm of the tool is similar to Memcheck
16 /// (http://goo.gl/QKbem). We associate a few shadow bits with every
17 /// byte of the application memory, poison the shadow of the malloc-ed
18 /// or alloca-ed memory, load the shadow bits on every memory read,
19 /// propagate the shadow bits through some of the arithmetic
20 /// instruction (including MOV), store the shadow bits on every memory
21 /// write, report a bug on some other instructions (e.g. JMP) if the
22 /// associated shadow is poisoned.
23 ///
24 /// But there are differences too. The first and the major one:
25 /// compiler instrumentation instead of binary instrumentation. This
26 /// gives us much better register allocation, possible compiler
27 /// optimizations and a fast start-up. But this brings the major issue
28 /// as well: msan needs to see all program events, including system
29 /// calls and reads/writes in system libraries, so we either need to
30 /// compile *everything* with msan or use a binary translation
31 /// component (e.g. DynamoRIO) to instrument pre-built libraries.
32 /// Another difference from Memcheck is that we use 8 shadow bits per
33 /// byte of application memory and use a direct shadow mapping. This
34 /// greatly simplifies the instrumentation code and avoids races on
35 /// shadow updates (Memcheck is single-threaded so races are not a
36 /// concern there. Memcheck uses 2 shadow bits per byte with a slow
37 /// path storage that uses 8 bits per byte).
38 ///
39 /// The default value of shadow is 0, which means "clean" (not poisoned).
40 ///
41 /// Every module initializer should call __msan_init to ensure that the
42 /// shadow memory is ready. On error, __msan_warning is called. Since
43 /// parameters and return values may be passed via registers, we have a
44 /// specialized thread-local shadow for return values
45 /// (__msan_retval_tls) and parameters (__msan_param_tls).
46 ///
47 ///                           Origin tracking.
48 ///
49 /// MemorySanitizer can track origins (allocation points) of all uninitialized
50 /// values. This behavior is controlled with a flag (msan-track-origins) and is
51 /// disabled by default.
52 ///
53 /// Origins are 4-byte values created and interpreted by the runtime library.
54 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
55 /// of application memory. Propagation of origins is basically a bunch of
56 /// "select" instructions that pick the origin of a dirty argument, if an
57 /// instruction has one.
58 ///
59 /// Every 4 aligned, consecutive bytes of application memory have one origin
60 /// value associated with them. If these bytes contain uninitialized data
61 /// coming from 2 different allocations, the last store wins. Because of this,
62 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
63 /// practice.
64 ///
65 /// Origins are meaningless for fully initialized values, so MemorySanitizer
66 /// avoids storing origin to memory when a fully initialized value is stored.
67 /// This way it avoids needless overwritting origin of the 4-byte region on
68 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
69 ///
70 ///                            Atomic handling.
71 ///
72 /// Ideally, every atomic store of application value should update the
73 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
74 /// of two disjoint locations can not be done without severe slowdown.
75 ///
76 /// Therefore, we implement an approximation that may err on the safe side.
77 /// In this implementation, every atomically accessed location in the program
78 /// may only change from (partially) uninitialized to fully initialized, but
79 /// not the other way around. We load the shadow _after_ the application load,
80 /// and we store the shadow _before_ the app store. Also, we always store clean
81 /// shadow (if the application store is atomic). This way, if the store-load
82 /// pair constitutes a happens-before arc, shadow store and load are correctly
83 /// ordered such that the load will get either the value that was stored, or
84 /// some later value (which is always clean).
85 ///
86 /// This does not work very well with Compare-And-Swap (CAS) and
87 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
88 /// must store the new shadow before the app operation, and load the shadow
89 /// after the app operation. Computers don't work this way. Current
90 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
91 /// value. It implements the store part as a simple atomic store by storing a
92 /// clean shadow.
93
94 //===----------------------------------------------------------------------===//
95
96 #define DEBUG_TYPE "msan"
97
98 #include "llvm/Transforms/Instrumentation.h"
99 #include "llvm/ADT/DepthFirstIterator.h"
100 #include "llvm/ADT/SmallString.h"
101 #include "llvm/ADT/SmallVector.h"
102 #include "llvm/ADT/Triple.h"
103 #include "llvm/IR/DataLayout.h"
104 #include "llvm/IR/Function.h"
105 #include "llvm/IR/IRBuilder.h"
106 #include "llvm/IR/InlineAsm.h"
107 #include "llvm/IR/InstVisitor.h"
108 #include "llvm/IR/IntrinsicInst.h"
109 #include "llvm/IR/LLVMContext.h"
110 #include "llvm/IR/MDBuilder.h"
111 #include "llvm/IR/Module.h"
112 #include "llvm/IR/Type.h"
113 #include "llvm/IR/ValueMap.h"
114 #include "llvm/Support/CommandLine.h"
115 #include "llvm/Support/Compiler.h"
116 #include "llvm/Support/Debug.h"
117 #include "llvm/Support/raw_ostream.h"
118 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
119 #include "llvm/Transforms/Utils/Local.h"
120 #include "llvm/Transforms/Utils/ModuleUtils.h"
121 #include "llvm/Transforms/Utils/SpecialCaseList.h"
122
123 using namespace llvm;
124
125 static const uint64_t kShadowMask32 = 1ULL << 31;
126 static const uint64_t kShadowMask64 = 1ULL << 46;
127 static const uint64_t kOriginOffset32 = 1ULL << 30;
128 static const uint64_t kOriginOffset64 = 1ULL << 45;
129 static const unsigned kMinOriginAlignment = 4;
130 static const unsigned kShadowTLSAlignment = 8;
131
132 /// \brief Track origins of uninitialized values.
133 ///
134 /// Adds a section to MemorySanitizer report that points to the allocation
135 /// (stack or heap) the uninitialized bits came from originally.
136 static cl::opt<int> ClTrackOrigins("msan-track-origins",
137        cl::desc("Track origins (allocation sites) of poisoned memory"),
138        cl::Hidden, cl::init(0));
139 static cl::opt<bool> ClKeepGoing("msan-keep-going",
140        cl::desc("keep going after reporting a UMR"),
141        cl::Hidden, cl::init(false));
142 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
143        cl::desc("poison uninitialized stack variables"),
144        cl::Hidden, cl::init(true));
145 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
146        cl::desc("poison uninitialized stack variables with a call"),
147        cl::Hidden, cl::init(false));
148 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
149        cl::desc("poison uninitialized stack variables with the given patter"),
150        cl::Hidden, cl::init(0xff));
151 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
152        cl::desc("poison undef temps"),
153        cl::Hidden, cl::init(true));
154
155 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
156        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
157        cl::Hidden, cl::init(true));
158
159 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
160        cl::desc("exact handling of relational integer ICmp"),
161        cl::Hidden, cl::init(false));
162
163 // This flag controls whether we check the shadow of the address
164 // operand of load or store. Such bugs are very rare, since load from
165 // a garbage address typically results in SEGV, but still happen
166 // (e.g. only lower bits of address are garbage, or the access happens
167 // early at program startup where malloc-ed memory is more likely to
168 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
169 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
170        cl::desc("report accesses through a pointer which has poisoned shadow"),
171        cl::Hidden, cl::init(true));
172
173 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
174        cl::desc("print out instructions with default strict semantics"),
175        cl::Hidden, cl::init(false));
176
177 static cl::opt<std::string>  ClBlacklistFile("msan-blacklist",
178        cl::desc("File containing the list of functions where MemorySanitizer "
179                 "should not report bugs"), cl::Hidden);
180
181 // Experimental. Wraps all indirect calls in the instrumented code with
182 // a call to the given function. This is needed to assist the dynamic
183 // helper tool (MSanDR) to regain control on transition between instrumented and
184 // non-instrumented code.
185 static cl::opt<std::string> ClWrapIndirectCalls("msan-wrap-indirect-calls",
186        cl::desc("Wrap indirect calls with a given function"),
187        cl::Hidden);
188
189 static cl::opt<bool> ClWrapIndirectCallsFast("msan-wrap-indirect-calls-fast",
190        cl::desc("Do not wrap indirect calls with target in the same module"),
191        cl::Hidden, cl::init(true));
192
193 namespace {
194
195 /// \brief An instrumentation pass implementing detection of uninitialized
196 /// reads.
197 ///
198 /// MemorySanitizer: instrument the code in module to find
199 /// uninitialized reads.
200 class MemorySanitizer : public FunctionPass {
201  public:
202   MemorySanitizer(int TrackOrigins = 0,
203                   StringRef BlacklistFile = StringRef())
204       : FunctionPass(ID),
205         TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
206         DL(0),
207         WarningFn(0),
208         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile : BlacklistFile),
209         WrapIndirectCalls(!ClWrapIndirectCalls.empty()) {}
210   const char *getPassName() const override { return "MemorySanitizer"; }
211   bool runOnFunction(Function &F) override;
212   bool doInitialization(Module &M) override;
213   static char ID;  // Pass identification, replacement for typeid.
214
215  private:
216   void initializeCallbacks(Module &M);
217
218   /// \brief Track origins (allocation points) of uninitialized values.
219   int TrackOrigins;
220
221   const DataLayout *DL;
222   LLVMContext *C;
223   Type *IntptrTy;
224   Type *OriginTy;
225   /// \brief Thread-local shadow storage for function parameters.
226   GlobalVariable *ParamTLS;
227   /// \brief Thread-local origin storage for function parameters.
228   GlobalVariable *ParamOriginTLS;
229   /// \brief Thread-local shadow storage for function return value.
230   GlobalVariable *RetvalTLS;
231   /// \brief Thread-local origin storage for function return value.
232   GlobalVariable *RetvalOriginTLS;
233   /// \brief Thread-local shadow storage for in-register va_arg function
234   /// parameters (x86_64-specific).
235   GlobalVariable *VAArgTLS;
236   /// \brief Thread-local shadow storage for va_arg overflow area
237   /// (x86_64-specific).
238   GlobalVariable *VAArgOverflowSizeTLS;
239   /// \brief Thread-local space used to pass origin value to the UMR reporting
240   /// function.
241   GlobalVariable *OriginTLS;
242
243   GlobalVariable *MsandrModuleStart;
244   GlobalVariable *MsandrModuleEnd;
245
246   /// \brief The run-time callback to print a warning.
247   Value *WarningFn;
248   /// \brief Run-time helper that generates a new origin value for a stack
249   /// allocation.
250   Value *MsanSetAllocaOrigin4Fn;
251   /// \brief Run-time helper that poisons stack on function entry.
252   Value *MsanPoisonStackFn;
253   /// \brief Run-time helper that records a store (or any event) of an
254   /// uninitialized value and returns an updated origin id encoding this info.
255   Value *MsanChainOriginFn;
256   /// \brief MSan runtime replacements for memmove, memcpy and memset.
257   Value *MemmoveFn, *MemcpyFn, *MemsetFn;
258
259   /// \brief Address mask used in application-to-shadow address calculation.
260   /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
261   uint64_t ShadowMask;
262   /// \brief Offset of the origin shadow from the "normal" shadow.
263   /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
264   uint64_t OriginOffset;
265   /// \brief Branch weights for error reporting.
266   MDNode *ColdCallWeights;
267   /// \brief Branch weights for origin store.
268   MDNode *OriginStoreWeights;
269   /// \brief Path to blacklist file.
270   SmallString<64> BlacklistFile;
271   /// \brief The blacklist.
272   std::unique_ptr<SpecialCaseList> BL;
273   /// \brief An empty volatile inline asm that prevents callback merge.
274   InlineAsm *EmptyAsm;
275
276   bool WrapIndirectCalls;
277   /// \brief Run-time wrapper for indirect calls.
278   Value *IndirectCallWrapperFn;
279   // Argument and return type of IndirectCallWrapperFn: void (*f)(void).
280   Type *AnyFunctionPtrTy;
281
282   friend struct MemorySanitizerVisitor;
283   friend struct VarArgAMD64Helper;
284 };
285 }  // namespace
286
287 char MemorySanitizer::ID = 0;
288 INITIALIZE_PASS(MemorySanitizer, "msan",
289                 "MemorySanitizer: detects uninitialized reads.",
290                 false, false)
291
292 FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins,
293                                               StringRef BlacklistFile) {
294   return new MemorySanitizer(TrackOrigins, BlacklistFile);
295 }
296
297 /// \brief Create a non-const global initialized with the given string.
298 ///
299 /// Creates a writable global for Str so that we can pass it to the
300 /// run-time lib. Runtime uses first 4 bytes of the string to store the
301 /// frame ID, so the string needs to be mutable.
302 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
303                                                             StringRef Str) {
304   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
305   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
306                             GlobalValue::PrivateLinkage, StrConst, "");
307 }
308
309
310 /// \brief Insert extern declaration of runtime-provided functions and globals.
311 void MemorySanitizer::initializeCallbacks(Module &M) {
312   // Only do this once.
313   if (WarningFn)
314     return;
315
316   IRBuilder<> IRB(*C);
317   // Create the callback.
318   // FIXME: this function should have "Cold" calling conv,
319   // which is not yet implemented.
320   StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
321                                         : "__msan_warning_noreturn";
322   WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
323
324   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
325     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
326     IRB.getInt8PtrTy(), IntptrTy, NULL);
327   MsanPoisonStackFn = M.getOrInsertFunction(
328     "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
329   MsanChainOriginFn = M.getOrInsertFunction(
330     "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), NULL);
331   MemmoveFn = M.getOrInsertFunction(
332     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
333     IRB.getInt8PtrTy(), IntptrTy, NULL);
334   MemcpyFn = M.getOrInsertFunction(
335     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
336     IntptrTy, NULL);
337   MemsetFn = M.getOrInsertFunction(
338     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
339     IntptrTy, NULL);
340
341   // Create globals.
342   RetvalTLS = new GlobalVariable(
343     M, ArrayType::get(IRB.getInt64Ty(), 8), false,
344     GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
345     GlobalVariable::InitialExecTLSModel);
346   RetvalOriginTLS = new GlobalVariable(
347     M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
348     "__msan_retval_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
349
350   ParamTLS = new GlobalVariable(
351     M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
352     GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
353     GlobalVariable::InitialExecTLSModel);
354   ParamOriginTLS = new GlobalVariable(
355     M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
356     0, "__msan_param_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
357
358   VAArgTLS = new GlobalVariable(
359     M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
360     GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
361     GlobalVariable::InitialExecTLSModel);
362   VAArgOverflowSizeTLS = new GlobalVariable(
363     M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
364     "__msan_va_arg_overflow_size_tls", 0,
365     GlobalVariable::InitialExecTLSModel);
366   OriginTLS = new GlobalVariable(
367     M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
368     "__msan_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
369
370   // We insert an empty inline asm after __msan_report* to avoid callback merge.
371   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
372                             StringRef(""), StringRef(""),
373                             /*hasSideEffects=*/true);
374
375   if (WrapIndirectCalls) {
376     AnyFunctionPtrTy =
377         PointerType::getUnqual(FunctionType::get(IRB.getVoidTy(), false));
378     IndirectCallWrapperFn = M.getOrInsertFunction(
379         ClWrapIndirectCalls, AnyFunctionPtrTy, AnyFunctionPtrTy, NULL);
380   }
381
382   if (ClWrapIndirectCallsFast) {
383     MsandrModuleStart = new GlobalVariable(
384         M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
385         0, "__executable_start");
386     MsandrModuleStart->setVisibility(GlobalVariable::HiddenVisibility);
387     MsandrModuleEnd = new GlobalVariable(
388         M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
389         0, "_end");
390     MsandrModuleEnd->setVisibility(GlobalVariable::HiddenVisibility);
391   }
392 }
393
394 /// \brief Module-level initialization.
395 ///
396 /// inserts a call to __msan_init to the module's constructor list.
397 bool MemorySanitizer::doInitialization(Module &M) {
398   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
399   if (!DLP)
400     return false;
401   DL = &DLP->getDataLayout();
402
403   BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
404   C = &(M.getContext());
405   unsigned PtrSize = DL->getPointerSizeInBits(/* AddressSpace */0);
406   switch (PtrSize) {
407     case 64:
408       ShadowMask = kShadowMask64;
409       OriginOffset = kOriginOffset64;
410       break;
411     case 32:
412       ShadowMask = kShadowMask32;
413       OriginOffset = kOriginOffset32;
414       break;
415     default:
416       report_fatal_error("unsupported pointer size");
417       break;
418   }
419
420   IRBuilder<> IRB(*C);
421   IntptrTy = IRB.getIntPtrTy(DL);
422   OriginTy = IRB.getInt32Ty();
423
424   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
425   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
426
427   // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
428   appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
429                       "__msan_init", IRB.getVoidTy(), NULL)), 0);
430
431   if (TrackOrigins)
432     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
433                        IRB.getInt32(TrackOrigins), "__msan_track_origins");
434
435   if (ClKeepGoing)
436     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
437                        IRB.getInt32(ClKeepGoing), "__msan_keep_going");
438
439   return true;
440 }
441
442 namespace {
443
444 /// \brief A helper class that handles instrumentation of VarArg
445 /// functions on a particular platform.
446 ///
447 /// Implementations are expected to insert the instrumentation
448 /// necessary to propagate argument shadow through VarArg function
449 /// calls. Visit* methods are called during an InstVisitor pass over
450 /// the function, and should avoid creating new basic blocks. A new
451 /// instance of this class is created for each instrumented function.
452 struct VarArgHelper {
453   /// \brief Visit a CallSite.
454   virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
455
456   /// \brief Visit a va_start call.
457   virtual void visitVAStartInst(VAStartInst &I) = 0;
458
459   /// \brief Visit a va_copy call.
460   virtual void visitVACopyInst(VACopyInst &I) = 0;
461
462   /// \brief Finalize function instrumentation.
463   ///
464   /// This method is called after visiting all interesting (see above)
465   /// instructions in a function.
466   virtual void finalizeInstrumentation() = 0;
467
468   virtual ~VarArgHelper() {}
469 };
470
471 struct MemorySanitizerVisitor;
472
473 VarArgHelper*
474 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
475                    MemorySanitizerVisitor &Visitor);
476
477 /// This class does all the work for a given function. Store and Load
478 /// instructions store and load corresponding shadow and origin
479 /// values. Most instructions propagate shadow from arguments to their
480 /// return values. Certain instructions (most importantly, BranchInst)
481 /// test their argument shadow and print reports (with a runtime call) if it's
482 /// non-zero.
483 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
484   Function &F;
485   MemorySanitizer &MS;
486   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
487   ValueMap<Value*, Value*> ShadowMap, OriginMap;
488   std::unique_ptr<VarArgHelper> VAHelper;
489
490   // The following flags disable parts of MSan instrumentation based on
491   // blacklist contents and command-line options.
492   bool InsertChecks;
493   bool LoadShadow;
494   bool PoisonStack;
495   bool PoisonUndef;
496   bool CheckReturnValue;
497
498   struct ShadowOriginAndInsertPoint {
499     Value *Shadow;
500     Value *Origin;
501     Instruction *OrigIns;
502     ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
503       : Shadow(S), Origin(O), OrigIns(I) { }
504   };
505   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
506   SmallVector<Instruction*, 16> StoreList;
507   SmallVector<CallSite, 16> IndirectCallList;
508
509   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
510       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
511     bool SanitizeFunction = !MS.BL->isIn(F) && F.getAttributes().hasAttribute(
512                                                    AttributeSet::FunctionIndex,
513                                                    Attribute::SanitizeMemory);
514     InsertChecks = SanitizeFunction;
515     LoadShadow = SanitizeFunction;
516     PoisonStack = SanitizeFunction && ClPoisonStack;
517     PoisonUndef = SanitizeFunction && ClPoisonUndef;
518     // FIXME: Consider using SpecialCaseList to specify a list of functions that
519     // must always return fully initialized values. For now, we hardcode "main".
520     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
521
522     DEBUG(if (!InsertChecks)
523           dbgs() << "MemorySanitizer is not inserting checks into '"
524                  << F.getName() << "'\n");
525   }
526
527   Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
528     if (MS.TrackOrigins <= 1) return V;
529     return IRB.CreateCall(MS.MsanChainOriginFn, V);
530   }
531
532   void materializeStores() {
533     for (size_t i = 0, n = StoreList.size(); i < n; i++) {
534       StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
535
536       IRBuilder<> IRB(&I);
537       Value *Val = I.getValueOperand();
538       Value *Addr = I.getPointerOperand();
539       Value *Shadow = I.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
540       Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
541
542       StoreInst *NewSI =
543         IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
544       DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
545       (void)NewSI;
546
547       if (ClCheckAccessAddress)
548         insertShadowCheck(Addr, &I);
549
550       if (I.isAtomic())
551         I.setOrdering(addReleaseOrdering(I.getOrdering()));
552
553       if (MS.TrackOrigins) {
554         unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
555         if (isa<StructType>(Shadow->getType())) {
556           IRB.CreateAlignedStore(updateOrigin(getOrigin(Val), IRB),
557                                  getOriginPtr(Addr, IRB), Alignment);
558         } else {
559           Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
560
561           // TODO(eugenis): handle non-zero constant shadow by inserting an
562           // unconditional check (can not simply fail compilation as this could
563           // be in the dead code).
564           if (isa<Constant>(ConvertedShadow))
565             continue;
566
567           Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
568               getCleanShadow(ConvertedShadow), "_mscmp");
569           Instruction *CheckTerm =
570               SplitBlockAndInsertIfThen(Cmp, &I, false, MS.OriginStoreWeights);
571           IRBuilder<> IRBNew(CheckTerm);
572           IRBNew.CreateAlignedStore(updateOrigin(getOrigin(Val), IRBNew),
573                                     getOriginPtr(Addr, IRBNew), Alignment);
574         }
575       }
576     }
577   }
578
579   void materializeChecks() {
580     for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
581       Value *Shadow = InstrumentationList[i].Shadow;
582       Instruction *OrigIns = InstrumentationList[i].OrigIns;
583       IRBuilder<> IRB(OrigIns);
584       DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
585       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
586       DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
587       // See the comment in materializeStores().
588       if (isa<Constant>(ConvertedShadow))
589         continue;
590       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
591                                     getCleanShadow(ConvertedShadow), "_mscmp");
592       Instruction *CheckTerm = SplitBlockAndInsertIfThen(
593           Cmp, OrigIns,
594           /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
595
596       IRB.SetInsertPoint(CheckTerm);
597       if (MS.TrackOrigins) {
598         Value *Origin = InstrumentationList[i].Origin;
599         IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
600                         MS.OriginTLS);
601       }
602       IRB.CreateCall(MS.WarningFn);
603       IRB.CreateCall(MS.EmptyAsm);
604       DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
605     }
606     DEBUG(dbgs() << "DONE:\n" << F);
607   }
608
609   void materializeIndirectCalls() {
610     for (size_t i = 0, n = IndirectCallList.size(); i < n; i++) {
611       CallSite CS = IndirectCallList[i];
612       Instruction *I = CS.getInstruction();
613       BasicBlock *B = I->getParent();
614       IRBuilder<> IRB(I);
615       Value *Fn0 = CS.getCalledValue();
616       Value *Fn = IRB.CreateBitCast(Fn0, MS.AnyFunctionPtrTy);
617
618       if (ClWrapIndirectCallsFast) {
619         // Check that call target is inside this module limits.
620         Value *Start =
621             IRB.CreateBitCast(MS.MsandrModuleStart, MS.AnyFunctionPtrTy);
622         Value *End = IRB.CreateBitCast(MS.MsandrModuleEnd, MS.AnyFunctionPtrTy);
623
624         Value *NotInThisModule = IRB.CreateOr(IRB.CreateICmpULT(Fn, Start),
625                                               IRB.CreateICmpUGE(Fn, End));
626
627         PHINode *NewFnPhi =
628             IRB.CreatePHI(Fn0->getType(), 2, "msandr.indirect_target");
629
630         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
631             NotInThisModule, NewFnPhi,
632             /* Unreachable */ false, MS.ColdCallWeights);
633
634         IRB.SetInsertPoint(CheckTerm);
635         // Slow path: call wrapper function to possibly transform the call
636         // target.
637         Value *NewFn = IRB.CreateBitCast(
638             IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
639
640         NewFnPhi->addIncoming(Fn0, B);
641         NewFnPhi->addIncoming(NewFn, dyn_cast<Instruction>(NewFn)->getParent());
642         CS.setCalledFunction(NewFnPhi);
643       } else {
644         Value *NewFn = IRB.CreateBitCast(
645             IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
646         CS.setCalledFunction(NewFn);
647       }
648     }
649   }
650
651   /// \brief Add MemorySanitizer instrumentation to a function.
652   bool runOnFunction() {
653     MS.initializeCallbacks(*F.getParent());
654     if (!MS.DL) return false;
655
656     // In the presence of unreachable blocks, we may see Phi nodes with
657     // incoming nodes from such blocks. Since InstVisitor skips unreachable
658     // blocks, such nodes will not have any shadow value associated with them.
659     // It's easier to remove unreachable blocks than deal with missing shadow.
660     removeUnreachableBlocks(F);
661
662     // Iterate all BBs in depth-first order and create shadow instructions
663     // for all instructions (where applicable).
664     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
665     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
666       visit(*BB);
667
668
669     // Finalize PHI nodes.
670     for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
671       PHINode *PN = ShadowPHINodes[i];
672       PHINode *PNS = cast<PHINode>(getShadow(PN));
673       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
674       size_t NumValues = PN->getNumIncomingValues();
675       for (size_t v = 0; v < NumValues; v++) {
676         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
677         if (PNO)
678           PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
679       }
680     }
681
682     VAHelper->finalizeInstrumentation();
683
684     // Delayed instrumentation of StoreInst.
685     // This may add new checks to be inserted later.
686     materializeStores();
687
688     // Insert shadow value checks.
689     materializeChecks();
690
691     // Wrap indirect calls.
692     materializeIndirectCalls();
693
694     return true;
695   }
696
697   /// \brief Compute the shadow type that corresponds to a given Value.
698   Type *getShadowTy(Value *V) {
699     return getShadowTy(V->getType());
700   }
701
702   /// \brief Compute the shadow type that corresponds to a given Type.
703   Type *getShadowTy(Type *OrigTy) {
704     if (!OrigTy->isSized()) {
705       return 0;
706     }
707     // For integer type, shadow is the same as the original type.
708     // This may return weird-sized types like i1.
709     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
710       return IT;
711     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
712       uint32_t EltSize = MS.DL->getTypeSizeInBits(VT->getElementType());
713       return VectorType::get(IntegerType::get(*MS.C, EltSize),
714                              VT->getNumElements());
715     }
716     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
717       SmallVector<Type*, 4> Elements;
718       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
719         Elements.push_back(getShadowTy(ST->getElementType(i)));
720       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
721       DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
722       return Res;
723     }
724     uint32_t TypeSize = MS.DL->getTypeSizeInBits(OrigTy);
725     return IntegerType::get(*MS.C, TypeSize);
726   }
727
728   /// \brief Flatten a vector type.
729   Type *getShadowTyNoVec(Type *ty) {
730     if (VectorType *vt = dyn_cast<VectorType>(ty))
731       return IntegerType::get(*MS.C, vt->getBitWidth());
732     return ty;
733   }
734
735   /// \brief Convert a shadow value to it's flattened variant.
736   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
737     Type *Ty = V->getType();
738     Type *NoVecTy = getShadowTyNoVec(Ty);
739     if (Ty == NoVecTy) return V;
740     return IRB.CreateBitCast(V, NoVecTy);
741   }
742
743   /// \brief Compute the shadow address that corresponds to a given application
744   /// address.
745   ///
746   /// Shadow = Addr & ~ShadowMask.
747   Value *getShadowPtr(Value *Addr, Type *ShadowTy,
748                       IRBuilder<> &IRB) {
749     Value *ShadowLong =
750       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
751                     ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
752     return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
753   }
754
755   /// \brief Compute the origin address that corresponds to a given application
756   /// address.
757   ///
758   /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
759   Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
760     Value *ShadowLong =
761       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
762                     ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
763     Value *Add =
764       IRB.CreateAdd(ShadowLong,
765                     ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
766     Value *SecondAnd =
767       IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
768     return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
769   }
770
771   /// \brief Compute the shadow address for a given function argument.
772   ///
773   /// Shadow = ParamTLS+ArgOffset.
774   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
775                                  int ArgOffset) {
776     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
777     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
778     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
779                               "_msarg");
780   }
781
782   /// \brief Compute the origin address for a given function argument.
783   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
784                                  int ArgOffset) {
785     if (!MS.TrackOrigins) return 0;
786     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
787     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
788     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
789                               "_msarg_o");
790   }
791
792   /// \brief Compute the shadow address for a retval.
793   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
794     Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
795     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
796                               "_msret");
797   }
798
799   /// \brief Compute the origin address for a retval.
800   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
801     // We keep a single origin for the entire retval. Might be too optimistic.
802     return MS.RetvalOriginTLS;
803   }
804
805   /// \brief Set SV to be the shadow value for V.
806   void setShadow(Value *V, Value *SV) {
807     assert(!ShadowMap.count(V) && "Values may only have one shadow");
808     ShadowMap[V] = SV;
809   }
810
811   /// \brief Set Origin to be the origin value for V.
812   void setOrigin(Value *V, Value *Origin) {
813     if (!MS.TrackOrigins) return;
814     assert(!OriginMap.count(V) && "Values may only have one origin");
815     DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
816     OriginMap[V] = Origin;
817   }
818
819   /// \brief Create a clean shadow value for a given value.
820   ///
821   /// Clean shadow (all zeroes) means all bits of the value are defined
822   /// (initialized).
823   Constant *getCleanShadow(Value *V) {
824     Type *ShadowTy = getShadowTy(V);
825     if (!ShadowTy)
826       return 0;
827     return Constant::getNullValue(ShadowTy);
828   }
829
830   /// \brief Create a dirty shadow of a given shadow type.
831   Constant *getPoisonedShadow(Type *ShadowTy) {
832     assert(ShadowTy);
833     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
834       return Constant::getAllOnesValue(ShadowTy);
835     StructType *ST = cast<StructType>(ShadowTy);
836     SmallVector<Constant *, 4> Vals;
837     for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
838       Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
839     return ConstantStruct::get(ST, Vals);
840   }
841
842   /// \brief Create a dirty shadow for a given value.
843   Constant *getPoisonedShadow(Value *V) {
844     Type *ShadowTy = getShadowTy(V);
845     if (!ShadowTy)
846       return 0;
847     return getPoisonedShadow(ShadowTy);
848   }
849
850   /// \brief Create a clean (zero) origin.
851   Value *getCleanOrigin() {
852     return Constant::getNullValue(MS.OriginTy);
853   }
854
855   /// \brief Get the shadow value for a given Value.
856   ///
857   /// This function either returns the value set earlier with setShadow,
858   /// or extracts if from ParamTLS (for function arguments).
859   Value *getShadow(Value *V) {
860     if (Instruction *I = dyn_cast<Instruction>(V)) {
861       // For instructions the shadow is already stored in the map.
862       Value *Shadow = ShadowMap[V];
863       if (!Shadow) {
864         DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
865         (void)I;
866         assert(Shadow && "No shadow for a value");
867       }
868       return Shadow;
869     }
870     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
871       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
872       DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
873       (void)U;
874       return AllOnes;
875     }
876     if (Argument *A = dyn_cast<Argument>(V)) {
877       // For arguments we compute the shadow on demand and store it in the map.
878       Value **ShadowPtr = &ShadowMap[V];
879       if (*ShadowPtr)
880         return *ShadowPtr;
881       Function *F = A->getParent();
882       IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
883       unsigned ArgOffset = 0;
884       for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
885            AI != AE; ++AI) {
886         if (!AI->getType()->isSized()) {
887           DEBUG(dbgs() << "Arg is not sized\n");
888           continue;
889         }
890         unsigned Size = AI->hasByValAttr()
891           ? MS.DL->getTypeAllocSize(AI->getType()->getPointerElementType())
892           : MS.DL->getTypeAllocSize(AI->getType());
893         if (A == AI) {
894           Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
895           if (AI->hasByValAttr()) {
896             // ByVal pointer itself has clean shadow. We copy the actual
897             // argument shadow to the underlying memory.
898             // Figure out maximal valid memcpy alignment.
899             unsigned ArgAlign = AI->getParamAlignment();
900             if (ArgAlign == 0) {
901               Type *EltType = A->getType()->getPointerElementType();
902               ArgAlign = MS.DL->getABITypeAlignment(EltType);
903             }
904             unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
905             Value *Cpy = EntryIRB.CreateMemCpy(
906                 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
907                 CopyAlign);
908             DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
909             (void)Cpy;
910             *ShadowPtr = getCleanShadow(V);
911           } else {
912             *ShadowPtr = EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
913           }
914           DEBUG(dbgs() << "  ARG:    "  << *AI << " ==> " <<
915                 **ShadowPtr << "\n");
916           if (MS.TrackOrigins) {
917             Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
918             setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
919           }
920         }
921         ArgOffset += DataLayout::RoundUpAlignment(Size, kShadowTLSAlignment);
922       }
923       assert(*ShadowPtr && "Could not find shadow for an argument");
924       return *ShadowPtr;
925     }
926     // For everything else the shadow is zero.
927     return getCleanShadow(V);
928   }
929
930   /// \brief Get the shadow for i-th argument of the instruction I.
931   Value *getShadow(Instruction *I, int i) {
932     return getShadow(I->getOperand(i));
933   }
934
935   /// \brief Get the origin for a value.
936   Value *getOrigin(Value *V) {
937     if (!MS.TrackOrigins) return 0;
938     if (isa<Instruction>(V) || isa<Argument>(V)) {
939       Value *Origin = OriginMap[V];
940       if (!Origin) {
941         DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
942         Origin = getCleanOrigin();
943       }
944       return Origin;
945     }
946     return getCleanOrigin();
947   }
948
949   /// \brief Get the origin for i-th argument of the instruction I.
950   Value *getOrigin(Instruction *I, int i) {
951     return getOrigin(I->getOperand(i));
952   }
953
954   /// \brief Remember the place where a shadow check should be inserted.
955   ///
956   /// This location will be later instrumented with a check that will print a
957   /// UMR warning in runtime if the shadow value is not 0.
958   void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
959     assert(Shadow);
960     if (!InsertChecks) return;
961 #ifndef NDEBUG
962     Type *ShadowTy = Shadow->getType();
963     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
964            "Can only insert checks for integer and vector shadow types");
965 #endif
966     InstrumentationList.push_back(
967         ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
968   }
969
970   /// \brief Remember the place where a shadow check should be inserted.
971   ///
972   /// This location will be later instrumented with a check that will print a
973   /// UMR warning in runtime if the value is not fully defined.
974   void insertShadowCheck(Value *Val, Instruction *OrigIns) {
975     assert(Val);
976     Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
977     if (!Shadow) return;
978     Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
979     insertShadowCheck(Shadow, Origin, OrigIns);
980   }
981
982   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
983     switch (a) {
984       case NotAtomic:
985         return NotAtomic;
986       case Unordered:
987       case Monotonic:
988       case Release:
989         return Release;
990       case Acquire:
991       case AcquireRelease:
992         return AcquireRelease;
993       case SequentiallyConsistent:
994         return SequentiallyConsistent;
995     }
996     llvm_unreachable("Unknown ordering");
997   }
998
999   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1000     switch (a) {
1001       case NotAtomic:
1002         return NotAtomic;
1003       case Unordered:
1004       case Monotonic:
1005       case Acquire:
1006         return Acquire;
1007       case Release:
1008       case AcquireRelease:
1009         return AcquireRelease;
1010       case SequentiallyConsistent:
1011         return SequentiallyConsistent;
1012     }
1013     llvm_unreachable("Unknown ordering");
1014   }
1015
1016   // ------------------- Visitors.
1017
1018   /// \brief Instrument LoadInst
1019   ///
1020   /// Loads the corresponding shadow and (optionally) origin.
1021   /// Optionally, checks that the load address is fully defined.
1022   void visitLoadInst(LoadInst &I) {
1023     assert(I.getType()->isSized() && "Load type must have size");
1024     IRBuilder<> IRB(I.getNextNode());
1025     Type *ShadowTy = getShadowTy(&I);
1026     Value *Addr = I.getPointerOperand();
1027     if (LoadShadow) {
1028       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1029       setShadow(&I,
1030                 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1031     } else {
1032       setShadow(&I, getCleanShadow(&I));
1033     }
1034
1035     if (ClCheckAccessAddress)
1036       insertShadowCheck(I.getPointerOperand(), &I);
1037
1038     if (I.isAtomic())
1039       I.setOrdering(addAcquireOrdering(I.getOrdering()));
1040
1041     if (MS.TrackOrigins) {
1042       if (LoadShadow) {
1043         unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
1044         setOrigin(&I,
1045                   IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
1046       } else {
1047         setOrigin(&I, getCleanOrigin());
1048       }
1049     }
1050   }
1051
1052   /// \brief Instrument StoreInst
1053   ///
1054   /// Stores the corresponding shadow and (optionally) origin.
1055   /// Optionally, checks that the store address is fully defined.
1056   void visitStoreInst(StoreInst &I) {
1057     StoreList.push_back(&I);
1058   }
1059
1060   void handleCASOrRMW(Instruction &I) {
1061     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1062
1063     IRBuilder<> IRB(&I);
1064     Value *Addr = I.getOperand(0);
1065     Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1066
1067     if (ClCheckAccessAddress)
1068       insertShadowCheck(Addr, &I);
1069
1070     // Only test the conditional argument of cmpxchg instruction.
1071     // The other argument can potentially be uninitialized, but we can not
1072     // detect this situation reliably without possible false positives.
1073     if (isa<AtomicCmpXchgInst>(I))
1074       insertShadowCheck(I.getOperand(1), &I);
1075
1076     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1077
1078     setShadow(&I, getCleanShadow(&I));
1079   }
1080
1081   void visitAtomicRMWInst(AtomicRMWInst &I) {
1082     handleCASOrRMW(I);
1083     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1084   }
1085
1086   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1087     handleCASOrRMW(I);
1088     I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1089   }
1090
1091   // Vector manipulation.
1092   void visitExtractElementInst(ExtractElementInst &I) {
1093     insertShadowCheck(I.getOperand(1), &I);
1094     IRBuilder<> IRB(&I);
1095     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1096               "_msprop"));
1097     setOrigin(&I, getOrigin(&I, 0));
1098   }
1099
1100   void visitInsertElementInst(InsertElementInst &I) {
1101     insertShadowCheck(I.getOperand(2), &I);
1102     IRBuilder<> IRB(&I);
1103     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1104               I.getOperand(2), "_msprop"));
1105     setOriginForNaryOp(I);
1106   }
1107
1108   void visitShuffleVectorInst(ShuffleVectorInst &I) {
1109     insertShadowCheck(I.getOperand(2), &I);
1110     IRBuilder<> IRB(&I);
1111     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1112               I.getOperand(2), "_msprop"));
1113     setOriginForNaryOp(I);
1114   }
1115
1116   // Casts.
1117   void visitSExtInst(SExtInst &I) {
1118     IRBuilder<> IRB(&I);
1119     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1120     setOrigin(&I, getOrigin(&I, 0));
1121   }
1122
1123   void visitZExtInst(ZExtInst &I) {
1124     IRBuilder<> IRB(&I);
1125     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1126     setOrigin(&I, getOrigin(&I, 0));
1127   }
1128
1129   void visitTruncInst(TruncInst &I) {
1130     IRBuilder<> IRB(&I);
1131     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1132     setOrigin(&I, getOrigin(&I, 0));
1133   }
1134
1135   void visitBitCastInst(BitCastInst &I) {
1136     IRBuilder<> IRB(&I);
1137     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1138     setOrigin(&I, getOrigin(&I, 0));
1139   }
1140
1141   void visitPtrToIntInst(PtrToIntInst &I) {
1142     IRBuilder<> IRB(&I);
1143     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1144              "_msprop_ptrtoint"));
1145     setOrigin(&I, getOrigin(&I, 0));
1146   }
1147
1148   void visitIntToPtrInst(IntToPtrInst &I) {
1149     IRBuilder<> IRB(&I);
1150     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1151              "_msprop_inttoptr"));
1152     setOrigin(&I, getOrigin(&I, 0));
1153   }
1154
1155   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1156   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1157   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1158   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1159   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1160   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1161
1162   /// \brief Propagate shadow for bitwise AND.
1163   ///
1164   /// This code is exact, i.e. if, for example, a bit in the left argument
1165   /// is defined and 0, then neither the value not definedness of the
1166   /// corresponding bit in B don't affect the resulting shadow.
1167   void visitAnd(BinaryOperator &I) {
1168     IRBuilder<> IRB(&I);
1169     //  "And" of 0 and a poisoned value results in unpoisoned value.
1170     //  1&1 => 1;     0&1 => 0;     p&1 => p;
1171     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
1172     //  1&p => p;     0&p => 0;     p&p => p;
1173     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1174     Value *S1 = getShadow(&I, 0);
1175     Value *S2 = getShadow(&I, 1);
1176     Value *V1 = I.getOperand(0);
1177     Value *V2 = I.getOperand(1);
1178     if (V1->getType() != S1->getType()) {
1179       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1180       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1181     }
1182     Value *S1S2 = IRB.CreateAnd(S1, S2);
1183     Value *V1S2 = IRB.CreateAnd(V1, S2);
1184     Value *S1V2 = IRB.CreateAnd(S1, V2);
1185     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1186     setOriginForNaryOp(I);
1187   }
1188
1189   void visitOr(BinaryOperator &I) {
1190     IRBuilder<> IRB(&I);
1191     //  "Or" of 1 and a poisoned value results in unpoisoned value.
1192     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
1193     //  1|0 => 1;     0|0 => 0;     p|0 => p;
1194     //  1|p => 1;     0|p => p;     p|p => p;
1195     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1196     Value *S1 = getShadow(&I, 0);
1197     Value *S2 = getShadow(&I, 1);
1198     Value *V1 = IRB.CreateNot(I.getOperand(0));
1199     Value *V2 = IRB.CreateNot(I.getOperand(1));
1200     if (V1->getType() != S1->getType()) {
1201       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1202       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1203     }
1204     Value *S1S2 = IRB.CreateAnd(S1, S2);
1205     Value *V1S2 = IRB.CreateAnd(V1, S2);
1206     Value *S1V2 = IRB.CreateAnd(S1, V2);
1207     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1208     setOriginForNaryOp(I);
1209   }
1210
1211   /// \brief Default propagation of shadow and/or origin.
1212   ///
1213   /// This class implements the general case of shadow propagation, used in all
1214   /// cases where we don't know and/or don't care about what the operation
1215   /// actually does. It converts all input shadow values to a common type
1216   /// (extending or truncating as necessary), and bitwise OR's them.
1217   ///
1218   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1219   /// fully initialized), and less prone to false positives.
1220   ///
1221   /// This class also implements the general case of origin propagation. For a
1222   /// Nary operation, result origin is set to the origin of an argument that is
1223   /// not entirely initialized. If there is more than one such arguments, the
1224   /// rightmost of them is picked. It does not matter which one is picked if all
1225   /// arguments are initialized.
1226   template <bool CombineShadow>
1227   class Combiner {
1228     Value *Shadow;
1229     Value *Origin;
1230     IRBuilder<> &IRB;
1231     MemorySanitizerVisitor *MSV;
1232
1233   public:
1234     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1235       Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
1236
1237     /// \brief Add a pair of shadow and origin values to the mix.
1238     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1239       if (CombineShadow) {
1240         assert(OpShadow);
1241         if (!Shadow)
1242           Shadow = OpShadow;
1243         else {
1244           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1245           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1246         }
1247       }
1248
1249       if (MSV->MS.TrackOrigins) {
1250         assert(OpOrigin);
1251         if (!Origin) {
1252           Origin = OpOrigin;
1253         } else {
1254           Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1255           Value *Cond = IRB.CreateICmpNE(FlatShadow,
1256                                          MSV->getCleanShadow(FlatShadow));
1257           Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1258         }
1259       }
1260       return *this;
1261     }
1262
1263     /// \brief Add an application value to the mix.
1264     Combiner &Add(Value *V) {
1265       Value *OpShadow = MSV->getShadow(V);
1266       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
1267       return Add(OpShadow, OpOrigin);
1268     }
1269
1270     /// \brief Set the current combined values as the given instruction's shadow
1271     /// and origin.
1272     void Done(Instruction *I) {
1273       if (CombineShadow) {
1274         assert(Shadow);
1275         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1276         MSV->setShadow(I, Shadow);
1277       }
1278       if (MSV->MS.TrackOrigins) {
1279         assert(Origin);
1280         MSV->setOrigin(I, Origin);
1281       }
1282     }
1283   };
1284
1285   typedef Combiner<true> ShadowAndOriginCombiner;
1286   typedef Combiner<false> OriginCombiner;
1287
1288   /// \brief Propagate origin for arbitrary operation.
1289   void setOriginForNaryOp(Instruction &I) {
1290     if (!MS.TrackOrigins) return;
1291     IRBuilder<> IRB(&I);
1292     OriginCombiner OC(this, IRB);
1293     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1294       OC.Add(OI->get());
1295     OC.Done(&I);
1296   }
1297
1298   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1299     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1300            "Vector of pointers is not a valid shadow type");
1301     return Ty->isVectorTy() ?
1302       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1303       Ty->getPrimitiveSizeInBits();
1304   }
1305
1306   /// \brief Cast between two shadow types, extending or truncating as
1307   /// necessary.
1308   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1309                           bool Signed = false) {
1310     Type *srcTy = V->getType();
1311     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1312       return IRB.CreateIntCast(V, dstTy, Signed);
1313     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1314         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1315       return IRB.CreateIntCast(V, dstTy, Signed);
1316     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1317     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1318     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1319     Value *V2 =
1320       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1321     return IRB.CreateBitCast(V2, dstTy);
1322     // TODO: handle struct types.
1323   }
1324
1325   /// \brief Cast an application value to the type of its own shadow.
1326   Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1327     Type *ShadowTy = getShadowTy(V);
1328     if (V->getType() == ShadowTy)
1329       return V;
1330     if (V->getType()->isPtrOrPtrVectorTy())
1331       return IRB.CreatePtrToInt(V, ShadowTy);
1332     else
1333       return IRB.CreateBitCast(V, ShadowTy);
1334   }
1335
1336   /// \brief Propagate shadow for arbitrary operation.
1337   void handleShadowOr(Instruction &I) {
1338     IRBuilder<> IRB(&I);
1339     ShadowAndOriginCombiner SC(this, IRB);
1340     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1341       SC.Add(OI->get());
1342     SC.Done(&I);
1343   }
1344
1345   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1346   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1347   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1348   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1349   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1350   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1351   void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1352
1353   void handleDiv(Instruction &I) {
1354     IRBuilder<> IRB(&I);
1355     // Strict on the second argument.
1356     insertShadowCheck(I.getOperand(1), &I);
1357     setShadow(&I, getShadow(&I, 0));
1358     setOrigin(&I, getOrigin(&I, 0));
1359   }
1360
1361   void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1362   void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1363   void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1364   void visitURem(BinaryOperator &I) { handleDiv(I); }
1365   void visitSRem(BinaryOperator &I) { handleDiv(I); }
1366   void visitFRem(BinaryOperator &I) { handleDiv(I); }
1367
1368   /// \brief Instrument == and != comparisons.
1369   ///
1370   /// Sometimes the comparison result is known even if some of the bits of the
1371   /// arguments are not.
1372   void handleEqualityComparison(ICmpInst &I) {
1373     IRBuilder<> IRB(&I);
1374     Value *A = I.getOperand(0);
1375     Value *B = I.getOperand(1);
1376     Value *Sa = getShadow(A);
1377     Value *Sb = getShadow(B);
1378
1379     // Get rid of pointers and vectors of pointers.
1380     // For ints (and vectors of ints), types of A and Sa match,
1381     // and this is a no-op.
1382     A = IRB.CreatePointerCast(A, Sa->getType());
1383     B = IRB.CreatePointerCast(B, Sb->getType());
1384
1385     // A == B  <==>  (C = A^B) == 0
1386     // A != B  <==>  (C = A^B) != 0
1387     // Sc = Sa | Sb
1388     Value *C = IRB.CreateXor(A, B);
1389     Value *Sc = IRB.CreateOr(Sa, Sb);
1390     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1391     // Result is defined if one of the following is true
1392     // * there is a defined 1 bit in C
1393     // * C is fully defined
1394     // Si = !(C & ~Sc) && Sc
1395     Value *Zero = Constant::getNullValue(Sc->getType());
1396     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1397     Value *Si =
1398       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1399                     IRB.CreateICmpEQ(
1400                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1401     Si->setName("_msprop_icmp");
1402     setShadow(&I, Si);
1403     setOriginForNaryOp(I);
1404   }
1405
1406   /// \brief Build the lowest possible value of V, taking into account V's
1407   ///        uninitialized bits.
1408   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1409                                 bool isSigned) {
1410     if (isSigned) {
1411       // Split shadow into sign bit and other bits.
1412       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1413       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1414       // Maximise the undefined shadow bit, minimize other undefined bits.
1415       return
1416         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1417     } else {
1418       // Minimize undefined bits.
1419       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1420     }
1421   }
1422
1423   /// \brief Build the highest possible value of V, taking into account V's
1424   ///        uninitialized bits.
1425   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1426                                 bool isSigned) {
1427     if (isSigned) {
1428       // Split shadow into sign bit and other bits.
1429       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1430       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1431       // Minimise the undefined shadow bit, maximise other undefined bits.
1432       return
1433         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1434     } else {
1435       // Maximize undefined bits.
1436       return IRB.CreateOr(A, Sa);
1437     }
1438   }
1439
1440   /// \brief Instrument relational comparisons.
1441   ///
1442   /// This function does exact shadow propagation for all relational
1443   /// comparisons of integers, pointers and vectors of those.
1444   /// FIXME: output seems suboptimal when one of the operands is a constant
1445   void handleRelationalComparisonExact(ICmpInst &I) {
1446     IRBuilder<> IRB(&I);
1447     Value *A = I.getOperand(0);
1448     Value *B = I.getOperand(1);
1449     Value *Sa = getShadow(A);
1450     Value *Sb = getShadow(B);
1451
1452     // Get rid of pointers and vectors of pointers.
1453     // For ints (and vectors of ints), types of A and Sa match,
1454     // and this is a no-op.
1455     A = IRB.CreatePointerCast(A, Sa->getType());
1456     B = IRB.CreatePointerCast(B, Sb->getType());
1457
1458     // Let [a0, a1] be the interval of possible values of A, taking into account
1459     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1460     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1461     bool IsSigned = I.isSigned();
1462     Value *S1 = IRB.CreateICmp(I.getPredicate(),
1463                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
1464                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
1465     Value *S2 = IRB.CreateICmp(I.getPredicate(),
1466                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
1467                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
1468     Value *Si = IRB.CreateXor(S1, S2);
1469     setShadow(&I, Si);
1470     setOriginForNaryOp(I);
1471   }
1472
1473   /// \brief Instrument signed relational comparisons.
1474   ///
1475   /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1476   /// propagating the highest bit of the shadow. Everything else is delegated
1477   /// to handleShadowOr().
1478   void handleSignedRelationalComparison(ICmpInst &I) {
1479     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1480     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1481     Value* op = NULL;
1482     CmpInst::Predicate pre = I.getPredicate();
1483     if (constOp0 && constOp0->isNullValue() &&
1484         (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1485       op = I.getOperand(1);
1486     } else if (constOp1 && constOp1->isNullValue() &&
1487                (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1488       op = I.getOperand(0);
1489     }
1490     if (op) {
1491       IRBuilder<> IRB(&I);
1492       Value* Shadow =
1493         IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1494       setShadow(&I, Shadow);
1495       setOrigin(&I, getOrigin(op));
1496     } else {
1497       handleShadowOr(I);
1498     }
1499   }
1500
1501   void visitICmpInst(ICmpInst &I) {
1502     if (!ClHandleICmp) {
1503       handleShadowOr(I);
1504       return;
1505     }
1506     if (I.isEquality()) {
1507       handleEqualityComparison(I);
1508       return;
1509     }
1510
1511     assert(I.isRelational());
1512     if (ClHandleICmpExact) {
1513       handleRelationalComparisonExact(I);
1514       return;
1515     }
1516     if (I.isSigned()) {
1517       handleSignedRelationalComparison(I);
1518       return;
1519     }
1520
1521     assert(I.isUnsigned());
1522     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1523       handleRelationalComparisonExact(I);
1524       return;
1525     }
1526
1527     handleShadowOr(I);
1528   }
1529
1530   void visitFCmpInst(FCmpInst &I) {
1531     handleShadowOr(I);
1532   }
1533
1534   void handleShift(BinaryOperator &I) {
1535     IRBuilder<> IRB(&I);
1536     // If any of the S2 bits are poisoned, the whole thing is poisoned.
1537     // Otherwise perform the same shift on S1.
1538     Value *S1 = getShadow(&I, 0);
1539     Value *S2 = getShadow(&I, 1);
1540     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1541                                    S2->getType());
1542     Value *V2 = I.getOperand(1);
1543     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1544     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1545     setOriginForNaryOp(I);
1546   }
1547
1548   void visitShl(BinaryOperator &I) { handleShift(I); }
1549   void visitAShr(BinaryOperator &I) { handleShift(I); }
1550   void visitLShr(BinaryOperator &I) { handleShift(I); }
1551
1552   /// \brief Instrument llvm.memmove
1553   ///
1554   /// At this point we don't know if llvm.memmove will be inlined or not.
1555   /// If we don't instrument it and it gets inlined,
1556   /// our interceptor will not kick in and we will lose the memmove.
1557   /// If we instrument the call here, but it does not get inlined,
1558   /// we will memove the shadow twice: which is bad in case
1559   /// of overlapping regions. So, we simply lower the intrinsic to a call.
1560   ///
1561   /// Similar situation exists for memcpy and memset.
1562   void visitMemMoveInst(MemMoveInst &I) {
1563     IRBuilder<> IRB(&I);
1564     IRB.CreateCall3(
1565       MS.MemmoveFn,
1566       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1567       IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1568       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1569     I.eraseFromParent();
1570   }
1571
1572   // Similar to memmove: avoid copying shadow twice.
1573   // This is somewhat unfortunate as it may slowdown small constant memcpys.
1574   // FIXME: consider doing manual inline for small constant sizes and proper
1575   // alignment.
1576   void visitMemCpyInst(MemCpyInst &I) {
1577     IRBuilder<> IRB(&I);
1578     IRB.CreateCall3(
1579       MS.MemcpyFn,
1580       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1581       IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1582       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1583     I.eraseFromParent();
1584   }
1585
1586   // Same as memcpy.
1587   void visitMemSetInst(MemSetInst &I) {
1588     IRBuilder<> IRB(&I);
1589     IRB.CreateCall3(
1590       MS.MemsetFn,
1591       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1592       IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1593       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1594     I.eraseFromParent();
1595   }
1596
1597   void visitVAStartInst(VAStartInst &I) {
1598     VAHelper->visitVAStartInst(I);
1599   }
1600
1601   void visitVACopyInst(VACopyInst &I) {
1602     VAHelper->visitVACopyInst(I);
1603   }
1604
1605   enum IntrinsicKind {
1606     IK_DoesNotAccessMemory,
1607     IK_OnlyReadsMemory,
1608     IK_WritesMemory
1609   };
1610
1611   static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1612     const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1613     const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1614     const int OnlyReadsMemory = IK_OnlyReadsMemory;
1615     const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1616     const int UnknownModRefBehavior = IK_WritesMemory;
1617 #define GET_INTRINSIC_MODREF_BEHAVIOR
1618 #define ModRefBehavior IntrinsicKind
1619 #include "llvm/IR/Intrinsics.gen"
1620 #undef ModRefBehavior
1621 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1622   }
1623
1624   /// \brief Handle vector store-like intrinsics.
1625   ///
1626   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1627   /// has 1 pointer argument and 1 vector argument, returns void.
1628   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1629     IRBuilder<> IRB(&I);
1630     Value* Addr = I.getArgOperand(0);
1631     Value *Shadow = getShadow(&I, 1);
1632     Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1633
1634     // We don't know the pointer alignment (could be unaligned SSE store!).
1635     // Have to assume to worst case.
1636     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1637
1638     if (ClCheckAccessAddress)
1639       insertShadowCheck(Addr, &I);
1640
1641     // FIXME: use ClStoreCleanOrigin
1642     // FIXME: factor out common code from materializeStores
1643     if (MS.TrackOrigins)
1644       IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1645     return true;
1646   }
1647
1648   /// \brief Handle vector load-like intrinsics.
1649   ///
1650   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1651   /// has 1 pointer argument, returns a vector.
1652   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1653     IRBuilder<> IRB(&I);
1654     Value *Addr = I.getArgOperand(0);
1655
1656     Type *ShadowTy = getShadowTy(&I);
1657     if (LoadShadow) {
1658       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1659       // We don't know the pointer alignment (could be unaligned SSE load!).
1660       // Have to assume to worst case.
1661       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1662     } else {
1663       setShadow(&I, getCleanShadow(&I));
1664     }
1665
1666     if (ClCheckAccessAddress)
1667       insertShadowCheck(Addr, &I);
1668
1669     if (MS.TrackOrigins) {
1670       if (LoadShadow)
1671         setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1672       else
1673         setOrigin(&I, getCleanOrigin());
1674     }
1675     return true;
1676   }
1677
1678   /// \brief Handle (SIMD arithmetic)-like intrinsics.
1679   ///
1680   /// Instrument intrinsics with any number of arguments of the same type,
1681   /// equal to the return type. The type should be simple (no aggregates or
1682   /// pointers; vectors are fine).
1683   /// Caller guarantees that this intrinsic does not access memory.
1684   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1685     Type *RetTy = I.getType();
1686     if (!(RetTy->isIntOrIntVectorTy() ||
1687           RetTy->isFPOrFPVectorTy() ||
1688           RetTy->isX86_MMXTy()))
1689       return false;
1690
1691     unsigned NumArgOperands = I.getNumArgOperands();
1692
1693     for (unsigned i = 0; i < NumArgOperands; ++i) {
1694       Type *Ty = I.getArgOperand(i)->getType();
1695       if (Ty != RetTy)
1696         return false;
1697     }
1698
1699     IRBuilder<> IRB(&I);
1700     ShadowAndOriginCombiner SC(this, IRB);
1701     for (unsigned i = 0; i < NumArgOperands; ++i)
1702       SC.Add(I.getArgOperand(i));
1703     SC.Done(&I);
1704
1705     return true;
1706   }
1707
1708   /// \brief Heuristically instrument unknown intrinsics.
1709   ///
1710   /// The main purpose of this code is to do something reasonable with all
1711   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1712   /// We recognize several classes of intrinsics by their argument types and
1713   /// ModRefBehaviour and apply special intrumentation when we are reasonably
1714   /// sure that we know what the intrinsic does.
1715   ///
1716   /// We special-case intrinsics where this approach fails. See llvm.bswap
1717   /// handling as an example of that.
1718   bool handleUnknownIntrinsic(IntrinsicInst &I) {
1719     unsigned NumArgOperands = I.getNumArgOperands();
1720     if (NumArgOperands == 0)
1721       return false;
1722
1723     Intrinsic::ID iid = I.getIntrinsicID();
1724     IntrinsicKind IK = getIntrinsicKind(iid);
1725     bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1726     bool WritesMemory = IK == IK_WritesMemory;
1727     assert(!(OnlyReadsMemory && WritesMemory));
1728
1729     if (NumArgOperands == 2 &&
1730         I.getArgOperand(0)->getType()->isPointerTy() &&
1731         I.getArgOperand(1)->getType()->isVectorTy() &&
1732         I.getType()->isVoidTy() &&
1733         WritesMemory) {
1734       // This looks like a vector store.
1735       return handleVectorStoreIntrinsic(I);
1736     }
1737
1738     if (NumArgOperands == 1 &&
1739         I.getArgOperand(0)->getType()->isPointerTy() &&
1740         I.getType()->isVectorTy() &&
1741         OnlyReadsMemory) {
1742       // This looks like a vector load.
1743       return handleVectorLoadIntrinsic(I);
1744     }
1745
1746     if (!OnlyReadsMemory && !WritesMemory)
1747       if (maybeHandleSimpleNomemIntrinsic(I))
1748         return true;
1749
1750     // FIXME: detect and handle SSE maskstore/maskload
1751     return false;
1752   }
1753
1754   void handleBswap(IntrinsicInst &I) {
1755     IRBuilder<> IRB(&I);
1756     Value *Op = I.getArgOperand(0);
1757     Type *OpType = Op->getType();
1758     Function *BswapFunc = Intrinsic::getDeclaration(
1759       F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1760     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1761     setOrigin(&I, getOrigin(Op));
1762   }
1763
1764   // \brief Instrument vector convert instrinsic.
1765   //
1766   // This function instruments intrinsics like cvtsi2ss:
1767   // %Out = int_xxx_cvtyyy(%ConvertOp)
1768   // or
1769   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
1770   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
1771   // number \p Out elements, and (if has 2 arguments) copies the rest of the
1772   // elements from \p CopyOp.
1773   // In most cases conversion involves floating-point value which may trigger a
1774   // hardware exception when not fully initialized. For this reason we require
1775   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
1776   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
1777   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
1778   // return a fully initialized value.
1779   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
1780     IRBuilder<> IRB(&I);
1781     Value *CopyOp, *ConvertOp;
1782
1783     switch (I.getNumArgOperands()) {
1784     case 2:
1785       CopyOp = I.getArgOperand(0);
1786       ConvertOp = I.getArgOperand(1);
1787       break;
1788     case 1:
1789       ConvertOp = I.getArgOperand(0);
1790       CopyOp = NULL;
1791       break;
1792     default:
1793       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
1794     }
1795
1796     // The first *NumUsedElements* elements of ConvertOp are converted to the
1797     // same number of output elements. The rest of the output is copied from
1798     // CopyOp, or (if not available) filled with zeroes.
1799     // Combine shadow for elements of ConvertOp that are used in this operation,
1800     // and insert a check.
1801     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
1802     // int->any conversion.
1803     Value *ConvertShadow = getShadow(ConvertOp);
1804     Value *AggShadow = 0;
1805     if (ConvertOp->getType()->isVectorTy()) {
1806       AggShadow = IRB.CreateExtractElement(
1807           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
1808       for (int i = 1; i < NumUsedElements; ++i) {
1809         Value *MoreShadow = IRB.CreateExtractElement(
1810             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
1811         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
1812       }
1813     } else {
1814       AggShadow = ConvertShadow;
1815     }
1816     assert(AggShadow->getType()->isIntegerTy());
1817     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
1818
1819     // Build result shadow by zero-filling parts of CopyOp shadow that come from
1820     // ConvertOp.
1821     if (CopyOp) {
1822       assert(CopyOp->getType() == I.getType());
1823       assert(CopyOp->getType()->isVectorTy());
1824       Value *ResultShadow = getShadow(CopyOp);
1825       Type *EltTy = ResultShadow->getType()->getVectorElementType();
1826       for (int i = 0; i < NumUsedElements; ++i) {
1827         ResultShadow = IRB.CreateInsertElement(
1828             ResultShadow, ConstantInt::getNullValue(EltTy),
1829             ConstantInt::get(IRB.getInt32Ty(), i));
1830       }
1831       setShadow(&I, ResultShadow);
1832       setOrigin(&I, getOrigin(CopyOp));
1833     } else {
1834       setShadow(&I, getCleanShadow(&I));
1835     }
1836   }
1837
1838   // Given a scalar or vector, extract lower 64 bits (or less), and return all
1839   // zeroes if it is zero, and all ones otherwise.
1840   Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
1841     if (S->getType()->isVectorTy())
1842       S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
1843     assert(S->getType()->getPrimitiveSizeInBits() <= 64);
1844     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1845     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
1846   }
1847
1848   Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
1849     Type *T = S->getType();
1850     assert(T->isVectorTy());
1851     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1852     return IRB.CreateSExt(S2, T);
1853   }
1854
1855   // \brief Instrument vector shift instrinsic.
1856   //
1857   // This function instruments intrinsics like int_x86_avx2_psll_w.
1858   // Intrinsic shifts %In by %ShiftSize bits.
1859   // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
1860   // size, and the rest is ignored. Behavior is defined even if shift size is
1861   // greater than register (or field) width.
1862   void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
1863     assert(I.getNumArgOperands() == 2);
1864     IRBuilder<> IRB(&I);
1865     // If any of the S2 bits are poisoned, the whole thing is poisoned.
1866     // Otherwise perform the same shift on S1.
1867     Value *S1 = getShadow(&I, 0);
1868     Value *S2 = getShadow(&I, 1);
1869     Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
1870                              : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
1871     Value *V1 = I.getOperand(0);
1872     Value *V2 = I.getOperand(1);
1873     Value *Shift = IRB.CreateCall2(I.getCalledValue(),
1874                                    IRB.CreateBitCast(S1, V1->getType()), V2);
1875     Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
1876     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1877     setOriginForNaryOp(I);
1878   }
1879
1880   void visitIntrinsicInst(IntrinsicInst &I) {
1881     switch (I.getIntrinsicID()) {
1882     case llvm::Intrinsic::bswap:
1883       handleBswap(I);
1884       break;
1885     case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
1886     case llvm::Intrinsic::x86_avx512_cvtsd2usi:
1887     case llvm::Intrinsic::x86_avx512_cvtss2usi64:
1888     case llvm::Intrinsic::x86_avx512_cvtss2usi:
1889     case llvm::Intrinsic::x86_avx512_cvttss2usi64:
1890     case llvm::Intrinsic::x86_avx512_cvttss2usi:
1891     case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
1892     case llvm::Intrinsic::x86_avx512_cvttsd2usi:
1893     case llvm::Intrinsic::x86_avx512_cvtusi2sd:
1894     case llvm::Intrinsic::x86_avx512_cvtusi2ss:
1895     case llvm::Intrinsic::x86_avx512_cvtusi642sd:
1896     case llvm::Intrinsic::x86_avx512_cvtusi642ss:
1897     case llvm::Intrinsic::x86_sse2_cvtsd2si64:
1898     case llvm::Intrinsic::x86_sse2_cvtsd2si:
1899     case llvm::Intrinsic::x86_sse2_cvtsd2ss:
1900     case llvm::Intrinsic::x86_sse2_cvtsi2sd:
1901     case llvm::Intrinsic::x86_sse2_cvtsi642sd:
1902     case llvm::Intrinsic::x86_sse2_cvtss2sd:
1903     case llvm::Intrinsic::x86_sse2_cvttsd2si64:
1904     case llvm::Intrinsic::x86_sse2_cvttsd2si:
1905     case llvm::Intrinsic::x86_sse_cvtsi2ss:
1906     case llvm::Intrinsic::x86_sse_cvtsi642ss:
1907     case llvm::Intrinsic::x86_sse_cvtss2si64:
1908     case llvm::Intrinsic::x86_sse_cvtss2si:
1909     case llvm::Intrinsic::x86_sse_cvttss2si64:
1910     case llvm::Intrinsic::x86_sse_cvttss2si:
1911       handleVectorConvertIntrinsic(I, 1);
1912       break;
1913     case llvm::Intrinsic::x86_sse2_cvtdq2pd:
1914     case llvm::Intrinsic::x86_sse2_cvtps2pd:
1915     case llvm::Intrinsic::x86_sse_cvtps2pi:
1916     case llvm::Intrinsic::x86_sse_cvttps2pi:
1917       handleVectorConvertIntrinsic(I, 2);
1918       break;
1919     case llvm::Intrinsic::x86_avx512_psll_dq:
1920     case llvm::Intrinsic::x86_avx512_psrl_dq:
1921     case llvm::Intrinsic::x86_avx2_psll_w:
1922     case llvm::Intrinsic::x86_avx2_psll_d:
1923     case llvm::Intrinsic::x86_avx2_psll_q:
1924     case llvm::Intrinsic::x86_avx2_pslli_w:
1925     case llvm::Intrinsic::x86_avx2_pslli_d:
1926     case llvm::Intrinsic::x86_avx2_pslli_q:
1927     case llvm::Intrinsic::x86_avx2_psll_dq:
1928     case llvm::Intrinsic::x86_avx2_psrl_w:
1929     case llvm::Intrinsic::x86_avx2_psrl_d:
1930     case llvm::Intrinsic::x86_avx2_psrl_q:
1931     case llvm::Intrinsic::x86_avx2_psra_w:
1932     case llvm::Intrinsic::x86_avx2_psra_d:
1933     case llvm::Intrinsic::x86_avx2_psrli_w:
1934     case llvm::Intrinsic::x86_avx2_psrli_d:
1935     case llvm::Intrinsic::x86_avx2_psrli_q:
1936     case llvm::Intrinsic::x86_avx2_psrai_w:
1937     case llvm::Intrinsic::x86_avx2_psrai_d:
1938     case llvm::Intrinsic::x86_avx2_psrl_dq:
1939     case llvm::Intrinsic::x86_sse2_psll_w:
1940     case llvm::Intrinsic::x86_sse2_psll_d:
1941     case llvm::Intrinsic::x86_sse2_psll_q:
1942     case llvm::Intrinsic::x86_sse2_pslli_w:
1943     case llvm::Intrinsic::x86_sse2_pslli_d:
1944     case llvm::Intrinsic::x86_sse2_pslli_q:
1945     case llvm::Intrinsic::x86_sse2_psll_dq:
1946     case llvm::Intrinsic::x86_sse2_psrl_w:
1947     case llvm::Intrinsic::x86_sse2_psrl_d:
1948     case llvm::Intrinsic::x86_sse2_psrl_q:
1949     case llvm::Intrinsic::x86_sse2_psra_w:
1950     case llvm::Intrinsic::x86_sse2_psra_d:
1951     case llvm::Intrinsic::x86_sse2_psrli_w:
1952     case llvm::Intrinsic::x86_sse2_psrli_d:
1953     case llvm::Intrinsic::x86_sse2_psrli_q:
1954     case llvm::Intrinsic::x86_sse2_psrai_w:
1955     case llvm::Intrinsic::x86_sse2_psrai_d:
1956     case llvm::Intrinsic::x86_sse2_psrl_dq:
1957     case llvm::Intrinsic::x86_mmx_psll_w:
1958     case llvm::Intrinsic::x86_mmx_psll_d:
1959     case llvm::Intrinsic::x86_mmx_psll_q:
1960     case llvm::Intrinsic::x86_mmx_pslli_w:
1961     case llvm::Intrinsic::x86_mmx_pslli_d:
1962     case llvm::Intrinsic::x86_mmx_pslli_q:
1963     case llvm::Intrinsic::x86_mmx_psrl_w:
1964     case llvm::Intrinsic::x86_mmx_psrl_d:
1965     case llvm::Intrinsic::x86_mmx_psrl_q:
1966     case llvm::Intrinsic::x86_mmx_psra_w:
1967     case llvm::Intrinsic::x86_mmx_psra_d:
1968     case llvm::Intrinsic::x86_mmx_psrli_w:
1969     case llvm::Intrinsic::x86_mmx_psrli_d:
1970     case llvm::Intrinsic::x86_mmx_psrli_q:
1971     case llvm::Intrinsic::x86_mmx_psrai_w:
1972     case llvm::Intrinsic::x86_mmx_psrai_d:
1973       handleVectorShiftIntrinsic(I, /* Variable */ false);
1974       break;
1975     case llvm::Intrinsic::x86_avx2_psllv_d:
1976     case llvm::Intrinsic::x86_avx2_psllv_d_256:
1977     case llvm::Intrinsic::x86_avx2_psllv_q:
1978     case llvm::Intrinsic::x86_avx2_psllv_q_256:
1979     case llvm::Intrinsic::x86_avx2_psrlv_d:
1980     case llvm::Intrinsic::x86_avx2_psrlv_d_256:
1981     case llvm::Intrinsic::x86_avx2_psrlv_q:
1982     case llvm::Intrinsic::x86_avx2_psrlv_q_256:
1983     case llvm::Intrinsic::x86_avx2_psrav_d:
1984     case llvm::Intrinsic::x86_avx2_psrav_d_256:
1985       handleVectorShiftIntrinsic(I, /* Variable */ true);
1986       break;
1987
1988     // Byte shifts are not implemented.
1989     // case llvm::Intrinsic::x86_avx512_psll_dq_bs:
1990     // case llvm::Intrinsic::x86_avx512_psrl_dq_bs:
1991     // case llvm::Intrinsic::x86_avx2_psll_dq_bs:
1992     // case llvm::Intrinsic::x86_avx2_psrl_dq_bs:
1993     // case llvm::Intrinsic::x86_sse2_psll_dq_bs:
1994     // case llvm::Intrinsic::x86_sse2_psrl_dq_bs:
1995
1996     default:
1997       if (!handleUnknownIntrinsic(I))
1998         visitInstruction(I);
1999       break;
2000     }
2001   }
2002
2003   void visitCallSite(CallSite CS) {
2004     Instruction &I = *CS.getInstruction();
2005     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2006     if (CS.isCall()) {
2007       CallInst *Call = cast<CallInst>(&I);
2008
2009       // For inline asm, do the usual thing: check argument shadow and mark all
2010       // outputs as clean. Note that any side effects of the inline asm that are
2011       // not immediately visible in its constraints are not handled.
2012       if (Call->isInlineAsm()) {
2013         visitInstruction(I);
2014         return;
2015       }
2016
2017       // Allow only tail calls with the same types, otherwise
2018       // we may have a false positive: shadow for a non-void RetVal
2019       // will get propagated to a void RetVal.
2020       if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
2021         Call->setTailCall(false);
2022
2023       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
2024
2025       // We are going to insert code that relies on the fact that the callee
2026       // will become a non-readonly function after it is instrumented by us. To
2027       // prevent this code from being optimized out, mark that function
2028       // non-readonly in advance.
2029       if (Function *Func = Call->getCalledFunction()) {
2030         // Clear out readonly/readnone attributes.
2031         AttrBuilder B;
2032         B.addAttribute(Attribute::ReadOnly)
2033           .addAttribute(Attribute::ReadNone);
2034         Func->removeAttributes(AttributeSet::FunctionIndex,
2035                                AttributeSet::get(Func->getContext(),
2036                                                  AttributeSet::FunctionIndex,
2037                                                  B));
2038       }
2039     }
2040     IRBuilder<> IRB(&I);
2041
2042     if (MS.WrapIndirectCalls && !CS.getCalledFunction())
2043       IndirectCallList.push_back(CS);
2044
2045     unsigned ArgOffset = 0;
2046     DEBUG(dbgs() << "  CallSite: " << I << "\n");
2047     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2048          ArgIt != End; ++ArgIt) {
2049       Value *A = *ArgIt;
2050       unsigned i = ArgIt - CS.arg_begin();
2051       if (!A->getType()->isSized()) {
2052         DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2053         continue;
2054       }
2055       unsigned Size = 0;
2056       Value *Store = 0;
2057       // Compute the Shadow for arg even if it is ByVal, because
2058       // in that case getShadow() will copy the actual arg shadow to
2059       // __msan_param_tls.
2060       Value *ArgShadow = getShadow(A);
2061       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2062       DEBUG(dbgs() << "  Arg#" << i << ": " << *A <<
2063             " Shadow: " << *ArgShadow << "\n");
2064       if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
2065         assert(A->getType()->isPointerTy() &&
2066                "ByVal argument is not a pointer!");
2067         Size = MS.DL->getTypeAllocSize(A->getType()->getPointerElementType());
2068         unsigned Alignment = CS.getParamAlignment(i + 1);
2069         Store = IRB.CreateMemCpy(ArgShadowBase,
2070                                  getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2071                                  Size, Alignment);
2072       } else {
2073         Size = MS.DL->getTypeAllocSize(A->getType());
2074         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2075                                        kShadowTLSAlignment);
2076       }
2077       if (MS.TrackOrigins)
2078         IRB.CreateStore(getOrigin(A),
2079                         getOriginPtrForArgument(A, IRB, ArgOffset));
2080       (void)Store;
2081       assert(Size != 0 && Store != 0);
2082       DEBUG(dbgs() << "  Param:" << *Store << "\n");
2083       ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
2084     }
2085     DEBUG(dbgs() << "  done with call args\n");
2086
2087     FunctionType *FT =
2088       cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
2089     if (FT->isVarArg()) {
2090       VAHelper->visitCallSite(CS, IRB);
2091     }
2092
2093     // Now, get the shadow for the RetVal.
2094     if (!I.getType()->isSized()) return;
2095     IRBuilder<> IRBBefore(&I);
2096     // Until we have full dynamic coverage, make sure the retval shadow is 0.
2097     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
2098     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
2099     Instruction *NextInsn = 0;
2100     if (CS.isCall()) {
2101       NextInsn = I.getNextNode();
2102     } else {
2103       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2104       if (!NormalDest->getSinglePredecessor()) {
2105         // FIXME: this case is tricky, so we are just conservative here.
2106         // Perhaps we need to split the edge between this BB and NormalDest,
2107         // but a naive attempt to use SplitEdge leads to a crash.
2108         setShadow(&I, getCleanShadow(&I));
2109         setOrigin(&I, getCleanOrigin());
2110         return;
2111       }
2112       NextInsn = NormalDest->getFirstInsertionPt();
2113       assert(NextInsn &&
2114              "Could not find insertion point for retval shadow load");
2115     }
2116     IRBuilder<> IRBAfter(NextInsn);
2117     Value *RetvalShadow =
2118       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2119                                  kShadowTLSAlignment, "_msret");
2120     setShadow(&I, RetvalShadow);
2121     if (MS.TrackOrigins)
2122       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2123   }
2124
2125   void visitReturnInst(ReturnInst &I) {
2126     IRBuilder<> IRB(&I);
2127     Value *RetVal = I.getReturnValue();
2128     if (!RetVal) return;
2129     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2130     if (CheckReturnValue) {
2131       insertShadowCheck(RetVal, &I);
2132       Value *Shadow = getCleanShadow(RetVal);
2133       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2134     } else {
2135       Value *Shadow = getShadow(RetVal);
2136       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2137       // FIXME: make it conditional if ClStoreCleanOrigin==0
2138       if (MS.TrackOrigins)
2139         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2140     }
2141   }
2142
2143   void visitPHINode(PHINode &I) {
2144     IRBuilder<> IRB(&I);
2145     ShadowPHINodes.push_back(&I);
2146     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2147                                 "_msphi_s"));
2148     if (MS.TrackOrigins)
2149       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2150                                   "_msphi_o"));
2151   }
2152
2153   void visitAllocaInst(AllocaInst &I) {
2154     setShadow(&I, getCleanShadow(&I));
2155     IRBuilder<> IRB(I.getNextNode());
2156     uint64_t Size = MS.DL->getTypeAllocSize(I.getAllocatedType());
2157     if (PoisonStack && ClPoisonStackWithCall) {
2158       IRB.CreateCall2(MS.MsanPoisonStackFn,
2159                       IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2160                       ConstantInt::get(MS.IntptrTy, Size));
2161     } else {
2162       Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2163       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2164       IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2165     }
2166
2167     if (PoisonStack && MS.TrackOrigins) {
2168       setOrigin(&I, getCleanOrigin());
2169       SmallString<2048> StackDescriptionStorage;
2170       raw_svector_ostream StackDescription(StackDescriptionStorage);
2171       // We create a string with a description of the stack allocation and
2172       // pass it into __msan_set_alloca_origin.
2173       // It will be printed by the run-time if stack-originated UMR is found.
2174       // The first 4 bytes of the string are set to '----' and will be replaced
2175       // by __msan_va_arg_overflow_size_tls at the first call.
2176       StackDescription << "----" << I.getName() << "@" << F.getName();
2177       Value *Descr =
2178           createPrivateNonConstGlobalForString(*F.getParent(),
2179                                                StackDescription.str());
2180
2181       IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
2182                       IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2183                       ConstantInt::get(MS.IntptrTy, Size),
2184                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2185                       IRB.CreatePointerCast(&F, MS.IntptrTy));
2186     }
2187   }
2188
2189   void visitSelectInst(SelectInst& I) {
2190     IRBuilder<> IRB(&I);
2191     // a = select b, c, d
2192     Value *B = I.getCondition();
2193     Value *C = I.getTrueValue();
2194     Value *D = I.getFalseValue();
2195     Value *Sb = getShadow(B);
2196     Value *Sc = getShadow(C);
2197     Value *Sd = getShadow(D);
2198
2199     // Result shadow if condition shadow is 0.
2200     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2201     Value *Sa1;
2202     if (I.getType()->isAggregateType()) {
2203       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2204       // an extra "select". This results in much more compact IR.
2205       // Sa = select Sb, poisoned, (select b, Sc, Sd)
2206       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
2207     } else {
2208       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2209       // If Sb (condition is poisoned), look for bits in c and d that are equal
2210       // and both unpoisoned.
2211       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2212
2213       // Cast arguments to shadow-compatible type.
2214       C = CreateAppToShadowCast(IRB, C);
2215       D = CreateAppToShadowCast(IRB, D);
2216
2217       // Result shadow if condition shadow is 1.
2218       Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
2219     }
2220     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2221     setShadow(&I, Sa);
2222     if (MS.TrackOrigins) {
2223       // Origins are always i32, so any vector conditions must be flattened.
2224       // FIXME: consider tracking vector origins for app vectors?
2225       if (B->getType()->isVectorTy()) {
2226         Type *FlatTy = getShadowTyNoVec(B->getType());
2227         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
2228                                 ConstantInt::getNullValue(FlatTy));
2229         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
2230                                       ConstantInt::getNullValue(FlatTy));
2231       }
2232       // a = select b, c, d
2233       // Oa = Sb ? Ob : (b ? Oc : Od)
2234       setOrigin(&I, IRB.CreateSelect(
2235                         Sb, getOrigin(I.getCondition()),
2236                         IRB.CreateSelect(B, getOrigin(C), getOrigin(D))));
2237     }
2238   }
2239
2240   void visitLandingPadInst(LandingPadInst &I) {
2241     // Do nothing.
2242     // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2243     setShadow(&I, getCleanShadow(&I));
2244     setOrigin(&I, getCleanOrigin());
2245   }
2246
2247   void visitGetElementPtrInst(GetElementPtrInst &I) {
2248     handleShadowOr(I);
2249   }
2250
2251   void visitExtractValueInst(ExtractValueInst &I) {
2252     IRBuilder<> IRB(&I);
2253     Value *Agg = I.getAggregateOperand();
2254     DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
2255     Value *AggShadow = getShadow(Agg);
2256     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2257     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2258     DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
2259     setShadow(&I, ResShadow);
2260     setOriginForNaryOp(I);
2261   }
2262
2263   void visitInsertValueInst(InsertValueInst &I) {
2264     IRBuilder<> IRB(&I);
2265     DEBUG(dbgs() << "InsertValue:  " << I << "\n");
2266     Value *AggShadow = getShadow(I.getAggregateOperand());
2267     Value *InsShadow = getShadow(I.getInsertedValueOperand());
2268     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2269     DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
2270     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2271     DEBUG(dbgs() << "   Res:        " << *Res << "\n");
2272     setShadow(&I, Res);
2273     setOriginForNaryOp(I);
2274   }
2275
2276   void dumpInst(Instruction &I) {
2277     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2278       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2279     } else {
2280       errs() << "ZZZ " << I.getOpcodeName() << "\n";
2281     }
2282     errs() << "QQQ " << I << "\n";
2283   }
2284
2285   void visitResumeInst(ResumeInst &I) {
2286     DEBUG(dbgs() << "Resume: " << I << "\n");
2287     // Nothing to do here.
2288   }
2289
2290   void visitInstruction(Instruction &I) {
2291     // Everything else: stop propagating and check for poisoned shadow.
2292     if (ClDumpStrictInstructions)
2293       dumpInst(I);
2294     DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2295     for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2296       insertShadowCheck(I.getOperand(i), &I);
2297     setShadow(&I, getCleanShadow(&I));
2298     setOrigin(&I, getCleanOrigin());
2299   }
2300 };
2301
2302 /// \brief AMD64-specific implementation of VarArgHelper.
2303 struct VarArgAMD64Helper : public VarArgHelper {
2304   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2305   // See a comment in visitCallSite for more details.
2306   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
2307   static const unsigned AMD64FpEndOffset = 176;
2308
2309   Function &F;
2310   MemorySanitizer &MS;
2311   MemorySanitizerVisitor &MSV;
2312   Value *VAArgTLSCopy;
2313   Value *VAArgOverflowSize;
2314
2315   SmallVector<CallInst*, 16> VAStartInstrumentationList;
2316
2317   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2318                     MemorySanitizerVisitor &MSV)
2319     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
2320
2321   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2322
2323   ArgKind classifyArgument(Value* arg) {
2324     // A very rough approximation of X86_64 argument classification rules.
2325     Type *T = arg->getType();
2326     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2327       return AK_FloatingPoint;
2328     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2329       return AK_GeneralPurpose;
2330     if (T->isPointerTy())
2331       return AK_GeneralPurpose;
2332     return AK_Memory;
2333   }
2334
2335   // For VarArg functions, store the argument shadow in an ABI-specific format
2336   // that corresponds to va_list layout.
2337   // We do this because Clang lowers va_arg in the frontend, and this pass
2338   // only sees the low level code that deals with va_list internals.
2339   // A much easier alternative (provided that Clang emits va_arg instructions)
2340   // would have been to associate each live instance of va_list with a copy of
2341   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2342   // order.
2343   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2344     unsigned GpOffset = 0;
2345     unsigned FpOffset = AMD64GpEndOffset;
2346     unsigned OverflowOffset = AMD64FpEndOffset;
2347     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2348          ArgIt != End; ++ArgIt) {
2349       Value *A = *ArgIt;
2350       unsigned ArgNo = CS.getArgumentNo(ArgIt);
2351       bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2352       if (IsByVal) {
2353         // ByVal arguments always go to the overflow area.
2354         assert(A->getType()->isPointerTy());
2355         Type *RealTy = A->getType()->getPointerElementType();
2356         uint64_t ArgSize = MS.DL->getTypeAllocSize(RealTy);
2357         Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
2358         OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
2359         IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2360                          ArgSize, kShadowTLSAlignment);
2361       } else {
2362         ArgKind AK = classifyArgument(A);
2363         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2364           AK = AK_Memory;
2365         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2366           AK = AK_Memory;
2367         Value *Base;
2368         switch (AK) {
2369           case AK_GeneralPurpose:
2370             Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2371             GpOffset += 8;
2372             break;
2373           case AK_FloatingPoint:
2374             Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2375             FpOffset += 16;
2376             break;
2377           case AK_Memory:
2378             uint64_t ArgSize = MS.DL->getTypeAllocSize(A->getType());
2379             Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2380             OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
2381         }
2382         IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2383       }
2384     }
2385     Constant *OverflowSize =
2386       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2387     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2388   }
2389
2390   /// \brief Compute the shadow address for a given va_arg.
2391   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2392                                    int ArgOffset) {
2393     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2394     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2395     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2396                               "_msarg");
2397   }
2398
2399   void visitVAStartInst(VAStartInst &I) override {
2400     IRBuilder<> IRB(&I);
2401     VAStartInstrumentationList.push_back(&I);
2402     Value *VAListTag = I.getArgOperand(0);
2403     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2404
2405     // Unpoison the whole __va_list_tag.
2406     // FIXME: magic ABI constants.
2407     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2408                      /* size */24, /* alignment */8, false);
2409   }
2410
2411   void visitVACopyInst(VACopyInst &I) override {
2412     IRBuilder<> IRB(&I);
2413     Value *VAListTag = I.getArgOperand(0);
2414     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2415
2416     // Unpoison the whole __va_list_tag.
2417     // FIXME: magic ABI constants.
2418     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2419                      /* size */24, /* alignment */8, false);
2420   }
2421
2422   void finalizeInstrumentation() override {
2423     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2424            "finalizeInstrumentation called twice");
2425     if (!VAStartInstrumentationList.empty()) {
2426       // If there is a va_start in this function, make a backup copy of
2427       // va_arg_tls somewhere in the function entry block.
2428       IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2429       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2430       Value *CopySize =
2431         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2432                       VAArgOverflowSize);
2433       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2434       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2435     }
2436
2437     // Instrument va_start.
2438     // Copy va_list shadow from the backup copy of the TLS contents.
2439     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2440       CallInst *OrigInst = VAStartInstrumentationList[i];
2441       IRBuilder<> IRB(OrigInst->getNextNode());
2442       Value *VAListTag = OrigInst->getArgOperand(0);
2443
2444       Value *RegSaveAreaPtrPtr =
2445         IRB.CreateIntToPtr(
2446           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2447                         ConstantInt::get(MS.IntptrTy, 16)),
2448           Type::getInt64PtrTy(*MS.C));
2449       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2450       Value *RegSaveAreaShadowPtr =
2451         MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2452       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2453                        AMD64FpEndOffset, 16);
2454
2455       Value *OverflowArgAreaPtrPtr =
2456         IRB.CreateIntToPtr(
2457           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2458                         ConstantInt::get(MS.IntptrTy, 8)),
2459           Type::getInt64PtrTy(*MS.C));
2460       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2461       Value *OverflowArgAreaShadowPtr =
2462         MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2463       Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
2464       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2465     }
2466   }
2467 };
2468
2469 /// \brief A no-op implementation of VarArgHelper.
2470 struct VarArgNoOpHelper : public VarArgHelper {
2471   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2472                    MemorySanitizerVisitor &MSV) {}
2473
2474   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
2475
2476   void visitVAStartInst(VAStartInst &I) override {}
2477
2478   void visitVACopyInst(VACopyInst &I) override {}
2479
2480   void finalizeInstrumentation() override {}
2481 };
2482
2483 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
2484                                  MemorySanitizerVisitor &Visitor) {
2485   // VarArg handling is only implemented on AMD64. False positives are possible
2486   // on other platforms.
2487   llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2488   if (TargetTriple.getArch() == llvm::Triple::x86_64)
2489     return new VarArgAMD64Helper(Func, Msan, Visitor);
2490   else
2491     return new VarArgNoOpHelper(Func, Msan, Visitor);
2492 }
2493
2494 }  // namespace
2495
2496 bool MemorySanitizer::runOnFunction(Function &F) {
2497   MemorySanitizerVisitor Visitor(F, *this);
2498
2499   // Clear out readonly/readnone attributes.
2500   AttrBuilder B;
2501   B.addAttribute(Attribute::ReadOnly)
2502     .addAttribute(Attribute::ReadNone);
2503   F.removeAttributes(AttributeSet::FunctionIndex,
2504                      AttributeSet::get(F.getContext(),
2505                                        AttributeSet::FunctionIndex, B));
2506
2507   return Visitor.runOnFunction();
2508 }