[asan] temporary disable generating __asan_loadN/__asan_storeN
[oota-llvm.git] / lib / Transforms / Instrumentation / DataFlowSanitizer.cpp
1 //===-- DataFlowSanitizer.cpp - dynamic data flow analysis ----------------===//
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 DataFlowSanitizer, a generalised dynamic data flow
11 /// analysis.
12 ///
13 /// Unlike other Sanitizer tools, this tool is not designed to detect a specific
14 /// class of bugs on its own.  Instead, it provides a generic dynamic data flow
15 /// analysis framework to be used by clients to help detect application-specific
16 /// issues within their own code.
17 ///
18 /// The analysis is based on automatic propagation of data flow labels (also
19 /// known as taint labels) through a program as it performs computation.  Each
20 /// byte of application memory is backed by two bytes of shadow memory which
21 /// hold the label.  On Linux/x86_64, memory is laid out as follows:
22 ///
23 /// +--------------------+ 0x800000000000 (top of memory)
24 /// | application memory |
25 /// +--------------------+ 0x700000008000 (kAppAddr)
26 /// |                    |
27 /// |       unused       |
28 /// |                    |
29 /// +--------------------+ 0x200200000000 (kUnusedAddr)
30 /// |    union table     |
31 /// +--------------------+ 0x200000000000 (kUnionTableAddr)
32 /// |   shadow memory    |
33 /// +--------------------+ 0x000000010000 (kShadowAddr)
34 /// | reserved by kernel |
35 /// +--------------------+ 0x000000000000
36 ///
37 /// To derive a shadow memory address from an application memory address,
38 /// bits 44-46 are cleared to bring the address into the range
39 /// [0x000000008000,0x100000000000).  Then the address is shifted left by 1 to
40 /// account for the double byte representation of shadow labels and move the
41 /// address into the shadow memory range.  See the function
42 /// DataFlowSanitizer::getShadowAddress below.
43 ///
44 /// For more information, please refer to the design document:
45 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
46
47 #include "llvm/Transforms/Instrumentation.h"
48 #include "llvm/ADT/DenseMap.h"
49 #include "llvm/ADT/DenseSet.h"
50 #include "llvm/ADT/DepthFirstIterator.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/Analysis/ValueTracking.h"
53 #include "llvm/IR/IRBuilder.h"
54 #include "llvm/IR/InlineAsm.h"
55 #include "llvm/IR/InstVisitor.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/MDBuilder.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/IR/Value.h"
60 #include "llvm/Pass.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
63 #include "llvm/Transforms/Utils/Local.h"
64 #include "llvm/Transforms/Utils/SpecialCaseList.h"
65 #include <iterator>
66
67 using namespace llvm;
68
69 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
70 // alignment requirements provided by the input IR are correct.  For example,
71 // if the input IR contains a load with alignment 8, this flag will cause
72 // the shadow load to have alignment 16.  This flag is disabled by default as
73 // we have unfortunately encountered too much code (including Clang itself;
74 // see PR14291) which performs misaligned access.
75 static cl::opt<bool> ClPreserveAlignment(
76     "dfsan-preserve-alignment",
77     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
78     cl::init(false));
79
80 // The ABI list file controls how shadow parameters are passed.  The pass treats
81 // every function labelled "uninstrumented" in the ABI list file as conforming
82 // to the "native" (i.e. unsanitized) ABI.  Unless the ABI list contains
83 // additional annotations for those functions, a call to one of those functions
84 // will produce a warning message, as the labelling behaviour of the function is
85 // unknown.  The other supported annotations are "functional" and "discard",
86 // which are described below under DataFlowSanitizer::WrapperKind.
87 static cl::opt<std::string> ClABIListFile(
88     "dfsan-abilist",
89     cl::desc("File listing native ABI functions and how the pass treats them"),
90     cl::Hidden);
91
92 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
93 // functions (see DataFlowSanitizer::InstrumentedABI below).
94 static cl::opt<bool> ClArgsABI(
95     "dfsan-args-abi",
96     cl::desc("Use the argument ABI rather than the TLS ABI"),
97     cl::Hidden);
98
99 // Controls whether the pass includes or ignores the labels of pointers in load
100 // instructions.
101 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
102     "dfsan-combine-pointer-labels-on-load",
103     cl::desc("Combine the label of the pointer with the label of the data when "
104              "loading from memory."),
105     cl::Hidden, cl::init(true));
106
107 // Controls whether the pass includes or ignores the labels of pointers in
108 // stores instructions.
109 static cl::opt<bool> ClCombinePointerLabelsOnStore(
110     "dfsan-combine-pointer-labels-on-store",
111     cl::desc("Combine the label of the pointer with the label of the data when "
112              "storing in memory."),
113     cl::Hidden, cl::init(false));
114
115 static cl::opt<bool> ClDebugNonzeroLabels(
116     "dfsan-debug-nonzero-labels",
117     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
118              "load or return with a nonzero label"),
119     cl::Hidden);
120
121 namespace {
122
123 class DataFlowSanitizer : public ModulePass {
124   friend struct DFSanFunction;
125   friend class DFSanVisitor;
126
127   enum {
128     ShadowWidth = 16
129   };
130
131   /// Which ABI should be used for instrumented functions?
132   enum InstrumentedABI {
133     /// Argument and return value labels are passed through additional
134     /// arguments and by modifying the return type.
135     IA_Args,
136
137     /// Argument and return value labels are passed through TLS variables
138     /// __dfsan_arg_tls and __dfsan_retval_tls.
139     IA_TLS
140   };
141
142   /// How should calls to uninstrumented functions be handled?
143   enum WrapperKind {
144     /// This function is present in an uninstrumented form but we don't know
145     /// how it should be handled.  Print a warning and call the function anyway.
146     /// Don't label the return value.
147     WK_Warning,
148
149     /// This function does not write to (user-accessible) memory, and its return
150     /// value is unlabelled.
151     WK_Discard,
152
153     /// This function does not write to (user-accessible) memory, and the label
154     /// of its return value is the union of the label of its arguments.
155     WK_Functional,
156
157     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
158     /// where F is the name of the function.  This function may wrap the
159     /// original function or provide its own implementation.  This is similar to
160     /// the IA_Args ABI, except that IA_Args uses a struct return type to
161     /// pass the return value shadow in a register, while WK_Custom uses an
162     /// extra pointer argument to return the shadow.  This allows the wrapped
163     /// form of the function type to be expressed in C.
164     WK_Custom
165   };
166
167   const DataLayout *DL;
168   Module *Mod;
169   LLVMContext *Ctx;
170   IntegerType *ShadowTy;
171   PointerType *ShadowPtrTy;
172   IntegerType *IntptrTy;
173   ConstantInt *ZeroShadow;
174   ConstantInt *ShadowPtrMask;
175   ConstantInt *ShadowPtrMul;
176   Constant *ArgTLS;
177   Constant *RetvalTLS;
178   void *(*GetArgTLSPtr)();
179   void *(*GetRetvalTLSPtr)();
180   Constant *GetArgTLS;
181   Constant *GetRetvalTLS;
182   FunctionType *DFSanUnionFnTy;
183   FunctionType *DFSanUnionLoadFnTy;
184   FunctionType *DFSanUnimplementedFnTy;
185   FunctionType *DFSanSetLabelFnTy;
186   FunctionType *DFSanNonzeroLabelFnTy;
187   Constant *DFSanUnionFn;
188   Constant *DFSanUnionLoadFn;
189   Constant *DFSanUnimplementedFn;
190   Constant *DFSanSetLabelFn;
191   Constant *DFSanNonzeroLabelFn;
192   MDNode *ColdCallWeights;
193   std::unique_ptr<SpecialCaseList> ABIList;
194   DenseMap<Value *, Function *> UnwrappedFnMap;
195   AttributeSet ReadOnlyNoneAttrs;
196
197   Value *getShadowAddress(Value *Addr, Instruction *Pos);
198   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
199   bool isInstrumented(const Function *F);
200   bool isInstrumented(const GlobalAlias *GA);
201   FunctionType *getArgsFunctionType(FunctionType *T);
202   FunctionType *getTrampolineFunctionType(FunctionType *T);
203   FunctionType *getCustomFunctionType(FunctionType *T);
204   InstrumentedABI getInstrumentedABI();
205   WrapperKind getWrapperKind(Function *F);
206   void addGlobalNamePrefix(GlobalValue *GV);
207   Function *buildWrapperFunction(Function *F, StringRef NewFName,
208                                  GlobalValue::LinkageTypes NewFLink,
209                                  FunctionType *NewFT);
210   Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
211
212  public:
213   DataFlowSanitizer(StringRef ABIListFile = StringRef(),
214                     void *(*getArgTLS)() = 0, void *(*getRetValTLS)() = 0);
215   static char ID;
216   bool doInitialization(Module &M) override;
217   bool runOnModule(Module &M) override;
218 };
219
220 struct DFSanFunction {
221   DataFlowSanitizer &DFS;
222   Function *F;
223   DataFlowSanitizer::InstrumentedABI IA;
224   bool IsNativeABI;
225   Value *ArgTLSPtr;
226   Value *RetvalTLSPtr;
227   AllocaInst *LabelReturnAlloca;
228   DenseMap<Value *, Value *> ValShadowMap;
229   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
230   std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
231   DenseSet<Instruction *> SkipInsts;
232   DenseSet<Value *> NonZeroChecks;
233
234   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
235       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
236         IsNativeABI(IsNativeABI), ArgTLSPtr(0), RetvalTLSPtr(0),
237         LabelReturnAlloca(0) {}
238   Value *getArgTLSPtr();
239   Value *getArgTLS(unsigned Index, Instruction *Pos);
240   Value *getRetvalTLS();
241   Value *getShadow(Value *V);
242   void setShadow(Instruction *I, Value *Shadow);
243   Value *combineOperandShadows(Instruction *Inst);
244   Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
245                     Instruction *Pos);
246   void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
247                    Instruction *Pos);
248 };
249
250 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
251  public:
252   DFSanFunction &DFSF;
253   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
254
255   void visitOperandShadowInst(Instruction &I);
256
257   void visitBinaryOperator(BinaryOperator &BO);
258   void visitCastInst(CastInst &CI);
259   void visitCmpInst(CmpInst &CI);
260   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
261   void visitLoadInst(LoadInst &LI);
262   void visitStoreInst(StoreInst &SI);
263   void visitReturnInst(ReturnInst &RI);
264   void visitCallSite(CallSite CS);
265   void visitPHINode(PHINode &PN);
266   void visitExtractElementInst(ExtractElementInst &I);
267   void visitInsertElementInst(InsertElementInst &I);
268   void visitShuffleVectorInst(ShuffleVectorInst &I);
269   void visitExtractValueInst(ExtractValueInst &I);
270   void visitInsertValueInst(InsertValueInst &I);
271   void visitAllocaInst(AllocaInst &I);
272   void visitSelectInst(SelectInst &I);
273   void visitMemSetInst(MemSetInst &I);
274   void visitMemTransferInst(MemTransferInst &I);
275 };
276
277 }
278
279 char DataFlowSanitizer::ID;
280 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
281                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
282
283 ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
284                                               void *(*getArgTLS)(),
285                                               void *(*getRetValTLS)()) {
286   return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
287 }
288
289 DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
290                                      void *(*getArgTLS)(),
291                                      void *(*getRetValTLS)())
292     : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
293       ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
294                                                                : ABIListFile)) {
295 }
296
297 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
298   llvm::SmallVector<Type *, 4> ArgTypes;
299   std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
300   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
301     ArgTypes.push_back(ShadowTy);
302   if (T->isVarArg())
303     ArgTypes.push_back(ShadowPtrTy);
304   Type *RetType = T->getReturnType();
305   if (!RetType->isVoidTy())
306     RetType = StructType::get(RetType, ShadowTy, (Type *)0);
307   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
308 }
309
310 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
311   assert(!T->isVarArg());
312   llvm::SmallVector<Type *, 4> ArgTypes;
313   ArgTypes.push_back(T->getPointerTo());
314   std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
315   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
316     ArgTypes.push_back(ShadowTy);
317   Type *RetType = T->getReturnType();
318   if (!RetType->isVoidTy())
319     ArgTypes.push_back(ShadowPtrTy);
320   return FunctionType::get(T->getReturnType(), ArgTypes, false);
321 }
322
323 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
324   assert(!T->isVarArg());
325   llvm::SmallVector<Type *, 4> ArgTypes;
326   for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
327        i != e; ++i) {
328     FunctionType *FT;
329     if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
330                                      *i)->getElementType()))) {
331       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
332       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
333     } else {
334       ArgTypes.push_back(*i);
335     }
336   }
337   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
338     ArgTypes.push_back(ShadowTy);
339   Type *RetType = T->getReturnType();
340   if (!RetType->isVoidTy())
341     ArgTypes.push_back(ShadowPtrTy);
342   return FunctionType::get(T->getReturnType(), ArgTypes, false);
343 }
344
345 bool DataFlowSanitizer::doInitialization(Module &M) {
346   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
347   if (!DLP)
348     return false;
349   DL = &DLP->getDataLayout();
350
351   Mod = &M;
352   Ctx = &M.getContext();
353   ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
354   ShadowPtrTy = PointerType::getUnqual(ShadowTy);
355   IntptrTy = DL->getIntPtrType(*Ctx);
356   ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
357   ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
358   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
359
360   Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
361   DFSanUnionFnTy =
362       FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
363   Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
364   DFSanUnionLoadFnTy =
365       FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
366   DFSanUnimplementedFnTy = FunctionType::get(
367       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
368   Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
369   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
370                                         DFSanSetLabelArgs, /*isVarArg=*/false);
371   DFSanNonzeroLabelFnTy = FunctionType::get(
372       Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
373
374   if (GetArgTLSPtr) {
375     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
376     ArgTLS = 0;
377     GetArgTLS = ConstantExpr::getIntToPtr(
378         ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
379         PointerType::getUnqual(
380             FunctionType::get(PointerType::getUnqual(ArgTLSTy), (Type *)0)));
381   }
382   if (GetRetvalTLSPtr) {
383     RetvalTLS = 0;
384     GetRetvalTLS = ConstantExpr::getIntToPtr(
385         ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
386         PointerType::getUnqual(
387             FunctionType::get(PointerType::getUnqual(ShadowTy), (Type *)0)));
388   }
389
390   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
391   return true;
392 }
393
394 bool DataFlowSanitizer::isInstrumented(const Function *F) {
395   return !ABIList->isIn(*F, "uninstrumented");
396 }
397
398 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
399   return !ABIList->isIn(*GA, "uninstrumented");
400 }
401
402 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
403   return ClArgsABI ? IA_Args : IA_TLS;
404 }
405
406 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
407   if (ABIList->isIn(*F, "functional"))
408     return WK_Functional;
409   if (ABIList->isIn(*F, "discard"))
410     return WK_Discard;
411   if (ABIList->isIn(*F, "custom"))
412     return WK_Custom;
413
414   return WK_Warning;
415 }
416
417 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
418   std::string GVName = GV->getName(), Prefix = "dfs$";
419   GV->setName(Prefix + GVName);
420
421   // Try to change the name of the function in module inline asm.  We only do
422   // this for specific asm directives, currently only ".symver", to try to avoid
423   // corrupting asm which happens to contain the symbol name as a substring.
424   // Note that the substitution for .symver assumes that the versioned symbol
425   // also has an instrumented name.
426   std::string Asm = GV->getParent()->getModuleInlineAsm();
427   std::string SearchStr = ".symver " + GVName + ",";
428   size_t Pos = Asm.find(SearchStr);
429   if (Pos != std::string::npos) {
430     Asm.replace(Pos, SearchStr.size(),
431                 ".symver " + Prefix + GVName + "," + Prefix);
432     GV->getParent()->setModuleInlineAsm(Asm);
433   }
434 }
435
436 Function *
437 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
438                                         GlobalValue::LinkageTypes NewFLink,
439                                         FunctionType *NewFT) {
440   FunctionType *FT = F->getFunctionType();
441   Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
442                                     F->getParent());
443   NewF->copyAttributesFrom(F);
444   NewF->removeAttributes(
445       AttributeSet::ReturnIndex,
446       AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
447                                        AttributeSet::ReturnIndex));
448
449   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
450   std::vector<Value *> Args;
451   unsigned n = FT->getNumParams();
452   for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
453     Args.push_back(&*ai);
454   CallInst *CI = CallInst::Create(F, Args, "", BB);
455   if (FT->getReturnType()->isVoidTy())
456     ReturnInst::Create(*Ctx, BB);
457   else
458     ReturnInst::Create(*Ctx, CI, BB);
459
460   return NewF;
461 }
462
463 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
464                                                           StringRef FName) {
465   FunctionType *FTT = getTrampolineFunctionType(FT);
466   Constant *C = Mod->getOrInsertFunction(FName, FTT);
467   Function *F = dyn_cast<Function>(C);
468   if (F && F->isDeclaration()) {
469     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
470     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
471     std::vector<Value *> Args;
472     Function::arg_iterator AI = F->arg_begin(); ++AI;
473     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
474       Args.push_back(&*AI);
475     CallInst *CI =
476         CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
477     ReturnInst *RI;
478     if (FT->getReturnType()->isVoidTy())
479       RI = ReturnInst::Create(*Ctx, BB);
480     else
481       RI = ReturnInst::Create(*Ctx, CI, BB);
482
483     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
484     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
485     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
486       DFSF.ValShadowMap[ValAI] = ShadowAI;
487     DFSanVisitor(DFSF).visitCallInst(*CI);
488     if (!FT->getReturnType()->isVoidTy())
489       new StoreInst(DFSF.getShadow(RI->getReturnValue()),
490                     &F->getArgumentList().back(), RI);
491   }
492
493   return C;
494 }
495
496 bool DataFlowSanitizer::runOnModule(Module &M) {
497   if (!DL)
498     return false;
499
500   if (ABIList->isIn(M, "skip"))
501     return false;
502
503   if (!GetArgTLSPtr) {
504     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
505     ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
506     if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
507       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
508   }
509   if (!GetRetvalTLSPtr) {
510     RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
511     if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
512       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
513   }
514
515   DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
516   if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
517     F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
518     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
519     F->addAttribute(1, Attribute::ZExt);
520     F->addAttribute(2, Attribute::ZExt);
521   }
522   DFSanUnionLoadFn =
523       Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
524   if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
525     F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
526     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
527   }
528   DFSanUnimplementedFn =
529       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
530   DFSanSetLabelFn =
531       Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
532   if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
533     F->addAttribute(1, Attribute::ZExt);
534   }
535   DFSanNonzeroLabelFn =
536       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
537
538   std::vector<Function *> FnsToInstrument;
539   llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
540   for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
541     if (!i->isIntrinsic() &&
542         i != DFSanUnionFn &&
543         i != DFSanUnionLoadFn &&
544         i != DFSanUnimplementedFn &&
545         i != DFSanSetLabelFn &&
546         i != DFSanNonzeroLabelFn)
547       FnsToInstrument.push_back(&*i);
548   }
549
550   // Give function aliases prefixes when necessary, and build wrappers where the
551   // instrumentedness is inconsistent.
552   for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
553     GlobalAlias *GA = &*i;
554     ++i;
555     // Don't stop on weak.  We assume people aren't playing games with the
556     // instrumentedness of overridden weak aliases.
557     if (Function *F = dyn_cast<Function>(GA->getAliasedGlobal())) {
558       bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
559       if (GAInst && FInst) {
560         addGlobalNamePrefix(GA);
561       } else if (GAInst != FInst) {
562         // Non-instrumented alias of an instrumented function, or vice versa.
563         // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
564         // below will take care of instrumenting it.
565         Function *NewF =
566             buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
567         GA->replaceAllUsesWith(NewF);
568         NewF->takeName(GA);
569         GA->eraseFromParent();
570         FnsToInstrument.push_back(NewF);
571       }
572     }
573   }
574
575   AttrBuilder B;
576   B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
577   ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
578
579   // First, change the ABI of every function in the module.  ABI-listed
580   // functions keep their original ABI and get a wrapper function.
581   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
582                                          e = FnsToInstrument.end();
583        i != e; ++i) {
584     Function &F = **i;
585     FunctionType *FT = F.getFunctionType();
586
587     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
588                               FT->getReturnType()->isVoidTy());
589
590     if (isInstrumented(&F)) {
591       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
592       // easily identify cases of mismatching ABIs.
593       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
594         FunctionType *NewFT = getArgsFunctionType(FT);
595         Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
596         NewF->copyAttributesFrom(&F);
597         NewF->removeAttributes(
598             AttributeSet::ReturnIndex,
599             AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
600                                              AttributeSet::ReturnIndex));
601         for (Function::arg_iterator FArg = F.arg_begin(),
602                                     NewFArg = NewF->arg_begin(),
603                                     FArgEnd = F.arg_end();
604              FArg != FArgEnd; ++FArg, ++NewFArg) {
605           FArg->replaceAllUsesWith(NewFArg);
606         }
607         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
608
609         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
610              UI != UE;) {
611           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
612           ++UI;
613           if (BA) {
614             BA->replaceAllUsesWith(
615                 BlockAddress::get(NewF, BA->getBasicBlock()));
616             delete BA;
617           }
618         }
619         F.replaceAllUsesWith(
620             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
621         NewF->takeName(&F);
622         F.eraseFromParent();
623         *i = NewF;
624         addGlobalNamePrefix(NewF);
625       } else {
626         addGlobalNamePrefix(&F);
627       }
628                // Hopefully, nobody will try to indirectly call a vararg
629                // function... yet.
630     } else if (FT->isVarArg()) {
631       UnwrappedFnMap[&F] = &F;
632       *i = 0;
633     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
634       // Build a wrapper function for F.  The wrapper simply calls F, and is
635       // added to FnsToInstrument so that any instrumentation according to its
636       // WrapperKind is done in the second pass below.
637       FunctionType *NewFT = getInstrumentedABI() == IA_Args
638                                 ? getArgsFunctionType(FT)
639                                 : FT;
640       Function *NewF = buildWrapperFunction(
641           &F, std::string("dfsw$") + std::string(F.getName()),
642           GlobalValue::LinkOnceODRLinkage, NewFT);
643       if (getInstrumentedABI() == IA_TLS)
644         NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
645
646       Value *WrappedFnCst =
647           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
648       F.replaceAllUsesWith(WrappedFnCst);
649       UnwrappedFnMap[WrappedFnCst] = &F;
650       *i = NewF;
651
652       if (!F.isDeclaration()) {
653         // This function is probably defining an interposition of an
654         // uninstrumented function and hence needs to keep the original ABI.
655         // But any functions it may call need to use the instrumented ABI, so
656         // we instrument it in a mode which preserves the original ABI.
657         FnsWithNativeABI.insert(&F);
658
659         // This code needs to rebuild the iterators, as they may be invalidated
660         // by the push_back, taking care that the new range does not include
661         // any functions added by this code.
662         size_t N = i - FnsToInstrument.begin(),
663                Count = e - FnsToInstrument.begin();
664         FnsToInstrument.push_back(&F);
665         i = FnsToInstrument.begin() + N;
666         e = FnsToInstrument.begin() + Count;
667       }
668     }
669   }
670
671   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
672                                          e = FnsToInstrument.end();
673        i != e; ++i) {
674     if (!*i || (*i)->isDeclaration())
675       continue;
676
677     removeUnreachableBlocks(**i);
678
679     DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
680
681     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
682     // Build a copy of the list before iterating over it.
683     llvm::SmallVector<BasicBlock *, 4> BBList(
684         depth_first(&(*i)->getEntryBlock()));
685
686     for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
687                                                       e = BBList.end();
688          i != e; ++i) {
689       Instruction *Inst = &(*i)->front();
690       while (1) {
691         // DFSanVisitor may split the current basic block, changing the current
692         // instruction's next pointer and moving the next instruction to the
693         // tail block from which we should continue.
694         Instruction *Next = Inst->getNextNode();
695         // DFSanVisitor may delete Inst, so keep track of whether it was a
696         // terminator.
697         bool IsTerminator = isa<TerminatorInst>(Inst);
698         if (!DFSF.SkipInsts.count(Inst))
699           DFSanVisitor(DFSF).visit(Inst);
700         if (IsTerminator)
701           break;
702         Inst = Next;
703       }
704     }
705
706     // We will not necessarily be able to compute the shadow for every phi node
707     // until we have visited every block.  Therefore, the code that handles phi
708     // nodes adds them to the PHIFixups list so that they can be properly
709     // handled here.
710     for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
711              i = DFSF.PHIFixups.begin(),
712              e = DFSF.PHIFixups.end();
713          i != e; ++i) {
714       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
715            ++val) {
716         i->second->setIncomingValue(
717             val, DFSF.getShadow(i->first->getIncomingValue(val)));
718       }
719     }
720
721     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
722     // places (i.e. instructions in basic blocks we haven't even begun visiting
723     // yet).  To make our life easier, do this work in a pass after the main
724     // instrumentation.
725     if (ClDebugNonzeroLabels) {
726       for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
727                                        e = DFSF.NonZeroChecks.end();
728            i != e; ++i) {
729         Instruction *Pos;
730         if (Instruction *I = dyn_cast<Instruction>(*i))
731           Pos = I->getNextNode();
732         else
733           Pos = DFSF.F->getEntryBlock().begin();
734         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
735           Pos = Pos->getNextNode();
736         IRBuilder<> IRB(Pos);
737         Value *Ne = IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow);
738         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
739             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
740         IRBuilder<> ThenIRB(BI);
741         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
742       }
743     }
744   }
745
746   return false;
747 }
748
749 Value *DFSanFunction::getArgTLSPtr() {
750   if (ArgTLSPtr)
751     return ArgTLSPtr;
752   if (DFS.ArgTLS)
753     return ArgTLSPtr = DFS.ArgTLS;
754
755   IRBuilder<> IRB(F->getEntryBlock().begin());
756   return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
757 }
758
759 Value *DFSanFunction::getRetvalTLS() {
760   if (RetvalTLSPtr)
761     return RetvalTLSPtr;
762   if (DFS.RetvalTLS)
763     return RetvalTLSPtr = DFS.RetvalTLS;
764
765   IRBuilder<> IRB(F->getEntryBlock().begin());
766   return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
767 }
768
769 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
770   IRBuilder<> IRB(Pos);
771   return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
772 }
773
774 Value *DFSanFunction::getShadow(Value *V) {
775   if (!isa<Argument>(V) && !isa<Instruction>(V))
776     return DFS.ZeroShadow;
777   Value *&Shadow = ValShadowMap[V];
778   if (!Shadow) {
779     if (Argument *A = dyn_cast<Argument>(V)) {
780       if (IsNativeABI)
781         return DFS.ZeroShadow;
782       switch (IA) {
783       case DataFlowSanitizer::IA_TLS: {
784         Value *ArgTLSPtr = getArgTLSPtr();
785         Instruction *ArgTLSPos =
786             DFS.ArgTLS ? &*F->getEntryBlock().begin()
787                        : cast<Instruction>(ArgTLSPtr)->getNextNode();
788         IRBuilder<> IRB(ArgTLSPos);
789         Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
790         break;
791       }
792       case DataFlowSanitizer::IA_Args: {
793         unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
794         Function::arg_iterator i = F->arg_begin();
795         while (ArgIdx--)
796           ++i;
797         Shadow = i;
798         assert(Shadow->getType() == DFS.ShadowTy);
799         break;
800       }
801       }
802       NonZeroChecks.insert(Shadow);
803     } else {
804       Shadow = DFS.ZeroShadow;
805     }
806   }
807   return Shadow;
808 }
809
810 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
811   assert(!ValShadowMap.count(I));
812   assert(Shadow->getType() == DFS.ShadowTy);
813   ValShadowMap[I] = Shadow;
814 }
815
816 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
817   assert(Addr != RetvalTLS && "Reinstrumenting?");
818   IRBuilder<> IRB(Pos);
819   return IRB.CreateIntToPtr(
820       IRB.CreateMul(
821           IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
822           ShadowPtrMul),
823       ShadowPtrTy);
824 }
825
826 // Generates IR to compute the union of the two given shadows, inserting it
827 // before Pos.  Returns the computed union Value.
828 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
829                                          Instruction *Pos) {
830   if (V1 == ZeroShadow)
831     return V2;
832   if (V2 == ZeroShadow)
833     return V1;
834   if (V1 == V2)
835     return V1;
836   IRBuilder<> IRB(Pos);
837   BasicBlock *Head = Pos->getParent();
838   Value *Ne = IRB.CreateICmpNE(V1, V2);
839   BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
840       Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
841   IRBuilder<> ThenIRB(BI);
842   CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
843   Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
844   Call->addAttribute(1, Attribute::ZExt);
845   Call->addAttribute(2, Attribute::ZExt);
846
847   BasicBlock *Tail = BI->getSuccessor(0);
848   PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
849   Phi->addIncoming(Call, Call->getParent());
850   Phi->addIncoming(V1, Head);
851   return Phi;
852 }
853
854 // A convenience function which folds the shadows of each of the operands
855 // of the provided instruction Inst, inserting the IR before Inst.  Returns
856 // the computed union Value.
857 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
858   if (Inst->getNumOperands() == 0)
859     return DFS.ZeroShadow;
860
861   Value *Shadow = getShadow(Inst->getOperand(0));
862   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
863     Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
864   }
865   return Shadow;
866 }
867
868 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
869   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
870   DFSF.setShadow(&I, CombinedShadow);
871 }
872
873 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
874 // Addr has alignment Align, and take the union of each of those shadows.
875 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
876                                  Instruction *Pos) {
877   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
878     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
879         AllocaShadowMap.find(AI);
880     if (i != AllocaShadowMap.end()) {
881       IRBuilder<> IRB(Pos);
882       return IRB.CreateLoad(i->second);
883     }
884   }
885
886   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
887   SmallVector<Value *, 2> Objs;
888   GetUnderlyingObjects(Addr, Objs, DFS.DL);
889   bool AllConstants = true;
890   for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
891        i != e; ++i) {
892     if (isa<Function>(*i) || isa<BlockAddress>(*i))
893       continue;
894     if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
895       continue;
896
897     AllConstants = false;
898     break;
899   }
900   if (AllConstants)
901     return DFS.ZeroShadow;
902
903   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
904   switch (Size) {
905   case 0:
906     return DFS.ZeroShadow;
907   case 1: {
908     LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
909     LI->setAlignment(ShadowAlign);
910     return LI;
911   }
912   case 2: {
913     IRBuilder<> IRB(Pos);
914     Value *ShadowAddr1 =
915         IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
916     return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
917                               IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
918                               Pos);
919   }
920   }
921   if (Size % (64 / DFS.ShadowWidth) == 0) {
922     // Fast path for the common case where each byte has identical shadow: load
923     // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
924     // shadow is non-equal.
925     BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
926     IRBuilder<> FallbackIRB(FallbackBB);
927     CallInst *FallbackCall = FallbackIRB.CreateCall2(
928         DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
929     FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
930
931     // Compare each of the shadows stored in the loaded 64 bits to each other,
932     // by computing (WideShadow rotl ShadowWidth) == WideShadow.
933     IRBuilder<> IRB(Pos);
934     Value *WideAddr =
935         IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
936     Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
937     Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
938     Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
939     Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
940     Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
941     Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
942
943     BasicBlock *Head = Pos->getParent();
944     BasicBlock *Tail = Head->splitBasicBlock(Pos);
945     // In the following code LastBr will refer to the previous basic block's
946     // conditional branch instruction, whose true successor is fixed up to point
947     // to the next block during the loop below or to the tail after the final
948     // iteration.
949     BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
950     ReplaceInstWithInst(Head->getTerminator(), LastBr);
951
952     for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
953          Ofs += 64 / DFS.ShadowWidth) {
954       BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
955       IRBuilder<> NextIRB(NextBB);
956       WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
957       Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
958       ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
959       LastBr->setSuccessor(0, NextBB);
960       LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
961     }
962
963     LastBr->setSuccessor(0, Tail);
964     FallbackIRB.CreateBr(Tail);
965     PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
966     Shadow->addIncoming(FallbackCall, FallbackBB);
967     Shadow->addIncoming(TruncShadow, LastBr->getParent());
968     return Shadow;
969   }
970
971   IRBuilder<> IRB(Pos);
972   CallInst *FallbackCall = IRB.CreateCall2(
973       DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
974   FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
975   return FallbackCall;
976 }
977
978 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
979   uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
980   uint64_t Align;
981   if (ClPreserveAlignment) {
982     Align = LI.getAlignment();
983     if (Align == 0)
984       Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
985   } else {
986     Align = 1;
987   }
988   IRBuilder<> IRB(&LI);
989   Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
990   if (ClCombinePointerLabelsOnLoad) {
991     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
992     Shadow = DFSF.DFS.combineShadows(Shadow, PtrShadow, &LI);
993   }
994   if (Shadow != DFSF.DFS.ZeroShadow)
995     DFSF.NonZeroChecks.insert(Shadow);
996
997   DFSF.setShadow(&LI, Shadow);
998 }
999
1000 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1001                                 Value *Shadow, Instruction *Pos) {
1002   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1003     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1004         AllocaShadowMap.find(AI);
1005     if (i != AllocaShadowMap.end()) {
1006       IRBuilder<> IRB(Pos);
1007       IRB.CreateStore(Shadow, i->second);
1008       return;
1009     }
1010   }
1011
1012   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1013   IRBuilder<> IRB(Pos);
1014   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1015   if (Shadow == DFS.ZeroShadow) {
1016     IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1017     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1018     Value *ExtShadowAddr =
1019         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1020     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1021     return;
1022   }
1023
1024   const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1025   uint64_t Offset = 0;
1026   if (Size >= ShadowVecSize) {
1027     VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1028     Value *ShadowVec = UndefValue::get(ShadowVecTy);
1029     for (unsigned i = 0; i != ShadowVecSize; ++i) {
1030       ShadowVec = IRB.CreateInsertElement(
1031           ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1032     }
1033     Value *ShadowVecAddr =
1034         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1035     do {
1036       Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1037       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1038       Size -= ShadowVecSize;
1039       ++Offset;
1040     } while (Size >= ShadowVecSize);
1041     Offset *= ShadowVecSize;
1042   }
1043   while (Size > 0) {
1044     Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1045     IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1046     --Size;
1047     ++Offset;
1048   }
1049 }
1050
1051 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1052   uint64_t Size =
1053       DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1054   uint64_t Align;
1055   if (ClPreserveAlignment) {
1056     Align = SI.getAlignment();
1057     if (Align == 0)
1058       Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1059   } else {
1060     Align = 1;
1061   }
1062
1063   Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1064   if (ClCombinePointerLabelsOnStore) {
1065     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1066     Shadow = DFSF.DFS.combineShadows(Shadow, PtrShadow, &SI);
1067   }
1068   DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
1069 }
1070
1071 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1072   visitOperandShadowInst(BO);
1073 }
1074
1075 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1076
1077 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1078
1079 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1080   visitOperandShadowInst(GEPI);
1081 }
1082
1083 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1084   visitOperandShadowInst(I);
1085 }
1086
1087 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1088   visitOperandShadowInst(I);
1089 }
1090
1091 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1092   visitOperandShadowInst(I);
1093 }
1094
1095 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1096   visitOperandShadowInst(I);
1097 }
1098
1099 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1100   visitOperandShadowInst(I);
1101 }
1102
1103 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1104   bool AllLoadsStores = true;
1105   for (User *U : I.users()) {
1106     if (isa<LoadInst>(U))
1107       continue;
1108
1109     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1110       if (SI->getPointerOperand() == &I)
1111         continue;
1112     }
1113
1114     AllLoadsStores = false;
1115     break;
1116   }
1117   if (AllLoadsStores) {
1118     IRBuilder<> IRB(&I);
1119     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1120   }
1121   DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1122 }
1123
1124 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1125   Value *CondShadow = DFSF.getShadow(I.getCondition());
1126   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1127   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1128
1129   if (isa<VectorType>(I.getCondition()->getType())) {
1130     DFSF.setShadow(
1131         &I, DFSF.DFS.combineShadows(
1132                 CondShadow,
1133                 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
1134   } else {
1135     Value *ShadowSel;
1136     if (TrueShadow == FalseShadow) {
1137       ShadowSel = TrueShadow;
1138     } else {
1139       ShadowSel =
1140           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1141     }
1142     DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
1143   }
1144 }
1145
1146 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1147   IRBuilder<> IRB(&I);
1148   Value *ValShadow = DFSF.getShadow(I.getValue());
1149   IRB.CreateCall3(
1150       DFSF.DFS.DFSanSetLabelFn, ValShadow,
1151       IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1152       IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1153 }
1154
1155 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1156   IRBuilder<> IRB(&I);
1157   Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1158   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1159   Value *LenShadow = IRB.CreateMul(
1160       I.getLength(),
1161       ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1162   Value *AlignShadow;
1163   if (ClPreserveAlignment) {
1164     AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1165                                 ConstantInt::get(I.getAlignmentCst()->getType(),
1166                                                  DFSF.DFS.ShadowWidth / 8));
1167   } else {
1168     AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1169                                    DFSF.DFS.ShadowWidth / 8);
1170   }
1171   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1172   DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1173   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1174   IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1175                   AlignShadow, I.getVolatileCst());
1176 }
1177
1178 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1179   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1180     switch (DFSF.IA) {
1181     case DataFlowSanitizer::IA_TLS: {
1182       Value *S = DFSF.getShadow(RI.getReturnValue());
1183       IRBuilder<> IRB(&RI);
1184       IRB.CreateStore(S, DFSF.getRetvalTLS());
1185       break;
1186     }
1187     case DataFlowSanitizer::IA_Args: {
1188       IRBuilder<> IRB(&RI);
1189       Type *RT = DFSF.F->getFunctionType()->getReturnType();
1190       Value *InsVal =
1191           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1192       Value *InsShadow =
1193           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1194       RI.setOperand(0, InsShadow);
1195       break;
1196     }
1197     }
1198   }
1199 }
1200
1201 void DFSanVisitor::visitCallSite(CallSite CS) {
1202   Function *F = CS.getCalledFunction();
1203   if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1204     visitOperandShadowInst(*CS.getInstruction());
1205     return;
1206   }
1207
1208   IRBuilder<> IRB(CS.getInstruction());
1209
1210   DenseMap<Value *, Function *>::iterator i =
1211       DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1212   if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1213     Function *F = i->second;
1214     switch (DFSF.DFS.getWrapperKind(F)) {
1215     case DataFlowSanitizer::WK_Warning: {
1216       CS.setCalledFunction(F);
1217       IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1218                      IRB.CreateGlobalStringPtr(F->getName()));
1219       DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1220       return;
1221     }
1222     case DataFlowSanitizer::WK_Discard: {
1223       CS.setCalledFunction(F);
1224       DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1225       return;
1226     }
1227     case DataFlowSanitizer::WK_Functional: {
1228       CS.setCalledFunction(F);
1229       visitOperandShadowInst(*CS.getInstruction());
1230       return;
1231     }
1232     case DataFlowSanitizer::WK_Custom: {
1233       // Don't try to handle invokes of custom functions, it's too complicated.
1234       // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1235       // wrapper.
1236       if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1237         FunctionType *FT = F->getFunctionType();
1238         FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1239         std::string CustomFName = "__dfsw_";
1240         CustomFName += F->getName();
1241         Constant *CustomF =
1242             DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1243         if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1244           CustomFn->copyAttributesFrom(F);
1245
1246           // Custom functions returning non-void will write to the return label.
1247           if (!FT->getReturnType()->isVoidTy()) {
1248             CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1249                                        DFSF.DFS.ReadOnlyNoneAttrs);
1250           }
1251         }
1252
1253         std::vector<Value *> Args;
1254
1255         CallSite::arg_iterator i = CS.arg_begin();
1256         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1257           Type *T = (*i)->getType();
1258           FunctionType *ParamFT;
1259           if (isa<PointerType>(T) &&
1260               (ParamFT = dyn_cast<FunctionType>(
1261                    cast<PointerType>(T)->getElementType()))) {
1262             std::string TName = "dfst";
1263             TName += utostr(FT->getNumParams() - n);
1264             TName += "$";
1265             TName += F->getName();
1266             Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1267             Args.push_back(T);
1268             Args.push_back(
1269                 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1270           } else {
1271             Args.push_back(*i);
1272           }
1273         }
1274
1275         i = CS.arg_begin();
1276         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1277           Args.push_back(DFSF.getShadow(*i));
1278
1279         if (!FT->getReturnType()->isVoidTy()) {
1280           if (!DFSF.LabelReturnAlloca) {
1281             DFSF.LabelReturnAlloca =
1282                 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1283                                DFSF.F->getEntryBlock().begin());
1284           }
1285           Args.push_back(DFSF.LabelReturnAlloca);
1286         }
1287
1288         CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1289         CustomCI->setCallingConv(CI->getCallingConv());
1290         CustomCI->setAttributes(CI->getAttributes());
1291
1292         if (!FT->getReturnType()->isVoidTy()) {
1293           LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1294           DFSF.setShadow(CustomCI, LabelLoad);
1295         }
1296
1297         CI->replaceAllUsesWith(CustomCI);
1298         CI->eraseFromParent();
1299         return;
1300       }
1301       break;
1302     }
1303     }
1304   }
1305
1306   FunctionType *FT = cast<FunctionType>(
1307       CS.getCalledValue()->getType()->getPointerElementType());
1308   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1309     for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1310       IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1311                       DFSF.getArgTLS(i, CS.getInstruction()));
1312     }
1313   }
1314
1315   Instruction *Next = 0;
1316   if (!CS.getType()->isVoidTy()) {
1317     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1318       if (II->getNormalDest()->getSinglePredecessor()) {
1319         Next = II->getNormalDest()->begin();
1320       } else {
1321         BasicBlock *NewBB =
1322             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1323         Next = NewBB->begin();
1324       }
1325     } else {
1326       Next = CS->getNextNode();
1327     }
1328
1329     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1330       IRBuilder<> NextIRB(Next);
1331       LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1332       DFSF.SkipInsts.insert(LI);
1333       DFSF.setShadow(CS.getInstruction(), LI);
1334       DFSF.NonZeroChecks.insert(LI);
1335     }
1336   }
1337
1338   // Do all instrumentation for IA_Args down here to defer tampering with the
1339   // CFG in a way that SplitEdge may be able to detect.
1340   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1341     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1342     Value *Func =
1343         IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1344     std::vector<Value *> Args;
1345
1346     CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1347     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1348       Args.push_back(*i);
1349
1350     i = CS.arg_begin();
1351     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1352       Args.push_back(DFSF.getShadow(*i));
1353
1354     if (FT->isVarArg()) {
1355       unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1356       ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1357       AllocaInst *VarArgShadow =
1358           new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1359       Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1360       for (unsigned n = 0; i != e; ++i, ++n) {
1361         IRB.CreateStore(DFSF.getShadow(*i),
1362                         IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1363         Args.push_back(*i);
1364       }
1365     }
1366
1367     CallSite NewCS;
1368     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1369       NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1370                                Args);
1371     } else {
1372       NewCS = IRB.CreateCall(Func, Args);
1373     }
1374     NewCS.setCallingConv(CS.getCallingConv());
1375     NewCS.setAttributes(CS.getAttributes().removeAttributes(
1376         *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1377         AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1378                                          AttributeSet::ReturnIndex)));
1379
1380     if (Next) {
1381       ExtractValueInst *ExVal =
1382           ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1383       DFSF.SkipInsts.insert(ExVal);
1384       ExtractValueInst *ExShadow =
1385           ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1386       DFSF.SkipInsts.insert(ExShadow);
1387       DFSF.setShadow(ExVal, ExShadow);
1388       DFSF.NonZeroChecks.insert(ExShadow);
1389
1390       CS.getInstruction()->replaceAllUsesWith(ExVal);
1391     }
1392
1393     CS.getInstruction()->eraseFromParent();
1394   }
1395 }
1396
1397 void DFSanVisitor::visitPHINode(PHINode &PN) {
1398   PHINode *ShadowPN =
1399       PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1400
1401   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1402   Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1403   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1404        ++i) {
1405     ShadowPN->addIncoming(UndefShadow, *i);
1406   }
1407
1408   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1409   DFSF.setShadow(&PN, ShadowPN);
1410 }