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