blob: 1cc949da5673011a63aba47c5030934823aad7b1 [file] [log] [blame]
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001//===-- 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
48#define DEBUG_TYPE "msan"
49
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include "llvm/Transforms/Instrumentation.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000051#include "BlackList.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000052#include "llvm/ADT/DepthFirstIterator.h"
53#include "llvm/ADT/SmallString.h"
54#include "llvm/ADT/SmallVector.h"
55#include "llvm/ADT/ValueMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/DataLayout.h"
57#include "llvm/Function.h"
58#include "llvm/IRBuilder.h"
59#include "llvm/InlineAsm.h"
60#include "llvm/InstVisitor.h"
61#include "llvm/IntrinsicInst.h"
62#include "llvm/LLVMContext.h"
63#include "llvm/MDBuilder.h"
64#include "llvm/Module.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000065#include "llvm/Support/CommandLine.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/Debug.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000068#include "llvm/Support/raw_ostream.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000069#include "llvm/Transforms/Utils/BasicBlockUtils.h"
70#include "llvm/Transforms/Utils/ModuleUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000071#include "llvm/Type.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000072
73using namespace llvm;
74
75static const uint64_t kShadowMask32 = 1ULL << 31;
76static const uint64_t kShadowMask64 = 1ULL << 46;
77static const uint64_t kOriginOffset32 = 1ULL << 30;
78static const uint64_t kOriginOffset64 = 1ULL << 45;
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +000079static const uint64_t kShadowTLSAlignment = 8;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000080
81// This is an important flag that makes the reports much more
82// informative at the cost of greater slowdown. Not fully implemented
83// yet.
84// FIXME: this should be a top-level clang flag, e.g.
85// -fmemory-sanitizer-full.
86static cl::opt<bool> ClTrackOrigins("msan-track-origins",
87 cl::desc("Track origins (allocation sites) of poisoned memory"),
88 cl::Hidden, cl::init(false));
89static cl::opt<bool> ClKeepGoing("msan-keep-going",
90 cl::desc("keep going after reporting a UMR"),
91 cl::Hidden, cl::init(false));
92static cl::opt<bool> ClPoisonStack("msan-poison-stack",
93 cl::desc("poison uninitialized stack variables"),
94 cl::Hidden, cl::init(true));
95static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
96 cl::desc("poison uninitialized stack variables with a call"),
97 cl::Hidden, cl::init(false));
98static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
99 cl::desc("poison uninitialized stack variables with the given patter"),
100 cl::Hidden, cl::init(0xff));
101
102static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
103 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
104 cl::Hidden, cl::init(true));
105
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000106static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
107 cl::desc("store origin for clean (fully initialized) values"),
108 cl::Hidden, cl::init(false));
109
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000110// This flag controls whether we check the shadow of the address
111// operand of load or store. Such bugs are very rare, since load from
112// a garbage address typically results in SEGV, but still happen
113// (e.g. only lower bits of address are garbage, or the access happens
114// early at program startup where malloc-ed memory is more likely to
115// be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
116static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
117 cl::desc("report accesses through a pointer which has poisoned shadow"),
118 cl::Hidden, cl::init(true));
119
120static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
121 cl::desc("print out instructions with default strict semantics"),
122 cl::Hidden, cl::init(false));
123
124static cl::opt<std::string> ClBlackListFile("msan-blacklist",
125 cl::desc("File containing the list of functions where MemorySanitizer "
126 "should not report bugs"), cl::Hidden);
127
128namespace {
129
130/// \brief An instrumentation pass implementing detection of uninitialized
131/// reads.
132///
133/// MemorySanitizer: instrument the code in module to find
134/// uninitialized reads.
135class MemorySanitizer : public FunctionPass {
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000136 public:
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000137 MemorySanitizer() : FunctionPass(ID), TD(0), WarningFn(0) { }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000138 const char *getPassName() const { return "MemorySanitizer"; }
139 bool runOnFunction(Function &F);
140 bool doInitialization(Module &M);
141 static char ID; // Pass identification, replacement for typeid.
142
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000143 private:
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000144 void initializeCallbacks(Module &M);
145
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000146 DataLayout *TD;
147 LLVMContext *C;
148 Type *IntptrTy;
149 Type *OriginTy;
150 /// \brief Thread-local shadow storage for function parameters.
151 GlobalVariable *ParamTLS;
152 /// \brief Thread-local origin storage for function parameters.
153 GlobalVariable *ParamOriginTLS;
154 /// \brief Thread-local shadow storage for function return value.
155 GlobalVariable *RetvalTLS;
156 /// \brief Thread-local origin storage for function return value.
157 GlobalVariable *RetvalOriginTLS;
158 /// \brief Thread-local shadow storage for in-register va_arg function
159 /// parameters (x86_64-specific).
160 GlobalVariable *VAArgTLS;
161 /// \brief Thread-local shadow storage for va_arg overflow area
162 /// (x86_64-specific).
163 GlobalVariable *VAArgOverflowSizeTLS;
164 /// \brief Thread-local space used to pass origin value to the UMR reporting
165 /// function.
166 GlobalVariable *OriginTLS;
167
168 /// \brief The run-time callback to print a warning.
169 Value *WarningFn;
170 /// \brief Run-time helper that copies origin info for a memory range.
171 Value *MsanCopyOriginFn;
172 /// \brief Run-time helper that generates a new origin value for a stack
173 /// allocation.
174 Value *MsanSetAllocaOriginFn;
175 /// \brief Run-time helper that poisons stack on function entry.
176 Value *MsanPoisonStackFn;
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000177 /// \brief MSan runtime replacements for memmove, memcpy and memset.
178 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000179
180 /// \brief Address mask used in application-to-shadow address calculation.
181 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
182 uint64_t ShadowMask;
183 /// \brief Offset of the origin shadow from the "normal" shadow.
184 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
185 uint64_t OriginOffset;
186 /// \brief Branch weights for error reporting.
187 MDNode *ColdCallWeights;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000188 /// \brief Branch weights for origin store.
189 MDNode *OriginStoreWeights;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000190 /// \brief The blacklist.
191 OwningPtr<BlackList> BL;
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000192 /// \brief An empty volatile inline asm that prevents callback merge.
193 InlineAsm *EmptyAsm;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000194
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000195 friend struct MemorySanitizerVisitor;
196 friend struct VarArgAMD64Helper;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000197};
198} // namespace
199
200char MemorySanitizer::ID = 0;
201INITIALIZE_PASS(MemorySanitizer, "msan",
202 "MemorySanitizer: detects uninitialized reads.",
203 false, false)
204
205FunctionPass *llvm::createMemorySanitizerPass() {
206 return new MemorySanitizer();
207}
208
209/// \brief Create a non-const global initialized with the given string.
210///
211/// Creates a writable global for Str so that we can pass it to the
212/// run-time lib. Runtime uses first 4 bytes of the string to store the
213/// frame ID, so the string needs to be mutable.
214static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
215 StringRef Str) {
216 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
217 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
218 GlobalValue::PrivateLinkage, StrConst, "");
219}
220
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000221
222/// \brief Insert extern declaration of runtime-provided functions and globals.
223void MemorySanitizer::initializeCallbacks(Module &M) {
224 // Only do this once.
225 if (WarningFn)
226 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000227
228 IRBuilder<> IRB(*C);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000229 // Create the callback.
230 // FIXME: this function should have "Cold" calling conv,
231 // which is not yet implemented.
232 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
233 : "__msan_warning_noreturn";
234 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
235
236 MsanCopyOriginFn = M.getOrInsertFunction(
237 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
238 IRB.getInt8PtrTy(), IntptrTy, NULL);
239 MsanSetAllocaOriginFn = M.getOrInsertFunction(
240 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
241 IRB.getInt8PtrTy(), NULL);
242 MsanPoisonStackFn = M.getOrInsertFunction(
243 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
244 MemmoveFn = M.getOrInsertFunction(
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000245 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
246 IRB.getInt8PtrTy(), IntptrTy, NULL);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000247 MemcpyFn = M.getOrInsertFunction(
248 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
249 IntptrTy, NULL);
250 MemsetFn = M.getOrInsertFunction(
251 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000252 IntptrTy, NULL);
253
254 // Create globals.
255 RetvalTLS = new GlobalVariable(
256 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
257 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
258 GlobalVariable::GeneralDynamicTLSModel);
259 RetvalOriginTLS = new GlobalVariable(
260 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
261 "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
262
263 ParamTLS = new GlobalVariable(
264 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
265 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
266 GlobalVariable::GeneralDynamicTLSModel);
267 ParamOriginTLS = new GlobalVariable(
268 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
269 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
270
271 VAArgTLS = new GlobalVariable(
272 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
273 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
274 GlobalVariable::GeneralDynamicTLSModel);
275 VAArgOverflowSizeTLS = new GlobalVariable(
276 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
277 "__msan_va_arg_overflow_size_tls", 0,
278 GlobalVariable::GeneralDynamicTLSModel);
279 OriginTLS = new GlobalVariable(
280 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
281 "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000282
283 // We insert an empty inline asm after __msan_report* to avoid callback merge.
284 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
285 StringRef(""), StringRef(""),
286 /*hasSideEffects=*/true);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000287}
288
289/// \brief Module-level initialization.
290///
291/// inserts a call to __msan_init to the module's constructor list.
292bool MemorySanitizer::doInitialization(Module &M) {
293 TD = getAnalysisIfAvailable<DataLayout>();
294 if (!TD)
295 return false;
296 BL.reset(new BlackList(ClBlackListFile));
297 C = &(M.getContext());
298 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
299 switch (PtrSize) {
300 case 64:
301 ShadowMask = kShadowMask64;
302 OriginOffset = kOriginOffset64;
303 break;
304 case 32:
305 ShadowMask = kShadowMask32;
306 OriginOffset = kOriginOffset32;
307 break;
308 default:
309 report_fatal_error("unsupported pointer size");
310 break;
311 }
312
313 IRBuilder<> IRB(*C);
314 IntptrTy = IRB.getIntPtrTy(TD);
315 OriginTy = IRB.getInt32Ty();
316
317 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000318 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000319
320 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
321 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
322 "__msan_init", IRB.getVoidTy(), NULL)), 0);
323
324 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
325 IRB.getInt32(ClTrackOrigins), "__msan_track_origins");
326
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000327 return true;
328}
329
330namespace {
331
332/// \brief A helper class that handles instrumentation of VarArg
333/// functions on a particular platform.
334///
335/// Implementations are expected to insert the instrumentation
336/// necessary to propagate argument shadow through VarArg function
337/// calls. Visit* methods are called during an InstVisitor pass over
338/// the function, and should avoid creating new basic blocks. A new
339/// instance of this class is created for each instrumented function.
340struct VarArgHelper {
341 /// \brief Visit a CallSite.
342 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
343
344 /// \brief Visit a va_start call.
345 virtual void visitVAStartInst(VAStartInst &I) = 0;
346
347 /// \brief Visit a va_copy call.
348 virtual void visitVACopyInst(VACopyInst &I) = 0;
349
350 /// \brief Finalize function instrumentation.
351 ///
352 /// This method is called after visiting all interesting (see above)
353 /// instructions in a function.
354 virtual void finalizeInstrumentation() = 0;
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000355
356 virtual ~VarArgHelper() {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000357};
358
359struct MemorySanitizerVisitor;
360
361VarArgHelper*
362CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
363 MemorySanitizerVisitor &Visitor);
364
365/// This class does all the work for a given function. Store and Load
366/// instructions store and load corresponding shadow and origin
367/// values. Most instructions propagate shadow from arguments to their
368/// return values. Certain instructions (most importantly, BranchInst)
369/// test their argument shadow and print reports (with a runtime call) if it's
370/// non-zero.
371struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
372 Function &F;
373 MemorySanitizer &MS;
374 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
375 ValueMap<Value*, Value*> ShadowMap, OriginMap;
376 bool InsertChecks;
377 OwningPtr<VarArgHelper> VAHelper;
378
379 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
380 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000381 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000382 static const unsigned AMD64FpEndOffset = 176;
383
384 struct ShadowOriginAndInsertPoint {
385 Instruction *Shadow;
386 Instruction *Origin;
387 Instruction *OrigIns;
388 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
389 : Shadow(S), Origin(O), OrigIns(I) { }
390 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
391 };
392 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000393 SmallVector<Instruction*, 16> StoreList;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000394
395 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
396 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
397 InsertChecks = !MS.BL->isIn(F);
398 DEBUG(if (!InsertChecks)
399 dbgs() << "MemorySanitizer is not inserting checks into '"
400 << F.getName() << "'\n");
401 }
402
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000403 void materializeStores() {
404 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
405 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
406
407 IRBuilder<> IRB(&I);
408 Value *Val = I.getValueOperand();
409 Value *Addr = I.getPointerOperand();
410 Value *Shadow = getShadow(Val);
411 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
412
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000413 StoreInst *NewSI =
414 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000415 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
NAKAMURA Takumie0b1b462012-12-06 13:38:00 +0000416 (void)NewSI;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000417 // If the store is volatile, add a check.
418 if (I.isVolatile())
419 insertCheck(Val, &I);
420 if (ClCheckAccessAddress)
421 insertCheck(Addr, &I);
422
423 if (ClTrackOrigins) {
424 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
Evgeniy Stepanov49175b22012-12-14 13:43:11 +0000425 IRB.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRB));
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000426 } else {
427 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
428
429 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
430 // TODO(eugenis): handle non-zero constant shadow by inserting an
431 // unconditional check (can not simply fail compilation as this could
432 // be in the dead code).
433 if (Cst)
434 continue;
435
436 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
437 getCleanShadow(ConvertedShadow), "_mscmp");
438 Instruction *CheckTerm =
Evgeniy Stepanov49175b22012-12-14 13:43:11 +0000439 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
440 MS.OriginStoreWeights);
441 IRBuilder<> IRBNew(CheckTerm);
442 IRBNew.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRBNew));
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000443 }
444 }
445 }
446 }
447
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000448 void materializeChecks() {
449 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
450 Instruction *Shadow = InstrumentationList[i].Shadow;
451 Instruction *OrigIns = InstrumentationList[i].OrigIns;
452 IRBuilder<> IRB(OrigIns);
453 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
454 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
455 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
456 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
457 getCleanShadow(ConvertedShadow), "_mscmp");
458 Instruction *CheckTerm =
459 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
460 /* Unreachable */ !ClKeepGoing,
461 MS.ColdCallWeights);
462
463 IRB.SetInsertPoint(CheckTerm);
464 if (ClTrackOrigins) {
465 Instruction *Origin = InstrumentationList[i].Origin;
466 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
467 MS.OriginTLS);
468 }
469 CallInst *Call = IRB.CreateCall(MS.WarningFn);
470 Call->setDebugLoc(OrigIns->getDebugLoc());
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000471 IRB.CreateCall(MS.EmptyAsm);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000472 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
473 }
474 DEBUG(dbgs() << "DONE:\n" << F);
475 }
476
477 /// \brief Add MemorySanitizer instrumentation to a function.
478 bool runOnFunction() {
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000479 MS.initializeCallbacks(*F.getParent());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000480 if (!MS.TD) return false;
481 // Iterate all BBs in depth-first order and create shadow instructions
482 // for all instructions (where applicable).
483 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
484 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
485 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
486 BasicBlock *BB = *DI;
487 visit(*BB);
488 }
489
490 // Finalize PHI nodes.
491 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
492 PHINode *PN = ShadowPHINodes[i];
493 PHINode *PNS = cast<PHINode>(getShadow(PN));
494 PHINode *PNO = ClTrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
495 size_t NumValues = PN->getNumIncomingValues();
496 for (size_t v = 0; v < NumValues; v++) {
497 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
498 if (PNO)
499 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
500 }
501 }
502
503 VAHelper->finalizeInstrumentation();
504
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000505 // Delayed instrumentation of StoreInst.
Evgeniy Stepanov47ac9ba2012-12-06 11:58:59 +0000506 // This may add new checks to be inserted later.
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000507 materializeStores();
508
509 // Insert shadow value checks.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000510 materializeChecks();
511
512 return true;
513 }
514
515 /// \brief Compute the shadow type that corresponds to a given Value.
516 Type *getShadowTy(Value *V) {
517 return getShadowTy(V->getType());
518 }
519
520 /// \brief Compute the shadow type that corresponds to a given Type.
521 Type *getShadowTy(Type *OrigTy) {
522 if (!OrigTy->isSized()) {
523 return 0;
524 }
525 // For integer type, shadow is the same as the original type.
526 // This may return weird-sized types like i1.
527 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
528 return IT;
529 if (VectorType *VT = dyn_cast<VectorType>(OrigTy))
530 return VectorType::getInteger(VT);
531 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
532 SmallVector<Type*, 4> Elements;
533 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
534 Elements.push_back(getShadowTy(ST->getElementType(i)));
535 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
536 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
537 return Res;
538 }
539 uint32_t TypeSize = MS.TD->getTypeStoreSizeInBits(OrigTy);
540 return IntegerType::get(*MS.C, TypeSize);
541 }
542
543 /// \brief Flatten a vector type.
544 Type *getShadowTyNoVec(Type *ty) {
545 if (VectorType *vt = dyn_cast<VectorType>(ty))
546 return IntegerType::get(*MS.C, vt->getBitWidth());
547 return ty;
548 }
549
550 /// \brief Convert a shadow value to it's flattened variant.
551 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
552 Type *Ty = V->getType();
553 Type *NoVecTy = getShadowTyNoVec(Ty);
554 if (Ty == NoVecTy) return V;
555 return IRB.CreateBitCast(V, NoVecTy);
556 }
557
558 /// \brief Compute the shadow address that corresponds to a given application
559 /// address.
560 ///
561 /// Shadow = Addr & ~ShadowMask.
562 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
563 IRBuilder<> &IRB) {
564 Value *ShadowLong =
565 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
566 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
567 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
568 }
569
570 /// \brief Compute the origin address that corresponds to a given application
571 /// address.
572 ///
573 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000574 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
575 Value *ShadowLong =
576 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000577 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000578 Value *Add =
579 IRB.CreateAdd(ShadowLong,
580 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000581 Value *SecondAnd =
582 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
583 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000584 }
585
586 /// \brief Compute the shadow address for a given function argument.
587 ///
588 /// Shadow = ParamTLS+ArgOffset.
589 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
590 int ArgOffset) {
591 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
592 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
593 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
594 "_msarg");
595 }
596
597 /// \brief Compute the origin address for a given function argument.
598 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
599 int ArgOffset) {
600 if (!ClTrackOrigins) return 0;
601 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
602 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
603 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
604 "_msarg_o");
605 }
606
607 /// \brief Compute the shadow address for a retval.
608 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
609 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
610 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
611 "_msret");
612 }
613
614 /// \brief Compute the origin address for a retval.
615 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
616 // We keep a single origin for the entire retval. Might be too optimistic.
617 return MS.RetvalOriginTLS;
618 }
619
620 /// \brief Set SV to be the shadow value for V.
621 void setShadow(Value *V, Value *SV) {
622 assert(!ShadowMap.count(V) && "Values may only have one shadow");
623 ShadowMap[V] = SV;
624 }
625
626 /// \brief Set Origin to be the origin value for V.
627 void setOrigin(Value *V, Value *Origin) {
628 if (!ClTrackOrigins) return;
629 assert(!OriginMap.count(V) && "Values may only have one origin");
630 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
631 OriginMap[V] = Origin;
632 }
633
634 /// \brief Create a clean shadow value for a given value.
635 ///
636 /// Clean shadow (all zeroes) means all bits of the value are defined
637 /// (initialized).
638 Value *getCleanShadow(Value *V) {
639 Type *ShadowTy = getShadowTy(V);
640 if (!ShadowTy)
641 return 0;
642 return Constant::getNullValue(ShadowTy);
643 }
644
645 /// \brief Create a dirty shadow of a given shadow type.
646 Constant *getPoisonedShadow(Type *ShadowTy) {
647 assert(ShadowTy);
648 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
649 return Constant::getAllOnesValue(ShadowTy);
650 StructType *ST = cast<StructType>(ShadowTy);
651 SmallVector<Constant *, 4> Vals;
652 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
653 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
654 return ConstantStruct::get(ST, Vals);
655 }
656
657 /// \brief Create a clean (zero) origin.
658 Value *getCleanOrigin() {
659 return Constant::getNullValue(MS.OriginTy);
660 }
661
662 /// \brief Get the shadow value for a given Value.
663 ///
664 /// This function either returns the value set earlier with setShadow,
665 /// or extracts if from ParamTLS (for function arguments).
666 Value *getShadow(Value *V) {
667 if (Instruction *I = dyn_cast<Instruction>(V)) {
668 // For instructions the shadow is already stored in the map.
669 Value *Shadow = ShadowMap[V];
670 if (!Shadow) {
671 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000672 (void)I;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000673 assert(Shadow && "No shadow for a value");
674 }
675 return Shadow;
676 }
677 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
678 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
679 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000680 (void)U;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000681 return AllOnes;
682 }
683 if (Argument *A = dyn_cast<Argument>(V)) {
684 // For arguments we compute the shadow on demand and store it in the map.
685 Value **ShadowPtr = &ShadowMap[V];
686 if (*ShadowPtr)
687 return *ShadowPtr;
688 Function *F = A->getParent();
689 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
690 unsigned ArgOffset = 0;
691 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
692 AI != AE; ++AI) {
693 if (!AI->getType()->isSized()) {
694 DEBUG(dbgs() << "Arg is not sized\n");
695 continue;
696 }
697 unsigned Size = AI->hasByValAttr()
698 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
699 : MS.TD->getTypeAllocSize(AI->getType());
700 if (A == AI) {
701 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
702 if (AI->hasByValAttr()) {
703 // ByVal pointer itself has clean shadow. We copy the actual
704 // argument shadow to the underlying memory.
705 Value *Cpy = EntryIRB.CreateMemCpy(
706 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
707 Base, Size, AI->getParamAlignment());
708 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000709 (void)Cpy;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000710 *ShadowPtr = getCleanShadow(V);
711 } else {
712 *ShadowPtr = EntryIRB.CreateLoad(Base);
713 }
714 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
715 **ShadowPtr << "\n");
716 if (ClTrackOrigins) {
717 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
718 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
719 }
720 }
721 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
722 }
723 assert(*ShadowPtr && "Could not find shadow for an argument");
724 return *ShadowPtr;
725 }
726 // For everything else the shadow is zero.
727 return getCleanShadow(V);
728 }
729
730 /// \brief Get the shadow for i-th argument of the instruction I.
731 Value *getShadow(Instruction *I, int i) {
732 return getShadow(I->getOperand(i));
733 }
734
735 /// \brief Get the origin for a value.
736 Value *getOrigin(Value *V) {
737 if (!ClTrackOrigins) return 0;
738 if (isa<Instruction>(V) || isa<Argument>(V)) {
739 Value *Origin = OriginMap[V];
740 if (!Origin) {
741 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
742 Origin = getCleanOrigin();
743 }
744 return Origin;
745 }
746 return getCleanOrigin();
747 }
748
749 /// \brief Get the origin for i-th argument of the instruction I.
750 Value *getOrigin(Instruction *I, int i) {
751 return getOrigin(I->getOperand(i));
752 }
753
754 /// \brief Remember the place where a shadow check should be inserted.
755 ///
756 /// This location will be later instrumented with a check that will print a
757 /// UMR warning in runtime if the value is not fully defined.
758 void insertCheck(Value *Val, Instruction *OrigIns) {
759 assert(Val);
760 if (!InsertChecks) return;
761 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
762 if (!Shadow) return;
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000763#ifndef NDEBUG
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000764 Type *ShadowTy = Shadow->getType();
765 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
766 "Can only insert checks for integer and vector shadow types");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000767#endif
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000768 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
769 InstrumentationList.push_back(
770 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
771 }
772
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000773 // ------------------- Visitors.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000774
775 /// \brief Instrument LoadInst
776 ///
777 /// Loads the corresponding shadow and (optionally) origin.
778 /// Optionally, checks that the load address is fully defined.
779 void visitLoadInst(LoadInst &I) {
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000780 assert(I.getType()->isSized() && "Load type must have size");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000781 IRBuilder<> IRB(&I);
782 Type *ShadowTy = getShadowTy(&I);
783 Value *Addr = I.getPointerOperand();
784 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
Evgeniy Stepanoveeb8b7c2012-11-29 14:05:53 +0000785 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000786
787 if (ClCheckAccessAddress)
788 insertCheck(I.getPointerOperand(), &I);
789
790 if (ClTrackOrigins)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +0000791 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000792 }
793
794 /// \brief Instrument StoreInst
795 ///
796 /// Stores the corresponding shadow and (optionally) origin.
797 /// Optionally, checks that the store address is fully defined.
798 /// Volatile stores check that the value being stored is fully defined.
799 void visitStoreInst(StoreInst &I) {
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000800 StoreList.push_back(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000801 }
802
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +0000803 // Vector manipulation.
804 void visitExtractElementInst(ExtractElementInst &I) {
805 insertCheck(I.getOperand(1), &I);
806 IRBuilder<> IRB(&I);
807 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
808 "_msprop"));
809 setOrigin(&I, getOrigin(&I, 0));
810 }
811
812 void visitInsertElementInst(InsertElementInst &I) {
813 insertCheck(I.getOperand(2), &I);
814 IRBuilder<> IRB(&I);
815 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
816 I.getOperand(2), "_msprop"));
817 setOriginForNaryOp(I);
818 }
819
820 void visitShuffleVectorInst(ShuffleVectorInst &I) {
821 insertCheck(I.getOperand(2), &I);
822 IRBuilder<> IRB(&I);
823 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
824 I.getOperand(2), "_msprop"));
825 setOriginForNaryOp(I);
826 }
827
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000828 // Casts.
829 void visitSExtInst(SExtInst &I) {
830 IRBuilder<> IRB(&I);
831 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
832 setOrigin(&I, getOrigin(&I, 0));
833 }
834
835 void visitZExtInst(ZExtInst &I) {
836 IRBuilder<> IRB(&I);
837 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
838 setOrigin(&I, getOrigin(&I, 0));
839 }
840
841 void visitTruncInst(TruncInst &I) {
842 IRBuilder<> IRB(&I);
843 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
844 setOrigin(&I, getOrigin(&I, 0));
845 }
846
847 void visitBitCastInst(BitCastInst &I) {
848 IRBuilder<> IRB(&I);
849 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
850 setOrigin(&I, getOrigin(&I, 0));
851 }
852
853 void visitPtrToIntInst(PtrToIntInst &I) {
854 IRBuilder<> IRB(&I);
855 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
856 "_msprop_ptrtoint"));
857 setOrigin(&I, getOrigin(&I, 0));
858 }
859
860 void visitIntToPtrInst(IntToPtrInst &I) {
861 IRBuilder<> IRB(&I);
862 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
863 "_msprop_inttoptr"));
864 setOrigin(&I, getOrigin(&I, 0));
865 }
866
867 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
868 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
869 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
870 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
871 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
872 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
873
874 /// \brief Propagate shadow for bitwise AND.
875 ///
876 /// This code is exact, i.e. if, for example, a bit in the left argument
877 /// is defined and 0, then neither the value not definedness of the
878 /// corresponding bit in B don't affect the resulting shadow.
879 void visitAnd(BinaryOperator &I) {
880 IRBuilder<> IRB(&I);
881 // "And" of 0 and a poisoned value results in unpoisoned value.
882 // 1&1 => 1; 0&1 => 0; p&1 => p;
883 // 1&0 => 0; 0&0 => 0; p&0 => 0;
884 // 1&p => p; 0&p => 0; p&p => p;
885 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
886 Value *S1 = getShadow(&I, 0);
887 Value *S2 = getShadow(&I, 1);
888 Value *V1 = I.getOperand(0);
889 Value *V2 = I.getOperand(1);
890 if (V1->getType() != S1->getType()) {
891 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
892 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
893 }
894 Value *S1S2 = IRB.CreateAnd(S1, S2);
895 Value *V1S2 = IRB.CreateAnd(V1, S2);
896 Value *S1V2 = IRB.CreateAnd(S1, V2);
897 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
898 setOriginForNaryOp(I);
899 }
900
901 void visitOr(BinaryOperator &I) {
902 IRBuilder<> IRB(&I);
903 // "Or" of 1 and a poisoned value results in unpoisoned value.
904 // 1|1 => 1; 0|1 => 1; p|1 => 1;
905 // 1|0 => 1; 0|0 => 0; p|0 => p;
906 // 1|p => 1; 0|p => p; p|p => p;
907 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
908 Value *S1 = getShadow(&I, 0);
909 Value *S2 = getShadow(&I, 1);
910 Value *V1 = IRB.CreateNot(I.getOperand(0));
911 Value *V2 = IRB.CreateNot(I.getOperand(1));
912 if (V1->getType() != S1->getType()) {
913 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
914 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
915 }
916 Value *S1S2 = IRB.CreateAnd(S1, S2);
917 Value *V1S2 = IRB.CreateAnd(V1, S2);
918 Value *S1V2 = IRB.CreateAnd(S1, V2);
919 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
920 setOriginForNaryOp(I);
921 }
922
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000923 /// \brief Default propagation of shadow and/or origin.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000924 ///
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000925 /// This class implements the general case of shadow propagation, used in all
926 /// cases where we don't know and/or don't care about what the operation
927 /// actually does. It converts all input shadow values to a common type
928 /// (extending or truncating as necessary), and bitwise OR's them.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000929 ///
930 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
931 /// fully initialized), and less prone to false positives.
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000932 ///
933 /// This class also implements the general case of origin propagation. For a
934 /// Nary operation, result origin is set to the origin of an argument that is
935 /// not entirely initialized. If there is more than one such arguments, the
936 /// rightmost of them is picked. It does not matter which one is picked if all
937 /// arguments are initialized.
938 template <bool CombineShadow>
939 class Combiner {
940 Value *Shadow;
941 Value *Origin;
942 IRBuilder<> &IRB;
943 MemorySanitizerVisitor *MSV;
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000944
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000945 public:
946 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
947 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
948
949 /// \brief Add a pair of shadow and origin values to the mix.
950 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
951 if (CombineShadow) {
952 assert(OpShadow);
953 if (!Shadow)
954 Shadow = OpShadow;
955 else {
956 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
957 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
958 }
959 }
960
961 if (ClTrackOrigins) {
962 assert(OpOrigin);
963 if (!Origin) {
964 Origin = OpOrigin;
965 } else {
966 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
967 Value *Cond = IRB.CreateICmpNE(FlatShadow,
968 MSV->getCleanShadow(FlatShadow));
969 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
970 }
971 }
972 return *this;
973 }
974
975 /// \brief Add an application value to the mix.
976 Combiner &Add(Value *V) {
977 Value *OpShadow = MSV->getShadow(V);
978 Value *OpOrigin = ClTrackOrigins ? MSV->getOrigin(V) : 0;
979 return Add(OpShadow, OpOrigin);
980 }
981
982 /// \brief Set the current combined values as the given instruction's shadow
983 /// and origin.
984 void Done(Instruction *I) {
985 if (CombineShadow) {
986 assert(Shadow);
987 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
988 MSV->setShadow(I, Shadow);
989 }
990 if (ClTrackOrigins) {
991 assert(Origin);
992 MSV->setOrigin(I, Origin);
993 }
994 }
995 };
996
997 typedef Combiner<true> ShadowAndOriginCombiner;
998 typedef Combiner<false> OriginCombiner;
999
1000 /// \brief Propagate origin for arbitrary operation.
1001 void setOriginForNaryOp(Instruction &I) {
1002 if (!ClTrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001003 IRBuilder<> IRB(&I);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001004 OriginCombiner OC(this, IRB);
1005 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1006 OC.Add(OI->get());
1007 OC.Done(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001008 }
1009
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001010 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1011 return Ty->isVectorTy() ?
1012 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1013 Ty->getPrimitiveSizeInBits();
1014 }
1015
1016 /// \brief Cast between two shadow types, extending or truncating as
1017 /// necessary.
1018 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1019 Type *srcTy = V->getType();
1020 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1021 return IRB.CreateIntCast(V, dstTy, false);
1022 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1023 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1024 return IRB.CreateIntCast(V, dstTy, false);
1025 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1026 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1027 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1028 Value *V2 =
1029 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1030 return IRB.CreateBitCast(V2, dstTy);
1031 // TODO: handle struct types.
1032 }
1033
1034 /// \brief Propagate shadow for arbitrary operation.
1035 void handleShadowOr(Instruction &I) {
1036 IRBuilder<> IRB(&I);
1037 ShadowAndOriginCombiner SC(this, IRB);
1038 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1039 SC.Add(OI->get());
1040 SC.Done(&I);
1041 }
1042
1043 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1044 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1045 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1046 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1047 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1048 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1049 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001050
1051 void handleDiv(Instruction &I) {
1052 IRBuilder<> IRB(&I);
1053 // Strict on the second argument.
1054 insertCheck(I.getOperand(1), &I);
1055 setShadow(&I, getShadow(&I, 0));
1056 setOrigin(&I, getOrigin(&I, 0));
1057 }
1058
1059 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1060 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1061 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1062 void visitURem(BinaryOperator &I) { handleDiv(I); }
1063 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1064 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1065
1066 /// \brief Instrument == and != comparisons.
1067 ///
1068 /// Sometimes the comparison result is known even if some of the bits of the
1069 /// arguments are not.
1070 void handleEqualityComparison(ICmpInst &I) {
1071 IRBuilder<> IRB(&I);
1072 Value *A = I.getOperand(0);
1073 Value *B = I.getOperand(1);
1074 Value *Sa = getShadow(A);
1075 Value *Sb = getShadow(B);
1076 if (A->getType()->isPointerTy())
1077 A = IRB.CreatePointerCast(A, MS.IntptrTy);
1078 if (B->getType()->isPointerTy())
1079 B = IRB.CreatePointerCast(B, MS.IntptrTy);
1080 // A == B <==> (C = A^B) == 0
1081 // A != B <==> (C = A^B) != 0
1082 // Sc = Sa | Sb
1083 Value *C = IRB.CreateXor(A, B);
1084 Value *Sc = IRB.CreateOr(Sa, Sb);
1085 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1086 // Result is defined if one of the following is true
1087 // * there is a defined 1 bit in C
1088 // * C is fully defined
1089 // Si = !(C & ~Sc) && Sc
1090 Value *Zero = Constant::getNullValue(Sc->getType());
1091 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1092 Value *Si =
1093 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1094 IRB.CreateICmpEQ(
1095 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1096 Si->setName("_msprop_icmp");
1097 setShadow(&I, Si);
1098 setOriginForNaryOp(I);
1099 }
1100
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001101 /// \brief Instrument signed relational comparisons.
1102 ///
1103 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1104 /// propagating the highest bit of the shadow. Everything else is delegated
1105 /// to handleShadowOr().
1106 void handleSignedRelationalComparison(ICmpInst &I) {
1107 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1108 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1109 Value* op = NULL;
1110 CmpInst::Predicate pre = I.getPredicate();
1111 if (constOp0 && constOp0->isNullValue() &&
1112 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1113 op = I.getOperand(1);
1114 } else if (constOp1 && constOp1->isNullValue() &&
1115 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1116 op = I.getOperand(0);
1117 }
1118 if (op) {
1119 IRBuilder<> IRB(&I);
1120 Value* Shadow =
1121 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1122 setShadow(&I, Shadow);
1123 setOrigin(&I, getOrigin(op));
1124 } else {
1125 handleShadowOr(I);
1126 }
1127 }
1128
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001129 void visitICmpInst(ICmpInst &I) {
1130 if (ClHandleICmp && I.isEquality())
1131 handleEqualityComparison(I);
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001132 else if (ClHandleICmp && I.isSigned() && I.isRelational())
1133 handleSignedRelationalComparison(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001134 else
1135 handleShadowOr(I);
1136 }
1137
1138 void visitFCmpInst(FCmpInst &I) {
1139 handleShadowOr(I);
1140 }
1141
1142 void handleShift(BinaryOperator &I) {
1143 IRBuilder<> IRB(&I);
1144 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1145 // Otherwise perform the same shift on S1.
1146 Value *S1 = getShadow(&I, 0);
1147 Value *S2 = getShadow(&I, 1);
1148 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1149 S2->getType());
1150 Value *V2 = I.getOperand(1);
1151 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1152 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1153 setOriginForNaryOp(I);
1154 }
1155
1156 void visitShl(BinaryOperator &I) { handleShift(I); }
1157 void visitAShr(BinaryOperator &I) { handleShift(I); }
1158 void visitLShr(BinaryOperator &I) { handleShift(I); }
1159
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001160 /// \brief Instrument llvm.memmove
1161 ///
1162 /// At this point we don't know if llvm.memmove will be inlined or not.
1163 /// If we don't instrument it and it gets inlined,
1164 /// our interceptor will not kick in and we will lose the memmove.
1165 /// If we instrument the call here, but it does not get inlined,
1166 /// we will memove the shadow twice: which is bad in case
1167 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1168 ///
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001169 /// Similar situation exists for memcpy and memset.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001170 void visitMemMoveInst(MemMoveInst &I) {
1171 IRBuilder<> IRB(&I);
1172 IRB.CreateCall3(
1173 MS.MemmoveFn,
1174 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1175 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1176 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1177 I.eraseFromParent();
1178 }
1179
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001180 // Similar to memmove: avoid copying shadow twice.
1181 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1182 // FIXME: consider doing manual inline for small constant sizes and proper
1183 // alignment.
1184 void visitMemCpyInst(MemCpyInst &I) {
1185 IRBuilder<> IRB(&I);
1186 IRB.CreateCall3(
1187 MS.MemcpyFn,
1188 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1189 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1190 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1191 I.eraseFromParent();
1192 }
1193
1194 // Same as memcpy.
1195 void visitMemSetInst(MemSetInst &I) {
1196 IRBuilder<> IRB(&I);
1197 IRB.CreateCall3(
1198 MS.MemsetFn,
1199 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1200 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1201 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1202 I.eraseFromParent();
1203 }
1204
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001205 void visitVAStartInst(VAStartInst &I) {
1206 VAHelper->visitVAStartInst(I);
1207 }
1208
1209 void visitVACopyInst(VACopyInst &I) {
1210 VAHelper->visitVACopyInst(I);
1211 }
1212
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001213 void handleBswap(IntrinsicInst &I) {
1214 IRBuilder<> IRB(&I);
1215 Value *Op = I.getArgOperand(0);
1216 Type *OpType = Op->getType();
1217 Function *BswapFunc = Intrinsic::getDeclaration(
1218 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1219 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1220 setOrigin(&I, getOrigin(Op));
1221 }
1222
1223 void visitIntrinsicInst(IntrinsicInst &I) {
1224 switch (I.getIntrinsicID()) {
1225 case llvm::Intrinsic::bswap:
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001226 handleBswap(I);
1227 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001228 default:
1229 visitInstruction(I); break;
1230 }
1231 }
1232
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001233 void visitCallSite(CallSite CS) {
1234 Instruction &I = *CS.getInstruction();
1235 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1236 if (CS.isCall()) {
Evgeniy Stepanov7ad7e832012-11-29 14:32:03 +00001237 CallInst *Call = cast<CallInst>(&I);
1238
1239 // For inline asm, do the usual thing: check argument shadow and mark all
1240 // outputs as clean. Note that any side effects of the inline asm that are
1241 // not immediately visible in its constraints are not handled.
1242 if (Call->isInlineAsm()) {
1243 visitInstruction(I);
1244 return;
1245 }
1246
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001247 // Allow only tail calls with the same types, otherwise
1248 // we may have a false positive: shadow for a non-void RetVal
1249 // will get propagated to a void RetVal.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001250 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1251 Call->setTailCall(false);
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001252
1253 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00001254
1255 // We are going to insert code that relies on the fact that the callee
1256 // will become a non-readonly function after it is instrumented by us. To
1257 // prevent this code from being optimized out, mark that function
1258 // non-readonly in advance.
1259 if (Function *Func = Call->getCalledFunction()) {
1260 // Clear out readonly/readnone attributes.
1261 AttrBuilder B;
1262 B.addAttribute(Attributes::ReadOnly)
1263 .addAttribute(Attributes::ReadNone);
Bill Wendlinge94d8432012-12-07 23:16:57 +00001264 Func->removeAttribute(AttributeSet::FunctionIndex,
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00001265 Attributes::get(Func->getContext(), B));
1266 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001267 }
1268 IRBuilder<> IRB(&I);
1269 unsigned ArgOffset = 0;
1270 DEBUG(dbgs() << " CallSite: " << I << "\n");
1271 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1272 ArgIt != End; ++ArgIt) {
1273 Value *A = *ArgIt;
1274 unsigned i = ArgIt - CS.arg_begin();
1275 if (!A->getType()->isSized()) {
1276 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1277 continue;
1278 }
1279 unsigned Size = 0;
1280 Value *Store = 0;
1281 // Compute the Shadow for arg even if it is ByVal, because
1282 // in that case getShadow() will copy the actual arg shadow to
1283 // __msan_param_tls.
1284 Value *ArgShadow = getShadow(A);
1285 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1286 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1287 " Shadow: " << *ArgShadow << "\n");
1288 if (CS.paramHasAttr(i + 1, Attributes::ByVal)) {
1289 assert(A->getType()->isPointerTy() &&
1290 "ByVal argument is not a pointer!");
1291 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1292 unsigned Alignment = CS.getParamAlignment(i + 1);
1293 Store = IRB.CreateMemCpy(ArgShadowBase,
1294 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1295 Size, Alignment);
1296 } else {
1297 Size = MS.TD->getTypeAllocSize(A->getType());
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001298 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1299 kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001300 }
1301 if (ClTrackOrigins)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +00001302 IRB.CreateStore(getOrigin(A),
1303 getOriginPtrForArgument(A, IRB, ArgOffset));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001304 assert(Size != 0 && Store != 0);
1305 DEBUG(dbgs() << " Param:" << *Store << "\n");
1306 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1307 }
1308 DEBUG(dbgs() << " done with call args\n");
1309
1310 FunctionType *FT =
1311 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1312 if (FT->isVarArg()) {
1313 VAHelper->visitCallSite(CS, IRB);
1314 }
1315
1316 // Now, get the shadow for the RetVal.
1317 if (!I.getType()->isSized()) return;
1318 IRBuilder<> IRBBefore(&I);
1319 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1320 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001321 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001322 Instruction *NextInsn = 0;
1323 if (CS.isCall()) {
1324 NextInsn = I.getNextNode();
1325 } else {
1326 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1327 if (!NormalDest->getSinglePredecessor()) {
1328 // FIXME: this case is tricky, so we are just conservative here.
1329 // Perhaps we need to split the edge between this BB and NormalDest,
1330 // but a naive attempt to use SplitEdge leads to a crash.
1331 setShadow(&I, getCleanShadow(&I));
1332 setOrigin(&I, getCleanOrigin());
1333 return;
1334 }
1335 NextInsn = NormalDest->getFirstInsertionPt();
1336 assert(NextInsn &&
1337 "Could not find insertion point for retval shadow load");
1338 }
1339 IRBuilder<> IRBAfter(NextInsn);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001340 Value *RetvalShadow =
1341 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1342 kShadowTLSAlignment, "_msret");
1343 setShadow(&I, RetvalShadow);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001344 if (ClTrackOrigins)
1345 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1346 }
1347
1348 void visitReturnInst(ReturnInst &I) {
1349 IRBuilder<> IRB(&I);
1350 if (Value *RetVal = I.getReturnValue()) {
1351 // Set the shadow for the RetVal.
1352 Value *Shadow = getShadow(RetVal);
1353 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1354 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001355 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001356 if (ClTrackOrigins)
1357 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1358 }
1359 }
1360
1361 void visitPHINode(PHINode &I) {
1362 IRBuilder<> IRB(&I);
1363 ShadowPHINodes.push_back(&I);
1364 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1365 "_msphi_s"));
1366 if (ClTrackOrigins)
1367 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1368 "_msphi_o"));
1369 }
1370
1371 void visitAllocaInst(AllocaInst &I) {
1372 setShadow(&I, getCleanShadow(&I));
1373 if (!ClPoisonStack) return;
1374 IRBuilder<> IRB(I.getNextNode());
1375 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1376 if (ClPoisonStackWithCall) {
1377 IRB.CreateCall2(MS.MsanPoisonStackFn,
1378 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1379 ConstantInt::get(MS.IntptrTy, Size));
1380 } else {
1381 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1382 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1383 Size, I.getAlignment());
1384 }
1385
1386 if (ClTrackOrigins) {
1387 setOrigin(&I, getCleanOrigin());
1388 SmallString<2048> StackDescriptionStorage;
1389 raw_svector_ostream StackDescription(StackDescriptionStorage);
1390 // We create a string with a description of the stack allocation and
1391 // pass it into __msan_set_alloca_origin.
1392 // It will be printed by the run-time if stack-originated UMR is found.
1393 // The first 4 bytes of the string are set to '----' and will be replaced
1394 // by __msan_va_arg_overflow_size_tls at the first call.
1395 StackDescription << "----" << I.getName() << "@" << F.getName();
1396 Value *Descr =
1397 createPrivateNonConstGlobalForString(*F.getParent(),
1398 StackDescription.str());
1399 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1400 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1401 ConstantInt::get(MS.IntptrTy, Size),
1402 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1403 }
1404 }
1405
1406 void visitSelectInst(SelectInst& I) {
1407 IRBuilder<> IRB(&I);
1408 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1409 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1410 "_msprop"));
1411 if (ClTrackOrigins)
1412 setOrigin(&I, IRB.CreateSelect(I.getCondition(),
1413 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1414 }
1415
1416 void visitLandingPadInst(LandingPadInst &I) {
1417 // Do nothing.
1418 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1419 setShadow(&I, getCleanShadow(&I));
1420 setOrigin(&I, getCleanOrigin());
1421 }
1422
1423 void visitGetElementPtrInst(GetElementPtrInst &I) {
1424 handleShadowOr(I);
1425 }
1426
1427 void visitExtractValueInst(ExtractValueInst &I) {
1428 IRBuilder<> IRB(&I);
1429 Value *Agg = I.getAggregateOperand();
1430 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1431 Value *AggShadow = getShadow(Agg);
1432 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1433 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1434 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1435 setShadow(&I, ResShadow);
1436 setOrigin(&I, getCleanOrigin());
1437 }
1438
1439 void visitInsertValueInst(InsertValueInst &I) {
1440 IRBuilder<> IRB(&I);
1441 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1442 Value *AggShadow = getShadow(I.getAggregateOperand());
1443 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1444 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1445 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1446 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1447 DEBUG(dbgs() << " Res: " << *Res << "\n");
1448 setShadow(&I, Res);
1449 setOrigin(&I, getCleanOrigin());
1450 }
1451
1452 void dumpInst(Instruction &I) {
1453 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1454 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1455 } else {
1456 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1457 }
1458 errs() << "QQQ " << I << "\n";
1459 }
1460
1461 void visitResumeInst(ResumeInst &I) {
1462 DEBUG(dbgs() << "Resume: " << I << "\n");
1463 // Nothing to do here.
1464 }
1465
1466 void visitInstruction(Instruction &I) {
1467 // Everything else: stop propagating and check for poisoned shadow.
1468 if (ClDumpStrictInstructions)
1469 dumpInst(I);
1470 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1471 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1472 insertCheck(I.getOperand(i), &I);
1473 setShadow(&I, getCleanShadow(&I));
1474 setOrigin(&I, getCleanOrigin());
1475 }
1476};
1477
1478/// \brief AMD64-specific implementation of VarArgHelper.
1479struct VarArgAMD64Helper : public VarArgHelper {
1480 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1481 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001482 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001483 static const unsigned AMD64FpEndOffset = 176;
1484
1485 Function &F;
1486 MemorySanitizer &MS;
1487 MemorySanitizerVisitor &MSV;
1488 Value *VAArgTLSCopy;
1489 Value *VAArgOverflowSize;
1490
1491 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1492
1493 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1494 MemorySanitizerVisitor &MSV)
1495 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1496
1497 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1498
1499 ArgKind classifyArgument(Value* arg) {
1500 // A very rough approximation of X86_64 argument classification rules.
1501 Type *T = arg->getType();
1502 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1503 return AK_FloatingPoint;
1504 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1505 return AK_GeneralPurpose;
1506 if (T->isPointerTy())
1507 return AK_GeneralPurpose;
1508 return AK_Memory;
1509 }
1510
1511 // For VarArg functions, store the argument shadow in an ABI-specific format
1512 // that corresponds to va_list layout.
1513 // We do this because Clang lowers va_arg in the frontend, and this pass
1514 // only sees the low level code that deals with va_list internals.
1515 // A much easier alternative (provided that Clang emits va_arg instructions)
1516 // would have been to associate each live instance of va_list with a copy of
1517 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1518 // order.
1519 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1520 unsigned GpOffset = 0;
1521 unsigned FpOffset = AMD64GpEndOffset;
1522 unsigned OverflowOffset = AMD64FpEndOffset;
1523 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1524 ArgIt != End; ++ArgIt) {
1525 Value *A = *ArgIt;
1526 ArgKind AK = classifyArgument(A);
1527 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1528 AK = AK_Memory;
1529 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1530 AK = AK_Memory;
1531 Value *Base;
1532 switch (AK) {
1533 case AK_GeneralPurpose:
1534 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1535 GpOffset += 8;
1536 break;
1537 case AK_FloatingPoint:
1538 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1539 FpOffset += 16;
1540 break;
1541 case AK_Memory:
1542 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1543 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1544 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1545 }
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001546 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001547 }
1548 Constant *OverflowSize =
1549 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1550 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1551 }
1552
1553 /// \brief Compute the shadow address for a given va_arg.
1554 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1555 int ArgOffset) {
1556 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1557 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1558 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1559 "_msarg");
1560 }
1561
1562 void visitVAStartInst(VAStartInst &I) {
1563 IRBuilder<> IRB(&I);
1564 VAStartInstrumentationList.push_back(&I);
1565 Value *VAListTag = I.getArgOperand(0);
1566 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1567
1568 // Unpoison the whole __va_list_tag.
1569 // FIXME: magic ABI constants.
1570 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1571 /* size */24, /* alignment */16, false);
1572 }
1573
1574 void visitVACopyInst(VACopyInst &I) {
1575 IRBuilder<> IRB(&I);
1576 Value *VAListTag = I.getArgOperand(0);
1577 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1578
1579 // Unpoison the whole __va_list_tag.
1580 // FIXME: magic ABI constants.
1581 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1582 /* size */ 24, /* alignment */ 16, false);
1583 }
1584
1585 void finalizeInstrumentation() {
1586 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1587 "finalizeInstrumentation called twice");
1588 if (!VAStartInstrumentationList.empty()) {
1589 // If there is a va_start in this function, make a backup copy of
1590 // va_arg_tls somewhere in the function entry block.
1591 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1592 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1593 Value *CopySize =
1594 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1595 VAArgOverflowSize);
1596 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1597 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1598 }
1599
1600 // Instrument va_start.
1601 // Copy va_list shadow from the backup copy of the TLS contents.
1602 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1603 CallInst *OrigInst = VAStartInstrumentationList[i];
1604 IRBuilder<> IRB(OrigInst->getNextNode());
1605 Value *VAListTag = OrigInst->getArgOperand(0);
1606
1607 Value *RegSaveAreaPtrPtr =
1608 IRB.CreateIntToPtr(
1609 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1610 ConstantInt::get(MS.IntptrTy, 16)),
1611 Type::getInt64PtrTy(*MS.C));
1612 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1613 Value *RegSaveAreaShadowPtr =
1614 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1615 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1616 AMD64FpEndOffset, 16);
1617
1618 Value *OverflowArgAreaPtrPtr =
1619 IRB.CreateIntToPtr(
1620 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1621 ConstantInt::get(MS.IntptrTy, 8)),
1622 Type::getInt64PtrTy(*MS.C));
1623 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1624 Value *OverflowArgAreaShadowPtr =
1625 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1626 Value *SrcPtr =
1627 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1628 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1629 }
1630 }
1631};
1632
1633VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1634 MemorySanitizerVisitor &Visitor) {
1635 return new VarArgAMD64Helper(Func, Msan, Visitor);
1636}
1637
1638} // namespace
1639
1640bool MemorySanitizer::runOnFunction(Function &F) {
1641 MemorySanitizerVisitor Visitor(F, *this);
1642
1643 // Clear out readonly/readnone attributes.
1644 AttrBuilder B;
1645 B.addAttribute(Attributes::ReadOnly)
1646 .addAttribute(Attributes::ReadNone);
Bill Wendlinge94d8432012-12-07 23:16:57 +00001647 F.removeAttribute(AttributeSet::FunctionIndex,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001648 Attributes::get(F.getContext(), B));
1649
1650 return Visitor.runOnFunction();
1651}