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