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