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