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 /// +--------------------+ 0x300200000000 (kUnusedAddr)
30 /// |    union table     |
31 /// +--------------------+ 0x300000000000 (kUnionTableAddr)
32 /// |       origin       |
33 /// +--------------------+ 0x200000008000 (kOriginAddr)
34 /// |   shadow memory    |
35 /// +--------------------+ 0x000000010000 (kShadowAddr)
36 /// | reserved by kernel |
37 /// +--------------------+ 0x000000000000
38 ///
39 /// To derive a shadow memory address from an application memory address,
40 /// bits 44-46 are cleared to bring the address into the range
41 /// [0x000000008000,0x100000000000).  Then the address is shifted left by 1 to
42 /// account for the double byte representation of shadow labels and move the
43 /// address into the shadow memory range.  See the function
44 /// DataFlowSanitizer::getShadowAddress below.
45 ///
46 /// For more information, please refer to the design document:
47 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
48 //
49 //===----------------------------------------------------------------------===//
50 
51 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
52 #include "llvm/ADT/DenseMap.h"
53 #include "llvm/ADT/DenseSet.h"
54 #include "llvm/ADT/DepthFirstIterator.h"
55 #include "llvm/ADT/None.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/Triple.h"
61 #include "llvm/Analysis/ValueTracking.h"
62 #include "llvm/IR/Argument.h"
63 #include "llvm/IR/Attributes.h"
64 #include "llvm/IR/BasicBlock.h"
65 #include "llvm/IR/Constant.h"
66 #include "llvm/IR/Constants.h"
67 #include "llvm/IR/DataLayout.h"
68 #include "llvm/IR/DerivedTypes.h"
69 #include "llvm/IR/Dominators.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/GlobalAlias.h"
72 #include "llvm/IR/GlobalValue.h"
73 #include "llvm/IR/GlobalVariable.h"
74 #include "llvm/IR/IRBuilder.h"
75 #include "llvm/IR/InlineAsm.h"
76 #include "llvm/IR/InstVisitor.h"
77 #include "llvm/IR/InstrTypes.h"
78 #include "llvm/IR/Instruction.h"
79 #include "llvm/IR/Instructions.h"
80 #include "llvm/IR/IntrinsicInst.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/MDBuilder.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/PassManager.h"
85 #include "llvm/IR/Type.h"
86 #include "llvm/IR/User.h"
87 #include "llvm/IR/Value.h"
88 #include "llvm/InitializePasses.h"
89 #include "llvm/Pass.h"
90 #include "llvm/Support/Casting.h"
91 #include "llvm/Support/CommandLine.h"
92 #include "llvm/Support/ErrorHandling.h"
93 #include "llvm/Support/SpecialCaseList.h"
94 #include "llvm/Support/VirtualFileSystem.h"
95 #include "llvm/Transforms/Instrumentation.h"
96 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
97 #include "llvm/Transforms/Utils/Local.h"
98 #include <algorithm>
99 #include <cassert>
100 #include <cstddef>
101 #include <cstdint>
102 #include <iterator>
103 #include <memory>
104 #include <set>
105 #include <string>
106 #include <utility>
107 #include <vector>
108 
109 using namespace llvm;
110 
111 // This must be consistent with ShadowWidthBits.
112 static const Align kShadowTLSAlignment = Align(2);
113 
114 static const Align kMinOriginAlignment = Align(4);
115 
116 // The size of TLS variables. These constants must be kept in sync with the ones
117 // in dfsan.cpp.
118 static const unsigned kArgTLSSize = 800;
119 static const unsigned kRetvalTLSSize = 800;
120 
121 // External symbol to be used when generating the shadow address for
122 // architectures with multiple VMAs. Instead of using a constant integer
123 // the runtime will set the external mask based on the VMA range.
124 const char kDFSanExternShadowPtrMask[] = "__dfsan_shadow_ptr_mask";
125 
126 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
127 // alignment requirements provided by the input IR are correct.  For example,
128 // if the input IR contains a load with alignment 8, this flag will cause
129 // the shadow load to have alignment 16.  This flag is disabled by default as
130 // we have unfortunately encountered too much code (including Clang itself;
131 // see PR14291) which performs misaligned access.
132 static cl::opt<bool> ClPreserveAlignment(
133     "dfsan-preserve-alignment",
134     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
135     cl::init(false));
136 
137 // The ABI list files control how shadow parameters are passed. The pass treats
138 // every function labelled "uninstrumented" in the ABI list file as conforming
139 // to the "native" (i.e. unsanitized) ABI.  Unless the ABI list contains
140 // additional annotations for those functions, a call to one of those functions
141 // will produce a warning message, as the labelling behaviour of the function is
142 // unknown.  The other supported annotations are "functional" and "discard",
143 // which are described below under DataFlowSanitizer::WrapperKind.
144 static cl::list<std::string> ClABIListFiles(
145     "dfsan-abilist",
146     cl::desc("File listing native ABI functions and how the pass treats them"),
147     cl::Hidden);
148 
149 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
150 // functions (see DataFlowSanitizer::InstrumentedABI below).
151 static cl::opt<bool> ClArgsABI(
152     "dfsan-args-abi",
153     cl::desc("Use the argument ABI rather than the TLS ABI"),
154     cl::Hidden);
155 
156 // Controls whether the pass includes or ignores the labels of pointers in load
157 // instructions.
158 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
159     "dfsan-combine-pointer-labels-on-load",
160     cl::desc("Combine the label of the pointer with the label of the data when "
161              "loading from memory."),
162     cl::Hidden, cl::init(true));
163 
164 // Controls whether the pass includes or ignores the labels of pointers in
165 // stores instructions.
166 static cl::opt<bool> ClCombinePointerLabelsOnStore(
167     "dfsan-combine-pointer-labels-on-store",
168     cl::desc("Combine the label of the pointer with the label of the data when "
169              "storing in memory."),
170     cl::Hidden, cl::init(false));
171 
172 static cl::opt<bool> ClDebugNonzeroLabels(
173     "dfsan-debug-nonzero-labels",
174     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
175              "load or return with a nonzero label"),
176     cl::Hidden);
177 
178 // Experimental feature that inserts callbacks for certain data events.
179 // Currently callbacks are only inserted for loads, stores, memory transfers
180 // (i.e. memcpy and memmove), and comparisons.
181 //
182 // If this flag is set to true, the user must provide definitions for the
183 // following callback functions:
184 //   void __dfsan_load_callback(dfsan_label Label, void* addr);
185 //   void __dfsan_store_callback(dfsan_label Label, void* addr);
186 //   void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
187 //   void __dfsan_cmp_callback(dfsan_label CombinedLabel);
188 static cl::opt<bool> ClEventCallbacks(
189     "dfsan-event-callbacks",
190     cl::desc("Insert calls to __dfsan_*_callback functions on data events."),
191     cl::Hidden, cl::init(false));
192 
193 // Use a distinct bit for each base label, enabling faster unions with less
194 // instrumentation.  Limits the max number of base labels to 16.
195 static cl::opt<bool> ClFast16Labels(
196     "dfsan-fast-16-labels",
197     cl::desc("Use more efficient instrumentation, limiting the number of "
198              "labels to 16."),
199     cl::Hidden, cl::init(false));
200 
201 // Controls whether the pass tracks the control flow of select instructions.
202 static cl::opt<bool> ClTrackSelectControlFlow(
203     "dfsan-track-select-control-flow",
204     cl::desc("Propagate labels from condition values of select instructions "
205              "to results."),
206     cl::Hidden, cl::init(true));
207 
208 // Controls how to track origins.
209 // * 0: do not track origins.
210 // * 1: track origins at memory store operations.
211 // * 2: TODO: track origins at memory store operations and callsites.
212 static cl::opt<int> ClTrackOrigins("dfsan-track-origins",
213                                    cl::desc("Track origins of labels"),
214                                    cl::Hidden, cl::init(0));
215 
216 static StringRef GetGlobalTypeString(const GlobalValue &G) {
217   // Types of GlobalVariables are always pointer types.
218   Type *GType = G.getValueType();
219   // For now we support excluding struct types only.
220   if (StructType *SGType = dyn_cast<StructType>(GType)) {
221     if (!SGType->isLiteral())
222       return SGType->getName();
223   }
224   return "<unknown type>";
225 }
226 
227 namespace {
228 
229 class DFSanABIList {
230   std::unique_ptr<SpecialCaseList> SCL;
231 
232  public:
233   DFSanABIList() = default;
234 
235   void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
236 
237   /// Returns whether either this function or its source file are listed in the
238   /// given category.
239   bool isIn(const Function &F, StringRef Category) const {
240     return isIn(*F.getParent(), Category) ||
241            SCL->inSection("dataflow", "fun", F.getName(), Category);
242   }
243 
244   /// Returns whether this global alias is listed in the given category.
245   ///
246   /// If GA aliases a function, the alias's name is matched as a function name
247   /// would be.  Similarly, aliases of globals are matched like globals.
248   bool isIn(const GlobalAlias &GA, StringRef Category) const {
249     if (isIn(*GA.getParent(), Category))
250       return true;
251 
252     if (isa<FunctionType>(GA.getValueType()))
253       return SCL->inSection("dataflow", "fun", GA.getName(), Category);
254 
255     return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
256            SCL->inSection("dataflow", "type", GetGlobalTypeString(GA),
257                           Category);
258   }
259 
260   /// Returns whether this module is listed in the given category.
261   bool isIn(const Module &M, StringRef Category) const {
262     return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
263   }
264 };
265 
266 /// TransformedFunction is used to express the result of transforming one
267 /// function type into another.  This struct is immutable.  It holds metadata
268 /// useful for updating calls of the old function to the new type.
269 struct TransformedFunction {
270   TransformedFunction(FunctionType* OriginalType,
271                       FunctionType* TransformedType,
272                       std::vector<unsigned> ArgumentIndexMapping)
273       : OriginalType(OriginalType),
274         TransformedType(TransformedType),
275         ArgumentIndexMapping(ArgumentIndexMapping) {}
276 
277   // Disallow copies.
278   TransformedFunction(const TransformedFunction&) = delete;
279   TransformedFunction& operator=(const TransformedFunction&) = delete;
280 
281   // Allow moves.
282   TransformedFunction(TransformedFunction&&) = default;
283   TransformedFunction& operator=(TransformedFunction&&) = default;
284 
285   /// Type of the function before the transformation.
286   FunctionType *OriginalType;
287 
288   /// Type of the function after the transformation.
289   FunctionType *TransformedType;
290 
291   /// Transforming a function may change the position of arguments.  This
292   /// member records the mapping from each argument's old position to its new
293   /// position.  Argument positions are zero-indexed.  If the transformation
294   /// from F to F' made the first argument of F into the third argument of F',
295   /// then ArgumentIndexMapping[0] will equal 2.
296   std::vector<unsigned> ArgumentIndexMapping;
297 };
298 
299 /// Given function attributes from a call site for the original function,
300 /// return function attributes appropriate for a call to the transformed
301 /// function.
302 AttributeList TransformFunctionAttributes(
303     const TransformedFunction& TransformedFunction,
304     LLVMContext& Ctx, AttributeList CallSiteAttrs) {
305 
306   // Construct a vector of AttributeSet for each function argument.
307   std::vector<llvm::AttributeSet> ArgumentAttributes(
308       TransformedFunction.TransformedType->getNumParams());
309 
310   // Copy attributes from the parameter of the original function to the
311   // transformed version.  'ArgumentIndexMapping' holds the mapping from
312   // old argument position to new.
313   for (unsigned i=0, ie = TransformedFunction.ArgumentIndexMapping.size();
314        i < ie; ++i) {
315     unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[i];
316     ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(i);
317   }
318 
319   // Copy annotations on varargs arguments.
320   for (unsigned i = TransformedFunction.OriginalType->getNumParams(),
321        ie = CallSiteAttrs.getNumAttrSets(); i<ie; ++i) {
322     ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(i));
323   }
324 
325   return AttributeList::get(
326       Ctx,
327       CallSiteAttrs.getFnAttributes(),
328       CallSiteAttrs.getRetAttributes(),
329       llvm::makeArrayRef(ArgumentAttributes));
330 }
331 
332 class DataFlowSanitizer {
333   friend struct DFSanFunction;
334   friend class DFSanVisitor;
335 
336   enum {
337     ShadowWidthBits = 16,
338     ShadowWidthBytes = ShadowWidthBits / 8,
339     OriginWidthBits = 32,
340     OriginWidthBytes = OriginWidthBits / 8
341   };
342 
343   /// Which ABI should be used for instrumented functions?
344   enum InstrumentedABI {
345     /// Argument and return value labels are passed through additional
346     /// arguments and by modifying the return type.
347     IA_Args,
348 
349     /// Argument and return value labels are passed through TLS variables
350     /// __dfsan_arg_tls and __dfsan_retval_tls.
351     IA_TLS
352   };
353 
354   /// How should calls to uninstrumented functions be handled?
355   enum WrapperKind {
356     /// This function is present in an uninstrumented form but we don't know
357     /// how it should be handled.  Print a warning and call the function anyway.
358     /// Don't label the return value.
359     WK_Warning,
360 
361     /// This function does not write to (user-accessible) memory, and its return
362     /// value is unlabelled.
363     WK_Discard,
364 
365     /// This function does not write to (user-accessible) memory, and the label
366     /// of its return value is the union of the label of its arguments.
367     WK_Functional,
368 
369     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
370     /// where F is the name of the function.  This function may wrap the
371     /// original function or provide its own implementation.  This is similar to
372     /// the IA_Args ABI, except that IA_Args uses a struct return type to
373     /// pass the return value shadow in a register, while WK_Custom uses an
374     /// extra pointer argument to return the shadow.  This allows the wrapped
375     /// form of the function type to be expressed in C.
376     WK_Custom
377   };
378 
379   Module *Mod;
380   LLVMContext *Ctx;
381   Type *Int8Ptr;
382   IntegerType *OriginTy;
383   PointerType *OriginPtrTy;
384   ConstantInt *OriginBase;
385   ConstantInt *ZeroOrigin;
386   /// The shadow type for all primitive types and vector types.
387   IntegerType *PrimitiveShadowTy;
388   PointerType *PrimitiveShadowPtrTy;
389   IntegerType *IntptrTy;
390   ConstantInt *ZeroPrimitiveShadow;
391   ConstantInt *ShadowPtrMask;
392   ConstantInt *ShadowPtrMul;
393   Constant *ArgTLS;
394   ArrayType *ArgOriginTLSTy;
395   Constant *ArgOriginTLS;
396   Constant *RetvalTLS;
397   Constant *RetvalOriginTLS;
398   Constant *ExternalShadowMask;
399   FunctionType *DFSanUnionFnTy;
400   FunctionType *DFSanUnionLoadFnTy;
401   FunctionType *DFSanLoadLabelAndOriginFnTy;
402   FunctionType *DFSanUnimplementedFnTy;
403   FunctionType *DFSanSetLabelFnTy;
404   FunctionType *DFSanNonzeroLabelFnTy;
405   FunctionType *DFSanVarargWrapperFnTy;
406   FunctionType *DFSanCmpCallbackFnTy;
407   FunctionType *DFSanLoadStoreCallbackFnTy;
408   FunctionType *DFSanMemTransferCallbackFnTy;
409   FunctionType *DFSanChainOriginFnTy;
410   FunctionType *DFSanMemOriginTransferFnTy;
411   FunctionType *DFSanMaybeStoreOriginFnTy;
412   FunctionCallee DFSanUnionFn;
413   FunctionCallee DFSanCheckedUnionFn;
414   FunctionCallee DFSanUnionLoadFn;
415   FunctionCallee DFSanUnionLoadFast16LabelsFn;
416   FunctionCallee DFSanLoadLabelAndOriginFn;
417   FunctionCallee DFSanUnimplementedFn;
418   FunctionCallee DFSanSetLabelFn;
419   FunctionCallee DFSanNonzeroLabelFn;
420   FunctionCallee DFSanVarargWrapperFn;
421   FunctionCallee DFSanLoadCallbackFn;
422   FunctionCallee DFSanStoreCallbackFn;
423   FunctionCallee DFSanMemTransferCallbackFn;
424   FunctionCallee DFSanCmpCallbackFn;
425   FunctionCallee DFSanChainOriginFn;
426   FunctionCallee DFSanMemOriginTransferFn;
427   FunctionCallee DFSanMaybeStoreOriginFn;
428   SmallPtrSet<Value *, 16> DFSanRuntimeFunctions;
429   MDNode *ColdCallWeights;
430   DFSanABIList ABIList;
431   DenseMap<Value *, Function *> UnwrappedFnMap;
432   AttrBuilder ReadOnlyNoneAttrs;
433   bool DFSanRuntimeShadowMask = false;
434 
435   Value *getShadowOffset(Value *Addr, IRBuilder<> &IRB);
436   Value *getShadowAddress(Value *Addr, Instruction *Pos);
437   // std::pair<Value *, Value *>
438   // getShadowOriginAddress(Value *Addr, Align InstAlignment, Instruction *Pos);
439   bool isInstrumented(const Function *F);
440   bool isInstrumented(const GlobalAlias *GA);
441   FunctionType *getArgsFunctionType(FunctionType *T);
442   FunctionType *getTrampolineFunctionType(FunctionType *T);
443   TransformedFunction getCustomFunctionType(FunctionType *T);
444   InstrumentedABI getInstrumentedABI();
445   WrapperKind getWrapperKind(Function *F);
446   void addGlobalNamePrefix(GlobalValue *GV);
447   Function *buildWrapperFunction(Function *F, StringRef NewFName,
448                                  GlobalValue::LinkageTypes NewFLink,
449                                  FunctionType *NewFT);
450   Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
451   void initializeCallbackFunctions(Module &M);
452   void initializeRuntimeFunctions(Module &M);
453 
454   bool init(Module &M);
455 
456   /// Returns whether the pass tracks origins. Support only fast16 mode in TLS
457   /// ABI mode.
458   bool shouldTrackOrigins();
459 
460   /// Returns whether the pass tracks labels for struct fields and array
461   /// indices. Support only fast16 mode in TLS ABI mode.
462   bool shouldTrackFieldsAndIndices();
463 
464   /// Returns a zero constant with the shadow type of OrigTy.
465   ///
466   /// getZeroShadow({T1,T2,...}) = {getZeroShadow(T1),getZeroShadow(T2,...}
467   /// getZeroShadow([n x T]) = [n x getZeroShadow(T)]
468   /// getZeroShadow(other type) = i16(0)
469   ///
470   /// Note that a zero shadow is always i16(0) when shouldTrackFieldsAndIndices
471   /// returns false.
472   Constant *getZeroShadow(Type *OrigTy);
473   /// Returns a zero constant with the shadow type of V's type.
474   Constant *getZeroShadow(Value *V);
475 
476   /// Checks if V is a zero shadow.
477   bool isZeroShadow(Value *V);
478 
479   /// Returns the shadow type of OrigTy.
480   ///
481   /// getShadowTy({T1,T2,...}) = {getShadowTy(T1),getShadowTy(T2),...}
482   /// getShadowTy([n x T]) = [n x getShadowTy(T)]
483   /// getShadowTy(other type) = i16
484   ///
485   /// Note that a shadow type is always i16 when shouldTrackFieldsAndIndices
486   /// returns false.
487   Type *getShadowTy(Type *OrigTy);
488   /// Returns the shadow type of of V's type.
489   Type *getShadowTy(Value *V);
490 
491   const uint64_t kNumOfElementsInArgOrgTLS = kArgTLSSize / OriginWidthBytes;
492 
493 public:
494   DataFlowSanitizer(const std::vector<std::string> &ABIListFiles);
495 
496   bool runImpl(Module &M);
497 };
498 
499 struct DFSanFunction {
500   DataFlowSanitizer &DFS;
501   Function *F;
502   DominatorTree DT;
503   DataFlowSanitizer::InstrumentedABI IA;
504   bool IsNativeABI;
505   AllocaInst *LabelReturnAlloca = nullptr;
506   DenseMap<Value *, Value *> ValShadowMap;
507   DenseMap<Value *, Value *> ValOriginMap;
508   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
509   std::vector<std::pair<PHINode *, PHINode *>> PHIFixups;
510   DenseSet<Instruction *> SkipInsts;
511   std::vector<Value *> NonZeroChecks;
512   bool AvoidNewBlocks;
513 
514   struct CachedShadow {
515     BasicBlock *Block; // The block where Shadow is defined.
516     Value *Shadow;
517   };
518   /// Maps a value to its latest shadow value in terms of domination tree.
519   DenseMap<std::pair<Value *, Value *>, CachedShadow> CachedShadows;
520   /// Maps a value to its latest collapsed shadow value it was converted to in
521   /// terms of domination tree. When ClDebugNonzeroLabels is on, this cache is
522   /// used at a post process where CFG blocks are split. So it does not cache
523   /// BasicBlock like CachedShadows, but uses domination between values.
524   DenseMap<Value *, Value *> CachedCollapsedShadows;
525   DenseMap<Value *, std::set<Value *>> ShadowElements;
526 
527   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
528       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
529     DT.recalculate(*F);
530     // FIXME: Need to track down the register allocator issue which causes poor
531     // performance in pathological cases with large numbers of basic blocks.
532     AvoidNewBlocks = F->size() > 1000;
533   }
534 
535   /// Computes the shadow address for a given function argument.
536   ///
537   /// Shadow = ArgTLS+ArgOffset.
538   Value *getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB);
539 
540   /// Computes the shadow address for a return value.
541   Value *getRetvalTLS(Type *T, IRBuilder<> &IRB);
542 
543   /// Computes the origin address for a given function argument.
544   ///
545   /// Origin = ArgOriginTLS[ArgNo].
546   // Value *getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB);
547 
548   /// Computes the origin address for a return value.
549   // Value *getRetvalOriginTLS();
550 
551   // Value *getOrigin(Value *V);
552   // void setOrigin(Instruction *I, Value *Origin);
553   Value *getShadow(Value *V);
554   void setShadow(Instruction *I, Value *Shadow);
555   /// Generates IR to compute the union of the two given shadows, inserting it
556   /// before Pos. The combined value is with primitive type.
557   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
558   /// Combines the shadow values of V1 and V2, then converts the combined value
559   /// with primitive type into a shadow value with the original type T.
560   Value *combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
561                                    Instruction *Pos);
562   Value *combineOperandShadows(Instruction *Inst);
563   Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
564                     Instruction *Pos);
565   void storePrimitiveShadow(Value *Addr, uint64_t Size, Align Alignment,
566                             Value *PrimitiveShadow, Instruction *Pos);
567   /// Applies PrimitiveShadow to all primitive subtypes of T, returning
568   /// the expanded shadow value.
569   ///
570   /// EFP({T1,T2, ...}, PS) = {EFP(T1,PS),EFP(T2,PS),...}
571   /// EFP([n x T], PS) = [n x EFP(T,PS)]
572   /// EFP(other types, PS) = PS
573   Value *expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
574                                    Instruction *Pos);
575   /// Collapses Shadow into a single primitive shadow value, unioning all
576   /// primitive shadow values in the process. Returns the final primitive
577   /// shadow value.
578   ///
579   /// CTP({V1,V2, ...}) = UNION(CFP(V1,PS),CFP(V2,PS),...)
580   /// CTP([V1,V2,...]) = UNION(CFP(V1,PS),CFP(V2,PS),...)
581   /// CTP(other types, PS) = PS
582   Value *collapseToPrimitiveShadow(Value *Shadow, Instruction *Pos);
583 
584 private:
585   /// Collapses the shadow with aggregate type into a single primitive shadow
586   /// value.
587   template <class AggregateType>
588   Value *collapseAggregateShadow(AggregateType *AT, Value *Shadow,
589                                  IRBuilder<> &IRB);
590 
591   Value *collapseToPrimitiveShadow(Value *Shadow, IRBuilder<> &IRB);
592 
593   /// Returns the shadow value of an argument A.
594   Value *getShadowForTLSArgument(Argument *A);
595 
596   /// The fast path of loading shadow in legacy mode.
597   Value *loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size,
598                               Align ShadowAlign, Instruction *Pos);
599 
600   /// The fast path of loading shadow in fast-16-label mode.
601   Value *loadFast16ShadowFast(Value *ShadowAddr, uint64_t Size,
602                               Align ShadowAlign, Instruction *Pos);
603 };
604 
605 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
606 public:
607   DFSanFunction &DFSF;
608 
609   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
610 
611   const DataLayout &getDataLayout() const {
612     return DFSF.F->getParent()->getDataLayout();
613   }
614 
615   // Combines shadow values for all of I's operands. Returns the combined shadow
616   // value.
617   Value *visitOperandShadowInst(Instruction &I);
618 
619   void visitUnaryOperator(UnaryOperator &UO);
620   void visitBinaryOperator(BinaryOperator &BO);
621   void visitCastInst(CastInst &CI);
622   void visitCmpInst(CmpInst &CI);
623   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
624   void visitLoadInst(LoadInst &LI);
625   void visitStoreInst(StoreInst &SI);
626   void visitReturnInst(ReturnInst &RI);
627   void visitCallBase(CallBase &CB);
628   void visitPHINode(PHINode &PN);
629   void visitExtractElementInst(ExtractElementInst &I);
630   void visitInsertElementInst(InsertElementInst &I);
631   void visitShuffleVectorInst(ShuffleVectorInst &I);
632   void visitExtractValueInst(ExtractValueInst &I);
633   void visitInsertValueInst(InsertValueInst &I);
634   void visitAllocaInst(AllocaInst &I);
635   void visitSelectInst(SelectInst &I);
636   void visitMemSetInst(MemSetInst &I);
637   void visitMemTransferInst(MemTransferInst &I);
638 
639 private:
640   // Returns false when this is an invoke of a custom function.
641   bool visitWrappedCallBase(Function &F, CallBase &CB);
642 };
643 
644 } // end anonymous namespace
645 
646 DataFlowSanitizer::DataFlowSanitizer(
647     const std::vector<std::string> &ABIListFiles) {
648   std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
649   llvm::append_range(AllABIListFiles, ClABIListFiles);
650   // FIXME: should we propagate vfs::FileSystem to this constructor?
651   ABIList.set(
652       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
653 }
654 
655 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
656   SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
657   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
658   if (T->isVarArg())
659     ArgTypes.push_back(PrimitiveShadowPtrTy);
660   Type *RetType = T->getReturnType();
661   if (!RetType->isVoidTy())
662     RetType = StructType::get(RetType, PrimitiveShadowTy);
663   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
664 }
665 
666 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
667   assert(!T->isVarArg());
668   SmallVector<Type *, 4> ArgTypes;
669   ArgTypes.push_back(T->getPointerTo());
670   ArgTypes.append(T->param_begin(), T->param_end());
671   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
672   Type *RetType = T->getReturnType();
673   if (!RetType->isVoidTy())
674     ArgTypes.push_back(PrimitiveShadowPtrTy);
675   return FunctionType::get(T->getReturnType(), ArgTypes, false);
676 }
677 
678 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
679   SmallVector<Type *, 4> ArgTypes;
680 
681   // Some parameters of the custom function being constructed are
682   // parameters of T.  Record the mapping from parameters of T to
683   // parameters of the custom function, so that parameter attributes
684   // at call sites can be updated.
685   std::vector<unsigned> ArgumentIndexMapping;
686   for (unsigned i = 0, ie = T->getNumParams(); i != ie; ++i) {
687     Type* param_type = T->getParamType(i);
688     FunctionType *FT;
689     if (isa<PointerType>(param_type) && (FT = dyn_cast<FunctionType>(
690             cast<PointerType>(param_type)->getElementType()))) {
691       ArgumentIndexMapping.push_back(ArgTypes.size());
692       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
693       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
694     } else {
695       ArgumentIndexMapping.push_back(ArgTypes.size());
696       ArgTypes.push_back(param_type);
697     }
698   }
699   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
700     ArgTypes.push_back(PrimitiveShadowTy);
701   if (T->isVarArg())
702     ArgTypes.push_back(PrimitiveShadowPtrTy);
703   Type *RetType = T->getReturnType();
704   if (!RetType->isVoidTy())
705     ArgTypes.push_back(PrimitiveShadowPtrTy);
706   return TransformedFunction(
707       T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
708       ArgumentIndexMapping);
709 }
710 
711 bool DataFlowSanitizer::isZeroShadow(Value *V) {
712   if (!shouldTrackFieldsAndIndices())
713     return ZeroPrimitiveShadow == V;
714 
715   Type *T = V->getType();
716   if (!isa<ArrayType>(T) && !isa<StructType>(T)) {
717     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
718       return CI->isZero();
719     return false;
720   }
721 
722   return isa<ConstantAggregateZero>(V);
723 }
724 
725 bool DataFlowSanitizer::shouldTrackOrigins() {
726   return ClTrackOrigins && getInstrumentedABI() == DataFlowSanitizer::IA_TLS &&
727          ClFast16Labels;
728 }
729 
730 bool DataFlowSanitizer::shouldTrackFieldsAndIndices() {
731   return getInstrumentedABI() == DataFlowSanitizer::IA_TLS && ClFast16Labels;
732 }
733 
734 Constant *DataFlowSanitizer::getZeroShadow(Type *OrigTy) {
735   if (!shouldTrackFieldsAndIndices())
736     return ZeroPrimitiveShadow;
737 
738   if (!isa<ArrayType>(OrigTy) && !isa<StructType>(OrigTy))
739     return ZeroPrimitiveShadow;
740   Type *ShadowTy = getShadowTy(OrigTy);
741   return ConstantAggregateZero::get(ShadowTy);
742 }
743 
744 Constant *DataFlowSanitizer::getZeroShadow(Value *V) {
745   return getZeroShadow(V->getType());
746 }
747 
748 static Value *expandFromPrimitiveShadowRecursive(
749     Value *Shadow, SmallVector<unsigned, 4> &Indices, Type *SubShadowTy,
750     Value *PrimitiveShadow, IRBuilder<> &IRB) {
751   if (!isa<ArrayType>(SubShadowTy) && !isa<StructType>(SubShadowTy))
752     return IRB.CreateInsertValue(Shadow, PrimitiveShadow, Indices);
753 
754   if (ArrayType *AT = dyn_cast<ArrayType>(SubShadowTy)) {
755     for (unsigned Idx = 0; Idx < AT->getNumElements(); Idx++) {
756       Indices.push_back(Idx);
757       Shadow = expandFromPrimitiveShadowRecursive(
758           Shadow, Indices, AT->getElementType(), PrimitiveShadow, IRB);
759       Indices.pop_back();
760     }
761     return Shadow;
762   }
763 
764   if (StructType *ST = dyn_cast<StructType>(SubShadowTy)) {
765     for (unsigned Idx = 0; Idx < ST->getNumElements(); Idx++) {
766       Indices.push_back(Idx);
767       Shadow = expandFromPrimitiveShadowRecursive(
768           Shadow, Indices, ST->getElementType(Idx), PrimitiveShadow, IRB);
769       Indices.pop_back();
770     }
771     return Shadow;
772   }
773   llvm_unreachable("Unexpected shadow type");
774 }
775 
776 Value *DFSanFunction::expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
777                                                 Instruction *Pos) {
778   Type *ShadowTy = DFS.getShadowTy(T);
779 
780   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
781     return PrimitiveShadow;
782 
783   if (DFS.isZeroShadow(PrimitiveShadow))
784     return DFS.getZeroShadow(ShadowTy);
785 
786   IRBuilder<> IRB(Pos);
787   SmallVector<unsigned, 4> Indices;
788   Value *Shadow = UndefValue::get(ShadowTy);
789   Shadow = expandFromPrimitiveShadowRecursive(Shadow, Indices, ShadowTy,
790                                               PrimitiveShadow, IRB);
791 
792   // Caches the primitive shadow value that built the shadow value.
793   CachedCollapsedShadows[Shadow] = PrimitiveShadow;
794   return Shadow;
795 }
796 
797 template <class AggregateType>
798 Value *DFSanFunction::collapseAggregateShadow(AggregateType *AT, Value *Shadow,
799                                               IRBuilder<> &IRB) {
800   if (!AT->getNumElements())
801     return DFS.ZeroPrimitiveShadow;
802 
803   Value *FirstItem = IRB.CreateExtractValue(Shadow, 0);
804   Value *Aggregator = collapseToPrimitiveShadow(FirstItem, IRB);
805 
806   for (unsigned Idx = 1; Idx < AT->getNumElements(); Idx++) {
807     Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
808     Value *ShadowInner = collapseToPrimitiveShadow(ShadowItem, IRB);
809     Aggregator = IRB.CreateOr(Aggregator, ShadowInner);
810   }
811   return Aggregator;
812 }
813 
814 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
815                                                 IRBuilder<> &IRB) {
816   Type *ShadowTy = Shadow->getType();
817   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
818     return Shadow;
819   if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy))
820     return collapseAggregateShadow<>(AT, Shadow, IRB);
821   if (StructType *ST = dyn_cast<StructType>(ShadowTy))
822     return collapseAggregateShadow<>(ST, Shadow, IRB);
823   llvm_unreachable("Unexpected shadow type");
824 }
825 
826 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
827                                                 Instruction *Pos) {
828   Type *ShadowTy = Shadow->getType();
829   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
830     return Shadow;
831 
832   assert(DFS.shouldTrackFieldsAndIndices());
833 
834   // Checks if the cached collapsed shadow value dominates Pos.
835   Value *&CS = CachedCollapsedShadows[Shadow];
836   if (CS && DT.dominates(CS, Pos))
837     return CS;
838 
839   IRBuilder<> IRB(Pos);
840   Value *PrimitiveShadow = collapseToPrimitiveShadow(Shadow, IRB);
841   // Caches the converted primitive shadow value.
842   CS = PrimitiveShadow;
843   return PrimitiveShadow;
844 }
845 
846 Type *DataFlowSanitizer::getShadowTy(Type *OrigTy) {
847   if (!shouldTrackFieldsAndIndices())
848     return PrimitiveShadowTy;
849 
850   if (!OrigTy->isSized())
851     return PrimitiveShadowTy;
852   if (isa<IntegerType>(OrigTy))
853     return PrimitiveShadowTy;
854   if (isa<VectorType>(OrigTy))
855     return PrimitiveShadowTy;
856   if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy))
857     return ArrayType::get(getShadowTy(AT->getElementType()),
858                           AT->getNumElements());
859   if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
860     SmallVector<Type *, 4> Elements;
861     for (unsigned I = 0, N = ST->getNumElements(); I < N; ++I)
862       Elements.push_back(getShadowTy(ST->getElementType(I)));
863     return StructType::get(*Ctx, Elements);
864   }
865   return PrimitiveShadowTy;
866 }
867 
868 Type *DataFlowSanitizer::getShadowTy(Value *V) {
869   return getShadowTy(V->getType());
870 }
871 
872 bool DataFlowSanitizer::init(Module &M) {
873   Triple TargetTriple(M.getTargetTriple());
874   bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
875   bool IsMIPS64 = TargetTriple.isMIPS64();
876   bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||
877                    TargetTriple.getArch() == Triple::aarch64_be;
878 
879   const DataLayout &DL = M.getDataLayout();
880 
881   Mod = &M;
882   Ctx = &M.getContext();
883   Int8Ptr = Type::getInt8PtrTy(*Ctx);
884   OriginTy = IntegerType::get(*Ctx, OriginWidthBits);
885   OriginPtrTy = PointerType::getUnqual(OriginTy);
886   PrimitiveShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
887   PrimitiveShadowPtrTy = PointerType::getUnqual(PrimitiveShadowTy);
888   IntptrTy = DL.getIntPtrType(*Ctx);
889   ZeroPrimitiveShadow = ConstantInt::getSigned(PrimitiveShadowTy, 0);
890   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidthBytes);
891   OriginBase = ConstantInt::get(IntptrTy, 0x200000000000LL);
892   ZeroOrigin = ConstantInt::getSigned(OriginTy, 0);
893   if (IsX86_64)
894     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
895   else if (IsMIPS64)
896     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
897   // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
898   else if (IsAArch64)
899     DFSanRuntimeShadowMask = true;
900   else
901     report_fatal_error("unsupported triple");
902 
903   Type *DFSanUnionArgs[2] = {PrimitiveShadowTy, PrimitiveShadowTy};
904   DFSanUnionFnTy =
905       FunctionType::get(PrimitiveShadowTy, DFSanUnionArgs, /*isVarArg=*/false);
906   Type *DFSanUnionLoadArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
907   DFSanUnionLoadFnTy = FunctionType::get(PrimitiveShadowTy, DFSanUnionLoadArgs,
908                                          /*isVarArg=*/false);
909   Type *DFSanLoadLabelAndOriginArgs[2] = {Int8Ptr, IntptrTy};
910   DFSanLoadLabelAndOriginFnTy =
911       FunctionType::get(IntegerType::get(*Ctx, 64), DFSanLoadLabelAndOriginArgs,
912                         /*isVarArg=*/false);
913   DFSanUnimplementedFnTy = FunctionType::get(
914       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
915   Type *DFSanSetLabelArgs[3] = {PrimitiveShadowTy, Type::getInt8PtrTy(*Ctx),
916                                 IntptrTy};
917   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
918                                         DFSanSetLabelArgs, /*isVarArg=*/false);
919   DFSanNonzeroLabelFnTy =
920       FunctionType::get(Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
921   DFSanVarargWrapperFnTy = FunctionType::get(
922       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
923   DFSanCmpCallbackFnTy =
924       FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy,
925                         /*isVarArg=*/false);
926   DFSanChainOriginFnTy =
927       FunctionType::get(OriginTy, OriginTy, /*isVarArg=*/false);
928   Type *DFSanMaybeStoreOriginArgs[4] = {IntegerType::get(*Ctx, ShadowWidthBits),
929                                         Int8Ptr, IntptrTy, OriginTy};
930   DFSanMaybeStoreOriginFnTy = FunctionType::get(
931       Type::getVoidTy(*Ctx), DFSanMaybeStoreOriginArgs, /*isVarArg=*/false);
932   Type *DFSanMemOriginTransferArgs[3] = {Int8Ptr, Int8Ptr, IntptrTy};
933   DFSanMemOriginTransferFnTy = FunctionType::get(
934       Type::getVoidTy(*Ctx), DFSanMemOriginTransferArgs, /*isVarArg=*/false);
935   Type *DFSanLoadStoreCallbackArgs[2] = {PrimitiveShadowTy, Int8Ptr};
936   DFSanLoadStoreCallbackFnTy =
937       FunctionType::get(Type::getVoidTy(*Ctx), DFSanLoadStoreCallbackArgs,
938                         /*isVarArg=*/false);
939   Type *DFSanMemTransferCallbackArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
940   DFSanMemTransferCallbackFnTy =
941       FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs,
942                         /*isVarArg=*/false);
943 
944   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
945   return true;
946 }
947 
948 bool DataFlowSanitizer::isInstrumented(const Function *F) {
949   return !ABIList.isIn(*F, "uninstrumented");
950 }
951 
952 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
953   return !ABIList.isIn(*GA, "uninstrumented");
954 }
955 
956 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
957   return ClArgsABI ? IA_Args : IA_TLS;
958 }
959 
960 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
961   if (ABIList.isIn(*F, "functional"))
962     return WK_Functional;
963   if (ABIList.isIn(*F, "discard"))
964     return WK_Discard;
965   if (ABIList.isIn(*F, "custom"))
966     return WK_Custom;
967 
968   return WK_Warning;
969 }
970 
971 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
972   std::string GVName = std::string(GV->getName()), Prefix = "dfs$";
973   GV->setName(Prefix + GVName);
974 
975   // Try to change the name of the function in module inline asm.  We only do
976   // this for specific asm directives, currently only ".symver", to try to avoid
977   // corrupting asm which happens to contain the symbol name as a substring.
978   // Note that the substitution for .symver assumes that the versioned symbol
979   // also has an instrumented name.
980   std::string Asm = GV->getParent()->getModuleInlineAsm();
981   std::string SearchStr = ".symver " + GVName + ",";
982   size_t Pos = Asm.find(SearchStr);
983   if (Pos != std::string::npos) {
984     Asm.replace(Pos, SearchStr.size(),
985                 ".symver " + Prefix + GVName + "," + Prefix);
986     GV->getParent()->setModuleInlineAsm(Asm);
987   }
988 }
989 
990 Function *
991 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
992                                         GlobalValue::LinkageTypes NewFLink,
993                                         FunctionType *NewFT) {
994   FunctionType *FT = F->getFunctionType();
995   Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
996                                     NewFName, F->getParent());
997   NewF->copyAttributesFrom(F);
998   NewF->removeAttributes(
999       AttributeList::ReturnIndex,
1000       AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1001 
1002   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
1003   if (F->isVarArg()) {
1004     NewF->removeAttributes(AttributeList::FunctionIndex,
1005                            AttrBuilder().addAttribute("split-stack"));
1006     CallInst::Create(DFSanVarargWrapperFn,
1007                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
1008                      BB);
1009     new UnreachableInst(*Ctx, BB);
1010   } else {
1011     std::vector<Value *> Args;
1012     unsigned n = FT->getNumParams();
1013     for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
1014       Args.push_back(&*ai);
1015     CallInst *CI = CallInst::Create(F, Args, "", BB);
1016     if (FT->getReturnType()->isVoidTy())
1017       ReturnInst::Create(*Ctx, BB);
1018     else
1019       ReturnInst::Create(*Ctx, CI, BB);
1020   }
1021 
1022   return NewF;
1023 }
1024 
1025 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
1026                                                           StringRef FName) {
1027   FunctionType *FTT = getTrampolineFunctionType(FT);
1028   FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
1029   Function *F = dyn_cast<Function>(C.getCallee());
1030   if (F && F->isDeclaration()) {
1031     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
1032     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
1033     std::vector<Value *> Args;
1034     Function::arg_iterator AI = F->arg_begin(); ++AI;
1035     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
1036       Args.push_back(&*AI);
1037     CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
1038     ReturnInst *RI;
1039     if (FT->getReturnType()->isVoidTy())
1040       RI = ReturnInst::Create(*Ctx, BB);
1041     else
1042       RI = ReturnInst::Create(*Ctx, CI, BB);
1043 
1044     // F is called by a wrapped custom function with primitive shadows. So
1045     // its arguments and return value need conversion.
1046     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
1047     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
1048     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N) {
1049       Value *Shadow =
1050           DFSF.expandFromPrimitiveShadow(ValAI->getType(), &*ShadowAI, CI);
1051       DFSF.ValShadowMap[&*ValAI] = Shadow;
1052     }
1053     DFSanVisitor(DFSF).visitCallInst(*CI);
1054     if (!FT->getReturnType()->isVoidTy()) {
1055       Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(
1056           DFSF.getShadow(RI->getReturnValue()), RI);
1057       new StoreInst(PrimitiveShadow, &*std::prev(F->arg_end()), RI);
1058     }
1059   }
1060 
1061   return cast<Constant>(C.getCallee());
1062 }
1063 
1064 // Initialize DataFlowSanitizer runtime functions and declare them in the module
1065 void DataFlowSanitizer::initializeRuntimeFunctions(Module &M) {
1066   {
1067     AttributeList AL;
1068     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1069                          Attribute::NoUnwind);
1070     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1071                          Attribute::ReadNone);
1072     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1073                          Attribute::ZExt);
1074     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1075     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1076     DFSanUnionFn =
1077         Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL);
1078   }
1079   {
1080     AttributeList AL;
1081     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1082                          Attribute::NoUnwind);
1083     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1084                          Attribute::ReadNone);
1085     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1086                          Attribute::ZExt);
1087     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1088     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1089     DFSanCheckedUnionFn =
1090         Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL);
1091   }
1092   {
1093     AttributeList AL;
1094     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1095                          Attribute::NoUnwind);
1096     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1097                          Attribute::ReadOnly);
1098     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1099                          Attribute::ZExt);
1100     DFSanUnionLoadFn =
1101         Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
1102   }
1103   {
1104     AttributeList AL;
1105     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1106                          Attribute::NoUnwind);
1107     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1108                          Attribute::ReadOnly);
1109     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1110                          Attribute::ZExt);
1111     DFSanUnionLoadFast16LabelsFn = Mod->getOrInsertFunction(
1112         "__dfsan_union_load_fast16labels", DFSanUnionLoadFnTy, AL);
1113   }
1114   {
1115     AttributeList AL;
1116     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1117                          Attribute::NoUnwind);
1118     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1119                          Attribute::ReadOnly);
1120     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1121                          Attribute::ZExt);
1122     DFSanLoadLabelAndOriginFn = Mod->getOrInsertFunction(
1123         "__dfsan_load_label_and_origin", DFSanLoadLabelAndOriginFnTy, AL);
1124   }
1125   DFSanUnimplementedFn =
1126       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
1127   {
1128     AttributeList AL;
1129     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1130     DFSanSetLabelFn =
1131         Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
1132   }
1133   DFSanNonzeroLabelFn =
1134       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
1135   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
1136                                                   DFSanVarargWrapperFnTy);
1137   {
1138     AttributeList AL;
1139     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1140     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1141                          Attribute::ZExt);
1142     DFSanChainOriginFn = Mod->getOrInsertFunction("__dfsan_chain_origin",
1143                                                   DFSanChainOriginFnTy, AL);
1144   }
1145   DFSanMemOriginTransferFn = Mod->getOrInsertFunction(
1146       "__dfsan_mem_origin_transfer", DFSanMemOriginTransferFnTy);
1147 
1148   {
1149     AttributeList AL;
1150     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1151     AL = AL.addParamAttribute(M.getContext(), 3, Attribute::ZExt);
1152     DFSanMaybeStoreOriginFn = Mod->getOrInsertFunction(
1153         "__dfsan_maybe_store_origin", DFSanMaybeStoreOriginFnTy, AL);
1154   }
1155 
1156   DFSanRuntimeFunctions.insert(DFSanUnionFn.getCallee()->stripPointerCasts());
1157   DFSanRuntimeFunctions.insert(
1158       DFSanCheckedUnionFn.getCallee()->stripPointerCasts());
1159   DFSanRuntimeFunctions.insert(
1160       DFSanUnionLoadFn.getCallee()->stripPointerCasts());
1161   DFSanRuntimeFunctions.insert(
1162       DFSanUnionLoadFast16LabelsFn.getCallee()->stripPointerCasts());
1163   DFSanRuntimeFunctions.insert(
1164       DFSanLoadLabelAndOriginFn.getCallee()->stripPointerCasts());
1165   DFSanRuntimeFunctions.insert(
1166       DFSanUnimplementedFn.getCallee()->stripPointerCasts());
1167   DFSanRuntimeFunctions.insert(
1168       DFSanSetLabelFn.getCallee()->stripPointerCasts());
1169   DFSanRuntimeFunctions.insert(
1170       DFSanNonzeroLabelFn.getCallee()->stripPointerCasts());
1171   DFSanRuntimeFunctions.insert(
1172       DFSanVarargWrapperFn.getCallee()->stripPointerCasts());
1173   DFSanRuntimeFunctions.insert(
1174       DFSanLoadCallbackFn.getCallee()->stripPointerCasts());
1175   DFSanRuntimeFunctions.insert(
1176       DFSanStoreCallbackFn.getCallee()->stripPointerCasts());
1177   DFSanRuntimeFunctions.insert(
1178       DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts());
1179   DFSanRuntimeFunctions.insert(
1180       DFSanCmpCallbackFn.getCallee()->stripPointerCasts());
1181   DFSanRuntimeFunctions.insert(
1182       DFSanChainOriginFn.getCallee()->stripPointerCasts());
1183   DFSanRuntimeFunctions.insert(
1184       DFSanMemOriginTransferFn.getCallee()->stripPointerCasts());
1185   DFSanRuntimeFunctions.insert(
1186       DFSanMaybeStoreOriginFn.getCallee()->stripPointerCasts());
1187 }
1188 
1189 // Initializes event callback functions and declare them in the module
1190 void DataFlowSanitizer::initializeCallbackFunctions(Module &M) {
1191   DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback",
1192                                                  DFSanLoadStoreCallbackFnTy);
1193   DFSanStoreCallbackFn = Mod->getOrInsertFunction("__dfsan_store_callback",
1194                                                   DFSanLoadStoreCallbackFnTy);
1195   DFSanMemTransferCallbackFn = Mod->getOrInsertFunction(
1196       "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy);
1197   DFSanCmpCallbackFn =
1198       Mod->getOrInsertFunction("__dfsan_cmp_callback", DFSanCmpCallbackFnTy);
1199 }
1200 
1201 bool DataFlowSanitizer::runImpl(Module &M) {
1202   init(M);
1203 
1204   if (ABIList.isIn(M, "skip"))
1205     return false;
1206 
1207   const unsigned InitialGlobalSize = M.global_size();
1208   const unsigned InitialModuleSize = M.size();
1209 
1210   bool Changed = false;
1211 
1212   auto getOrInsertGlobal = [this, &Changed](StringRef Name,
1213                                             Type *Ty) -> Constant * {
1214     Constant *C = Mod->getOrInsertGlobal(Name, Ty);
1215     if (GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1216       Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel;
1217       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
1218     }
1219     return C;
1220   };
1221 
1222   // These globals must be kept in sync with the ones in dfsan.cpp.
1223   ArgTLS = getOrInsertGlobal(
1224       "__dfsan_arg_tls",
1225       ArrayType::get(Type::getInt64Ty(*Ctx), kArgTLSSize / 8));
1226   RetvalTLS = getOrInsertGlobal(
1227       "__dfsan_retval_tls",
1228       ArrayType::get(Type::getInt64Ty(*Ctx), kRetvalTLSSize / 8));
1229   ArgOriginTLSTy = ArrayType::get(OriginTy, kNumOfElementsInArgOrgTLS);
1230   ArgOriginTLS = getOrInsertGlobal("__dfsan_arg_origin_tls", ArgOriginTLSTy);
1231   RetvalOriginTLS = getOrInsertGlobal("__dfsan_retval_origin_tls", OriginTy);
1232 
1233   (void)Mod->getOrInsertGlobal("__dfsan_track_origins", OriginTy, [&] {
1234     Changed = true;
1235     return new GlobalVariable(
1236         M, OriginTy, true, GlobalValue::WeakODRLinkage,
1237         ConstantInt::getSigned(OriginTy, shouldTrackOrigins()),
1238         "__dfsan_track_origins");
1239   });
1240 
1241   ExternalShadowMask =
1242       Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
1243 
1244   initializeCallbackFunctions(M);
1245   initializeRuntimeFunctions(M);
1246 
1247   std::vector<Function *> FnsToInstrument;
1248   SmallPtrSet<Function *, 2> FnsWithNativeABI;
1249   for (Function &i : M)
1250     if (!i.isIntrinsic() && !DFSanRuntimeFunctions.contains(&i))
1251       FnsToInstrument.push_back(&i);
1252 
1253   // Give function aliases prefixes when necessary, and build wrappers where the
1254   // instrumentedness is inconsistent.
1255   for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
1256     GlobalAlias *GA = &*i;
1257     ++i;
1258     // Don't stop on weak.  We assume people aren't playing games with the
1259     // instrumentedness of overridden weak aliases.
1260     if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
1261       bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
1262       if (GAInst && FInst) {
1263         addGlobalNamePrefix(GA);
1264       } else if (GAInst != FInst) {
1265         // Non-instrumented alias of an instrumented function, or vice versa.
1266         // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
1267         // below will take care of instrumenting it.
1268         Function *NewF =
1269             buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
1270         GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
1271         NewF->takeName(GA);
1272         GA->eraseFromParent();
1273         FnsToInstrument.push_back(NewF);
1274       }
1275     }
1276   }
1277 
1278   ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
1279       .addAttribute(Attribute::ReadNone);
1280 
1281   // First, change the ABI of every function in the module.  ABI-listed
1282   // functions keep their original ABI and get a wrapper function.
1283   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
1284                                          e = FnsToInstrument.end();
1285        i != e; ++i) {
1286     Function &F = **i;
1287     FunctionType *FT = F.getFunctionType();
1288 
1289     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
1290                               FT->getReturnType()->isVoidTy());
1291 
1292     if (isInstrumented(&F)) {
1293       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
1294       // easily identify cases of mismatching ABIs.
1295       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
1296         FunctionType *NewFT = getArgsFunctionType(FT);
1297         Function *NewF = Function::Create(NewFT, F.getLinkage(),
1298                                           F.getAddressSpace(), "", &M);
1299         NewF->copyAttributesFrom(&F);
1300         NewF->removeAttributes(
1301             AttributeList::ReturnIndex,
1302             AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1303         for (Function::arg_iterator FArg = F.arg_begin(),
1304                                     NewFArg = NewF->arg_begin(),
1305                                     FArgEnd = F.arg_end();
1306              FArg != FArgEnd; ++FArg, ++NewFArg) {
1307           FArg->replaceAllUsesWith(&*NewFArg);
1308         }
1309         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
1310 
1311         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
1312              UI != UE;) {
1313           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
1314           ++UI;
1315           if (BA) {
1316             BA->replaceAllUsesWith(
1317                 BlockAddress::get(NewF, BA->getBasicBlock()));
1318             delete BA;
1319           }
1320         }
1321         F.replaceAllUsesWith(
1322             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
1323         NewF->takeName(&F);
1324         F.eraseFromParent();
1325         *i = NewF;
1326         addGlobalNamePrefix(NewF);
1327       } else {
1328         addGlobalNamePrefix(&F);
1329       }
1330     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
1331       // Build a wrapper function for F.  The wrapper simply calls F, and is
1332       // added to FnsToInstrument so that any instrumentation according to its
1333       // WrapperKind is done in the second pass below.
1334       FunctionType *NewFT = getInstrumentedABI() == IA_Args
1335                                 ? getArgsFunctionType(FT)
1336                                 : FT;
1337 
1338       // If the function being wrapped has local linkage, then preserve the
1339       // function's linkage in the wrapper function.
1340       GlobalValue::LinkageTypes wrapperLinkage =
1341           F.hasLocalLinkage()
1342               ? F.getLinkage()
1343               : GlobalValue::LinkOnceODRLinkage;
1344 
1345       Function *NewF = buildWrapperFunction(
1346           &F, std::string("dfsw$") + std::string(F.getName()),
1347           wrapperLinkage, NewFT);
1348       if (getInstrumentedABI() == IA_TLS)
1349         NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
1350 
1351       Value *WrappedFnCst =
1352           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
1353       F.replaceAllUsesWith(WrappedFnCst);
1354 
1355       UnwrappedFnMap[WrappedFnCst] = &F;
1356       *i = NewF;
1357 
1358       if (!F.isDeclaration()) {
1359         // This function is probably defining an interposition of an
1360         // uninstrumented function and hence needs to keep the original ABI.
1361         // But any functions it may call need to use the instrumented ABI, so
1362         // we instrument it in a mode which preserves the original ABI.
1363         FnsWithNativeABI.insert(&F);
1364 
1365         // This code needs to rebuild the iterators, as they may be invalidated
1366         // by the push_back, taking care that the new range does not include
1367         // any functions added by this code.
1368         size_t N = i - FnsToInstrument.begin(),
1369                Count = e - FnsToInstrument.begin();
1370         FnsToInstrument.push_back(&F);
1371         i = FnsToInstrument.begin() + N;
1372         e = FnsToInstrument.begin() + Count;
1373       }
1374                // Hopefully, nobody will try to indirectly call a vararg
1375                // function... yet.
1376     } else if (FT->isVarArg()) {
1377       UnwrappedFnMap[&F] = &F;
1378       *i = nullptr;
1379     }
1380   }
1381 
1382   for (Function *i : FnsToInstrument) {
1383     if (!i || i->isDeclaration())
1384       continue;
1385 
1386     removeUnreachableBlocks(*i);
1387 
1388     DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
1389 
1390     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
1391     // Build a copy of the list before iterating over it.
1392     SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
1393 
1394     for (BasicBlock *i : BBList) {
1395       Instruction *Inst = &i->front();
1396       while (true) {
1397         // DFSanVisitor may split the current basic block, changing the current
1398         // instruction's next pointer and moving the next instruction to the
1399         // tail block from which we should continue.
1400         Instruction *Next = Inst->getNextNode();
1401         // DFSanVisitor may delete Inst, so keep track of whether it was a
1402         // terminator.
1403         bool IsTerminator = Inst->isTerminator();
1404         if (!DFSF.SkipInsts.count(Inst))
1405           DFSanVisitor(DFSF).visit(Inst);
1406         if (IsTerminator)
1407           break;
1408         Inst = Next;
1409       }
1410     }
1411 
1412     // We will not necessarily be able to compute the shadow for every phi node
1413     // until we have visited every block.  Therefore, the code that handles phi
1414     // nodes adds them to the PHIFixups list so that they can be properly
1415     // handled here.
1416     for (std::vector<std::pair<PHINode *, PHINode *>>::iterator
1417              i = DFSF.PHIFixups.begin(),
1418              e = DFSF.PHIFixups.end();
1419          i != e; ++i) {
1420       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
1421            ++val) {
1422         i->second->setIncomingValue(
1423             val, DFSF.getShadow(i->first->getIncomingValue(val)));
1424       }
1425     }
1426 
1427     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
1428     // places (i.e. instructions in basic blocks we haven't even begun visiting
1429     // yet).  To make our life easier, do this work in a pass after the main
1430     // instrumentation.
1431     if (ClDebugNonzeroLabels) {
1432       for (Value *V : DFSF.NonZeroChecks) {
1433         Instruction *Pos;
1434         if (Instruction *I = dyn_cast<Instruction>(V))
1435           Pos = I->getNextNode();
1436         else
1437           Pos = &DFSF.F->getEntryBlock().front();
1438         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
1439           Pos = Pos->getNextNode();
1440         IRBuilder<> IRB(Pos);
1441         Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(V, Pos);
1442         Value *Ne =
1443             IRB.CreateICmpNE(PrimitiveShadow, DFSF.DFS.ZeroPrimitiveShadow);
1444         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1445             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
1446         IRBuilder<> ThenIRB(BI);
1447         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1448       }
1449     }
1450   }
1451 
1452   return Changed || !FnsToInstrument.empty() ||
1453          M.global_size() != InitialGlobalSize || M.size() != InitialModuleSize;
1454 }
1455 
1456 Value *DFSanFunction::getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB) {
1457   Value *Base = IRB.CreatePointerCast(DFS.ArgTLS, DFS.IntptrTy);
1458   if (ArgOffset)
1459     Base = IRB.CreateAdd(Base, ConstantInt::get(DFS.IntptrTy, ArgOffset));
1460   return IRB.CreateIntToPtr(Base, PointerType::get(DFS.getShadowTy(T), 0),
1461                             "_dfsarg");
1462 }
1463 
1464 Value *DFSanFunction::getRetvalTLS(Type *T, IRBuilder<> &IRB) {
1465   return IRB.CreatePointerCast(
1466       DFS.RetvalTLS, PointerType::get(DFS.getShadowTy(T), 0), "_dfsret");
1467 }
1468 /*
1469 Value *DFSanFunction::getRetvalOriginTLS() { return DFS.RetvalOriginTLS; }
1470 
1471 Value *DFSanFunction::getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB) {
1472   return IRB.CreateConstGEP2_64(DFS.ArgOriginTLSTy, DFS.ArgOriginTLS, 0, ArgNo,
1473                                 "_dfsarg_o");
1474 }
1475 
1476 Value *DFSanFunction::getOrigin(Value *V) {
1477   assert(DFS.shouldTrackOrigins());
1478   if (!isa<Argument>(V) && !isa<Instruction>(V))
1479     return DFS.ZeroOrigin;
1480   Value *&Origin = ValOriginMap[V];
1481   if (!Origin) {
1482     if (Argument *A = dyn_cast<Argument>(V)) {
1483       if (IsNativeABI)
1484         return DFS.ZeroOrigin;
1485       switch (IA) {
1486       case DataFlowSanitizer::IA_TLS: {
1487         if (A->getArgNo() < DFS.kNumOfElementsInArgOrgTLS) {
1488           Instruction *ArgOriginTLSPos = &*F->getEntryBlock().begin();
1489           IRBuilder<> IRB(ArgOriginTLSPos);
1490           Value *ArgOriginPtr = getArgOriginTLS(A->getArgNo(), IRB);
1491           Origin = IRB.CreateLoad(DFS.OriginTy, ArgOriginPtr);
1492         } else {
1493           // Overflow
1494           Origin = DFS.ZeroOrigin;
1495         }
1496         break;
1497       }
1498       case DataFlowSanitizer::IA_Args: {
1499         Origin = DFS.ZeroOrigin;
1500         break;
1501       }
1502       }
1503     } else {
1504       Origin = DFS.ZeroOrigin;
1505     }
1506   }
1507   return Origin;
1508 }
1509 
1510 void DFSanFunction::setOrigin(Instruction *I, Value *Origin) {
1511   if (!DFS.shouldTrackOrigins())
1512     return;
1513   assert(!ValOriginMap.count(I));
1514   assert(Origin->getType() == DFS.OriginTy);
1515   ValOriginMap[I] = Origin;
1516 }
1517 */
1518 Value *DFSanFunction::getShadowForTLSArgument(Argument *A) {
1519   unsigned ArgOffset = 0;
1520   const DataLayout &DL = F->getParent()->getDataLayout();
1521   for (auto &FArg : F->args()) {
1522     if (!FArg.getType()->isSized()) {
1523       if (A == &FArg)
1524         break;
1525       continue;
1526     }
1527 
1528     unsigned Size = DL.getTypeAllocSize(DFS.getShadowTy(&FArg));
1529     if (A != &FArg) {
1530       ArgOffset += alignTo(Size, kShadowTLSAlignment);
1531       if (ArgOffset > kArgTLSSize)
1532         break; // ArgTLS overflows, uses a zero shadow.
1533       continue;
1534     }
1535 
1536     if (ArgOffset + Size > kArgTLSSize)
1537       break; // ArgTLS overflows, uses a zero shadow.
1538 
1539     Instruction *ArgTLSPos = &*F->getEntryBlock().begin();
1540     IRBuilder<> IRB(ArgTLSPos);
1541     Value *ArgShadowPtr = getArgTLS(FArg.getType(), ArgOffset, IRB);
1542     return IRB.CreateAlignedLoad(DFS.getShadowTy(&FArg), ArgShadowPtr,
1543                                  kShadowTLSAlignment);
1544   }
1545 
1546   return DFS.getZeroShadow(A);
1547 }
1548 
1549 Value *DFSanFunction::getShadow(Value *V) {
1550   if (!isa<Argument>(V) && !isa<Instruction>(V))
1551     return DFS.getZeroShadow(V);
1552   Value *&Shadow = ValShadowMap[V];
1553   if (!Shadow) {
1554     if (Argument *A = dyn_cast<Argument>(V)) {
1555       if (IsNativeABI)
1556         return DFS.getZeroShadow(V);
1557       switch (IA) {
1558       case DataFlowSanitizer::IA_TLS: {
1559         Shadow = getShadowForTLSArgument(A);
1560         break;
1561       }
1562       case DataFlowSanitizer::IA_Args: {
1563         unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
1564         Function::arg_iterator i = F->arg_begin();
1565         while (ArgIdx--)
1566           ++i;
1567         Shadow = &*i;
1568         assert(Shadow->getType() == DFS.PrimitiveShadowTy);
1569         break;
1570       }
1571       }
1572       NonZeroChecks.push_back(Shadow);
1573     } else {
1574       Shadow = DFS.getZeroShadow(V);
1575     }
1576   }
1577   return Shadow;
1578 }
1579 
1580 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1581   assert(!ValShadowMap.count(I));
1582   assert(DFS.shouldTrackFieldsAndIndices() ||
1583          Shadow->getType() == DFS.PrimitiveShadowTy);
1584   ValShadowMap[I] = Shadow;
1585 }
1586 
1587 Value *DataFlowSanitizer::getShadowOffset(Value *Addr, IRBuilder<> &IRB) {
1588   // Returns Addr & shadow_mask
1589   assert(Addr != RetvalTLS && "Reinstrumenting?");
1590   Value *ShadowPtrMaskValue;
1591   if (DFSanRuntimeShadowMask)
1592     ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
1593   else
1594     ShadowPtrMaskValue = ShadowPtrMask;
1595   return IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
1596                        IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy));
1597 }
1598 /*
1599 std::pair<Value *, Value *>
1600 DataFlowSanitizer::getShadowOriginAddress(Value *Addr, Align InstAlignment,
1601                                           Instruction *Pos) {
1602   // Returns ((Addr & shadow_mask) + origin_base) & ~4UL
1603   IRBuilder<> IRB(Pos);
1604   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1605   Value *ShadowPtr = IRB.CreateIntToPtr(
1606       IRB.CreateMul(ShadowOffset, ShadowPtrMul), PrimitiveShadowPtrTy);
1607   Value *OriginPtr = nullptr;
1608   if (shouldTrackOrigins()) {
1609     Value *OriginLong = IRB.CreateAdd(ShadowOffset, OriginBase);
1610     const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1611     // When alignment is >= 4, Addr must be aligned to 4, otherwise it is UB.
1612     // So Mask is unnecessary.
1613     if (Alignment < kMinOriginAlignment) {
1614       uint64_t Mask = kMinOriginAlignment.value() - 1;
1615       OriginLong = IRB.CreateAnd(OriginLong, ConstantInt::get(IntptrTy, ~Mask));
1616     }
1617     OriginPtr = IRB.CreateIntToPtr(OriginLong, OriginPtrTy);
1618   }
1619   return {ShadowPtr, OriginPtr};
1620 }
1621 */
1622 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1623   // Returns (Addr & shadow_mask) x 2
1624   IRBuilder<> IRB(Pos);
1625   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1626   return IRB.CreateIntToPtr(IRB.CreateMul(ShadowOffset, ShadowPtrMul),
1627                             PrimitiveShadowPtrTy);
1628 }
1629 
1630 Value *DFSanFunction::combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
1631                                                 Instruction *Pos) {
1632   Value *PrimitiveValue = combineShadows(V1, V2, Pos);
1633   return expandFromPrimitiveShadow(T, PrimitiveValue, Pos);
1634 }
1635 
1636 // Generates IR to compute the union of the two given shadows, inserting it
1637 // before Pos. The combined value is with primitive type.
1638 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1639   if (DFS.isZeroShadow(V1))
1640     return collapseToPrimitiveShadow(V2, Pos);
1641   if (DFS.isZeroShadow(V2))
1642     return collapseToPrimitiveShadow(V1, Pos);
1643   if (V1 == V2)
1644     return collapseToPrimitiveShadow(V1, Pos);
1645 
1646   auto V1Elems = ShadowElements.find(V1);
1647   auto V2Elems = ShadowElements.find(V2);
1648   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1649     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1650                       V2Elems->second.begin(), V2Elems->second.end())) {
1651       return collapseToPrimitiveShadow(V1, Pos);
1652     } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1653                              V1Elems->second.begin(), V1Elems->second.end())) {
1654       return collapseToPrimitiveShadow(V2, Pos);
1655     }
1656   } else if (V1Elems != ShadowElements.end()) {
1657     if (V1Elems->second.count(V2))
1658       return collapseToPrimitiveShadow(V1, Pos);
1659   } else if (V2Elems != ShadowElements.end()) {
1660     if (V2Elems->second.count(V1))
1661       return collapseToPrimitiveShadow(V2, Pos);
1662   }
1663 
1664   auto Key = std::make_pair(V1, V2);
1665   if (V1 > V2)
1666     std::swap(Key.first, Key.second);
1667   CachedShadow &CCS = CachedShadows[Key];
1668   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1669     return CCS.Shadow;
1670 
1671   // Converts inputs shadows to shadows with primitive types.
1672   Value *PV1 = collapseToPrimitiveShadow(V1, Pos);
1673   Value *PV2 = collapseToPrimitiveShadow(V2, Pos);
1674 
1675   IRBuilder<> IRB(Pos);
1676   if (ClFast16Labels) {
1677     CCS.Block = Pos->getParent();
1678     CCS.Shadow = IRB.CreateOr(PV1, PV2);
1679   } else if (AvoidNewBlocks) {
1680     CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {PV1, PV2});
1681     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1682     Call->addParamAttr(0, Attribute::ZExt);
1683     Call->addParamAttr(1, Attribute::ZExt);
1684 
1685     CCS.Block = Pos->getParent();
1686     CCS.Shadow = Call;
1687   } else {
1688     BasicBlock *Head = Pos->getParent();
1689     Value *Ne = IRB.CreateICmpNE(PV1, PV2);
1690     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1691         Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1692     IRBuilder<> ThenIRB(BI);
1693     CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {PV1, PV2});
1694     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1695     Call->addParamAttr(0, Attribute::ZExt);
1696     Call->addParamAttr(1, Attribute::ZExt);
1697 
1698     BasicBlock *Tail = BI->getSuccessor(0);
1699     PHINode *Phi =
1700         PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
1701     Phi->addIncoming(Call, Call->getParent());
1702     Phi->addIncoming(PV1, Head);
1703 
1704     CCS.Block = Tail;
1705     CCS.Shadow = Phi;
1706   }
1707 
1708   std::set<Value *> UnionElems;
1709   if (V1Elems != ShadowElements.end()) {
1710     UnionElems = V1Elems->second;
1711   } else {
1712     UnionElems.insert(V1);
1713   }
1714   if (V2Elems != ShadowElements.end()) {
1715     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1716   } else {
1717     UnionElems.insert(V2);
1718   }
1719   ShadowElements[CCS.Shadow] = std::move(UnionElems);
1720 
1721   return CCS.Shadow;
1722 }
1723 
1724 // A convenience function which folds the shadows of each of the operands
1725 // of the provided instruction Inst, inserting the IR before Inst.  Returns
1726 // the computed union Value.
1727 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1728   if (Inst->getNumOperands() == 0)
1729     return DFS.getZeroShadow(Inst);
1730 
1731   Value *Shadow = getShadow(Inst->getOperand(0));
1732   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
1733     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1734   }
1735   return expandFromPrimitiveShadow(Inst->getType(), Shadow, Inst);
1736 }
1737 
1738 Value *DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1739   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1740   DFSF.setShadow(&I, CombinedShadow);
1741   return CombinedShadow;
1742 }
1743 
1744 Value *DFSanFunction::loadFast16ShadowFast(Value *ShadowAddr, uint64_t Size,
1745                                            Align ShadowAlign,
1746                                            Instruction *Pos) {
1747   // First OR all the WideShadows, then OR individual shadows within the
1748   // combined WideShadow. This is fewer instructions than ORing shadows
1749   // individually.
1750   IRBuilder<> IRB(Pos);
1751   Value *WideAddr =
1752       IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1753   Value *CombinedWideShadow =
1754       IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1755   for (uint64_t Ofs = 64 / DFS.ShadowWidthBits; Ofs != Size;
1756        Ofs += 64 / DFS.ShadowWidthBits) {
1757     WideAddr = IRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1758                              ConstantInt::get(DFS.IntptrTy, 1));
1759     Value *NextWideShadow =
1760         IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1761     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, NextWideShadow);
1762   }
1763   for (unsigned Width = 32; Width >= DFS.ShadowWidthBits; Width >>= 1) {
1764     Value *ShrShadow = IRB.CreateLShr(CombinedWideShadow, Width);
1765     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, ShrShadow);
1766   }
1767   return IRB.CreateTrunc(CombinedWideShadow, DFS.PrimitiveShadowTy);
1768 }
1769 
1770 Value *DFSanFunction::loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size,
1771                                            Align ShadowAlign,
1772                                            Instruction *Pos) {
1773   // Fast path for the common case where each byte has identical shadow: load
1774   // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1775   // shadow is non-equal.
1776   BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1777   IRBuilder<> FallbackIRB(FallbackBB);
1778   CallInst *FallbackCall = FallbackIRB.CreateCall(
1779       DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1780   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1781 
1782   // Compare each of the shadows stored in the loaded 64 bits to each other,
1783   // by computing (WideShadow rotl ShadowWidthBits) == WideShadow.
1784   IRBuilder<> IRB(Pos);
1785   Value *WideAddr =
1786       IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1787   Value *WideShadow =
1788       IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1789   Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.PrimitiveShadowTy);
1790   Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidthBits);
1791   Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidthBits);
1792   Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1793   Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1794 
1795   BasicBlock *Head = Pos->getParent();
1796   BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
1797 
1798   if (DomTreeNode *OldNode = DT.getNode(Head)) {
1799     std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1800 
1801     DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1802     for (auto *Child : Children)
1803       DT.changeImmediateDominator(Child, NewNode);
1804   }
1805 
1806   // In the following code LastBr will refer to the previous basic block's
1807   // conditional branch instruction, whose true successor is fixed up to point
1808   // to the next block during the loop below or to the tail after the final
1809   // iteration.
1810   BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1811   ReplaceInstWithInst(Head->getTerminator(), LastBr);
1812   DT.addNewBlock(FallbackBB, Head);
1813 
1814   for (uint64_t Ofs = 64 / DFS.ShadowWidthBits; Ofs != Size;
1815        Ofs += 64 / DFS.ShadowWidthBits) {
1816     BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1817     DT.addNewBlock(NextBB, LastBr->getParent());
1818     IRBuilder<> NextIRB(NextBB);
1819     WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1820                                  ConstantInt::get(DFS.IntptrTy, 1));
1821     Value *NextWideShadow =
1822         NextIRB.CreateAlignedLoad(NextIRB.getInt64Ty(), WideAddr, ShadowAlign);
1823     ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1824     LastBr->setSuccessor(0, NextBB);
1825     LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1826   }
1827 
1828   LastBr->setSuccessor(0, Tail);
1829   FallbackIRB.CreateBr(Tail);
1830   PHINode *Shadow =
1831       PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
1832   Shadow->addIncoming(FallbackCall, FallbackBB);
1833   Shadow->addIncoming(TruncShadow, LastBr->getParent());
1834   return Shadow;
1835 }
1836 
1837 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1838 // Addr has alignment Align, and take the union of each of those shadows. The
1839 // returned shadow always has primitive type.
1840 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1841                                  Instruction *Pos) {
1842   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1843     const auto i = AllocaShadowMap.find(AI);
1844     if (i != AllocaShadowMap.end()) {
1845       IRBuilder<> IRB(Pos);
1846       return IRB.CreateLoad(DFS.PrimitiveShadowTy, i->second);
1847     }
1848   }
1849 
1850   const llvm::Align ShadowAlign(Align * DFS.ShadowWidthBytes);
1851   SmallVector<const Value *, 2> Objs;
1852   getUnderlyingObjects(Addr, Objs);
1853   bool AllConstants = true;
1854   for (const Value *Obj : Objs) {
1855     if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
1856       continue;
1857     if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
1858       continue;
1859 
1860     AllConstants = false;
1861     break;
1862   }
1863   if (AllConstants)
1864     return DFS.ZeroPrimitiveShadow;
1865 
1866   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1867   switch (Size) {
1868   case 0:
1869     return DFS.ZeroPrimitiveShadow;
1870   case 1: {
1871     LoadInst *LI = new LoadInst(DFS.PrimitiveShadowTy, ShadowAddr, "", Pos);
1872     LI->setAlignment(ShadowAlign);
1873     return LI;
1874   }
1875   case 2: {
1876     IRBuilder<> IRB(Pos);
1877     Value *ShadowAddr1 = IRB.CreateGEP(DFS.PrimitiveShadowTy, ShadowAddr,
1878                                        ConstantInt::get(DFS.IntptrTy, 1));
1879     return combineShadows(
1880         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr, ShadowAlign),
1881         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr1, ShadowAlign),
1882         Pos);
1883   }
1884   }
1885 
1886   if (ClFast16Labels && Size % (64 / DFS.ShadowWidthBits) == 0)
1887     return loadFast16ShadowFast(ShadowAddr, Size, ShadowAlign, Pos);
1888 
1889   if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidthBits) == 0)
1890     return loadLegacyShadowFast(ShadowAddr, Size, ShadowAlign, Pos);
1891 
1892   IRBuilder<> IRB(Pos);
1893   FunctionCallee &UnionLoadFn =
1894       ClFast16Labels ? DFS.DFSanUnionLoadFast16LabelsFn : DFS.DFSanUnionLoadFn;
1895   CallInst *FallbackCall = IRB.CreateCall(
1896       UnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1897   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1898   return FallbackCall;
1899 }
1900 
1901 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1902   auto &DL = LI.getModule()->getDataLayout();
1903   uint64_t Size = DL.getTypeStoreSize(LI.getType());
1904   if (Size == 0) {
1905     DFSF.setShadow(&LI, DFSF.DFS.getZeroShadow(&LI));
1906     return;
1907   }
1908 
1909   Align Alignment = ClPreserveAlignment ? LI.getAlign() : Align(1);
1910   Value *PrimitiveShadow =
1911       DFSF.loadShadow(LI.getPointerOperand(), Size, Alignment.value(), &LI);
1912   if (ClCombinePointerLabelsOnLoad) {
1913     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1914     PrimitiveShadow = DFSF.combineShadows(PrimitiveShadow, PtrShadow, &LI);
1915   }
1916   if (!DFSF.DFS.isZeroShadow(PrimitiveShadow))
1917     DFSF.NonZeroChecks.push_back(PrimitiveShadow);
1918 
1919   Value *Shadow =
1920       DFSF.expandFromPrimitiveShadow(LI.getType(), PrimitiveShadow, &LI);
1921   DFSF.setShadow(&LI, Shadow);
1922   if (ClEventCallbacks) {
1923     IRBuilder<> IRB(&LI);
1924     Value *Addr8 = IRB.CreateBitCast(LI.getPointerOperand(), DFSF.DFS.Int8Ptr);
1925     IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, {PrimitiveShadow, Addr8});
1926   }
1927 }
1928 
1929 void DFSanFunction::storePrimitiveShadow(Value *Addr, uint64_t Size,
1930                                          Align Alignment,
1931                                          Value *PrimitiveShadow,
1932                                          Instruction *Pos) {
1933   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1934     const auto i = AllocaShadowMap.find(AI);
1935     if (i != AllocaShadowMap.end()) {
1936       IRBuilder<> IRB(Pos);
1937       IRB.CreateStore(PrimitiveShadow, i->second);
1938       return;
1939     }
1940   }
1941 
1942   const Align ShadowAlign(Alignment.value() * DFS.ShadowWidthBytes);
1943   IRBuilder<> IRB(Pos);
1944   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1945   if (DFS.isZeroShadow(PrimitiveShadow)) {
1946     IntegerType *ShadowTy =
1947         IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits);
1948     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1949     Value *ExtShadowAddr =
1950         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1951     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1952     return;
1953   }
1954 
1955   const unsigned ShadowVecSize = 128 / DFS.ShadowWidthBits;
1956   uint64_t Offset = 0;
1957   if (Size >= ShadowVecSize) {
1958     auto *ShadowVecTy =
1959         FixedVectorType::get(DFS.PrimitiveShadowTy, ShadowVecSize);
1960     Value *ShadowVec = UndefValue::get(ShadowVecTy);
1961     for (unsigned i = 0; i != ShadowVecSize; ++i) {
1962       ShadowVec = IRB.CreateInsertElement(
1963           ShadowVec, PrimitiveShadow,
1964           ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1965     }
1966     Value *ShadowVecAddr =
1967         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1968     do {
1969       Value *CurShadowVecAddr =
1970           IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
1971       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1972       Size -= ShadowVecSize;
1973       ++Offset;
1974     } while (Size >= ShadowVecSize);
1975     Offset *= ShadowVecSize;
1976   }
1977   while (Size > 0) {
1978     Value *CurShadowAddr =
1979         IRB.CreateConstGEP1_32(DFS.PrimitiveShadowTy, ShadowAddr, Offset);
1980     IRB.CreateAlignedStore(PrimitiveShadow, CurShadowAddr, ShadowAlign);
1981     --Size;
1982     ++Offset;
1983   }
1984 }
1985 
1986 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1987   auto &DL = SI.getModule()->getDataLayout();
1988   uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
1989   if (Size == 0)
1990     return;
1991 
1992   const Align Alignment = ClPreserveAlignment ? SI.getAlign() : Align(1);
1993 
1994   Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1995   Value *PrimitiveShadow;
1996   if (ClCombinePointerLabelsOnStore) {
1997     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1998     PrimitiveShadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1999   } else {
2000     PrimitiveShadow = DFSF.collapseToPrimitiveShadow(Shadow, &SI);
2001   }
2002   DFSF.storePrimitiveShadow(SI.getPointerOperand(), Size, Alignment,
2003                             PrimitiveShadow, &SI);
2004   if (ClEventCallbacks) {
2005     IRBuilder<> IRB(&SI);
2006     Value *Addr8 = IRB.CreateBitCast(SI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2007     IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, {PrimitiveShadow, Addr8});
2008   }
2009 }
2010 
2011 void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
2012   visitOperandShadowInst(UO);
2013 }
2014 
2015 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
2016   visitOperandShadowInst(BO);
2017 }
2018 
2019 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
2020 
2021 void DFSanVisitor::visitCmpInst(CmpInst &CI) {
2022   Value *CombinedShadow = visitOperandShadowInst(CI);
2023   if (ClEventCallbacks) {
2024     IRBuilder<> IRB(&CI);
2025     IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow);
2026   }
2027 }
2028 
2029 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2030   visitOperandShadowInst(GEPI);
2031 }
2032 
2033 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
2034   visitOperandShadowInst(I);
2035 }
2036 
2037 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
2038   visitOperandShadowInst(I);
2039 }
2040 
2041 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
2042   visitOperandShadowInst(I);
2043 }
2044 
2045 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
2046   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2047     visitOperandShadowInst(I);
2048     return;
2049   }
2050 
2051   IRBuilder<> IRB(&I);
2052   Value *Agg = I.getAggregateOperand();
2053   Value *AggShadow = DFSF.getShadow(Agg);
2054   Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2055   DFSF.setShadow(&I, ResShadow);
2056 }
2057 
2058 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
2059   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2060     visitOperandShadowInst(I);
2061     return;
2062   }
2063 
2064   IRBuilder<> IRB(&I);
2065   Value *AggShadow = DFSF.getShadow(I.getAggregateOperand());
2066   Value *InsShadow = DFSF.getShadow(I.getInsertedValueOperand());
2067   Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2068   DFSF.setShadow(&I, Res);
2069 }
2070 
2071 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
2072   bool AllLoadsStores = true;
2073   for (User *U : I.users()) {
2074     if (isa<LoadInst>(U))
2075       continue;
2076 
2077     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2078       if (SI->getPointerOperand() == &I)
2079         continue;
2080     }
2081 
2082     AllLoadsStores = false;
2083     break;
2084   }
2085   if (AllLoadsStores) {
2086     IRBuilder<> IRB(&I);
2087     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.PrimitiveShadowTy);
2088   }
2089   DFSF.setShadow(&I, DFSF.DFS.ZeroPrimitiveShadow);
2090 }
2091 
2092 void DFSanVisitor::visitSelectInst(SelectInst &I) {
2093   Value *CondShadow = DFSF.getShadow(I.getCondition());
2094   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
2095   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
2096   Value *ShadowSel = nullptr;
2097 
2098   if (isa<VectorType>(I.getCondition()->getType())) {
2099     ShadowSel = DFSF.combineShadowsThenConvert(I.getType(), TrueShadow,
2100                                                FalseShadow, &I);
2101   } else {
2102     if (TrueShadow == FalseShadow) {
2103       ShadowSel = TrueShadow;
2104     } else {
2105       ShadowSel =
2106           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
2107     }
2108   }
2109   DFSF.setShadow(&I, ClTrackSelectControlFlow
2110                          ? DFSF.combineShadowsThenConvert(
2111                                I.getType(), CondShadow, ShadowSel, &I)
2112                          : ShadowSel);
2113 }
2114 
2115 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
2116   IRBuilder<> IRB(&I);
2117   Value *ValShadow = DFSF.getShadow(I.getValue());
2118   IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
2119                  {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
2120                                                                 *DFSF.DFS.Ctx)),
2121                   IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2122 }
2123 
2124 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
2125   IRBuilder<> IRB(&I);
2126   Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
2127   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
2128   Value *LenShadow =
2129       IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(),
2130                                                     DFSF.DFS.ShadowWidthBytes));
2131   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
2132   Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr);
2133   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
2134   auto *MTI = cast<MemTransferInst>(
2135       IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
2136                      {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
2137   if (ClPreserveAlignment) {
2138     MTI->setDestAlignment(I.getDestAlign() * DFSF.DFS.ShadowWidthBytes);
2139     MTI->setSourceAlignment(I.getSourceAlign() * DFSF.DFS.ShadowWidthBytes);
2140   } else {
2141     MTI->setDestAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2142     MTI->setSourceAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2143   }
2144   if (ClEventCallbacks) {
2145     IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn,
2146                    {RawDestShadow, I.getLength()});
2147   }
2148 }
2149 
2150 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
2151   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
2152     switch (DFSF.IA) {
2153     case DataFlowSanitizer::IA_TLS: {
2154       Value *S = DFSF.getShadow(RI.getReturnValue());
2155       IRBuilder<> IRB(&RI);
2156       Type *RT = DFSF.F->getFunctionType()->getReturnType();
2157       unsigned Size =
2158           getDataLayout().getTypeAllocSize(DFSF.DFS.getShadowTy(RT));
2159       if (Size <= kRetvalTLSSize) {
2160         // If the size overflows, stores nothing. At callsite, oversized return
2161         // shadows are set to zero.
2162         IRB.CreateAlignedStore(S, DFSF.getRetvalTLS(RT, IRB),
2163                                kShadowTLSAlignment);
2164       }
2165       break;
2166     }
2167     case DataFlowSanitizer::IA_Args: {
2168       IRBuilder<> IRB(&RI);
2169       Type *RT = DFSF.F->getFunctionType()->getReturnType();
2170       Value *InsVal =
2171           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
2172       Value *InsShadow =
2173           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
2174       RI.setOperand(0, InsShadow);
2175       break;
2176     }
2177     }
2178   }
2179 }
2180 
2181 bool DFSanVisitor::visitWrappedCallBase(Function &F, CallBase &CB) {
2182   IRBuilder<> IRB(&CB);
2183   switch (DFSF.DFS.getWrapperKind(&F)) {
2184   case DataFlowSanitizer::WK_Warning:
2185     CB.setCalledFunction(&F);
2186     IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
2187                    IRB.CreateGlobalStringPtr(F.getName()));
2188     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2189     return true;
2190   case DataFlowSanitizer::WK_Discard:
2191     CB.setCalledFunction(&F);
2192     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2193     return true;
2194   case DataFlowSanitizer::WK_Functional:
2195     CB.setCalledFunction(&F);
2196     visitOperandShadowInst(CB);
2197     return true;
2198   case DataFlowSanitizer::WK_Custom:
2199     // Don't try to handle invokes of custom functions, it's too complicated.
2200     // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
2201     // wrapper.
2202     CallInst *CI = dyn_cast<CallInst>(&CB);
2203     if (!CI)
2204       return false;
2205 
2206     FunctionType *FT = F.getFunctionType();
2207     TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
2208     std::string CustomFName = "__dfsw_";
2209     CustomFName += F.getName();
2210     FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
2211         CustomFName, CustomFn.TransformedType);
2212     if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
2213       CustomFn->copyAttributesFrom(&F);
2214 
2215       // Custom functions returning non-void will write to the return label.
2216       if (!FT->getReturnType()->isVoidTy()) {
2217         CustomFn->removeAttributes(AttributeList::FunctionIndex,
2218                                    DFSF.DFS.ReadOnlyNoneAttrs);
2219       }
2220     }
2221 
2222     std::vector<Value *> Args;
2223 
2224     // Adds non-variable arguments.
2225     auto *I = CB.arg_begin();
2226     for (unsigned n = FT->getNumParams(); n != 0; ++I, --n) {
2227       Type *T = (*I)->getType();
2228       FunctionType *ParamFT;
2229       if (isa<PointerType>(T) &&
2230           (ParamFT = dyn_cast<FunctionType>(
2231                cast<PointerType>(T)->getElementType()))) {
2232         std::string TName = "dfst";
2233         TName += utostr(FT->getNumParams() - n);
2234         TName += "$";
2235         TName += F.getName();
2236         Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
2237         Args.push_back(T);
2238         Args.push_back(
2239             IRB.CreateBitCast(*I, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
2240       } else {
2241         Args.push_back(*I);
2242       }
2243     }
2244 
2245     // Adds non-variable argument shadows.
2246     I = CB.arg_begin();
2247     const unsigned ShadowArgStart = Args.size();
2248     for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2249       Args.push_back(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB));
2250 
2251     // Adds variable argument shadows.
2252     if (FT->isVarArg()) {
2253       auto *LabelVATy = ArrayType::get(DFSF.DFS.PrimitiveShadowTy,
2254                                        CB.arg_size() - FT->getNumParams());
2255       auto *LabelVAAlloca =
2256           new AllocaInst(LabelVATy, getDataLayout().getAllocaAddrSpace(),
2257                          "labelva", &DFSF.F->getEntryBlock().front());
2258 
2259       for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2260         auto *LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, N);
2261         IRB.CreateStore(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB),
2262                         LabelVAPtr);
2263       }
2264 
2265       Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
2266     }
2267 
2268     // Adds the return value shadow.
2269     if (!FT->getReturnType()->isVoidTy()) {
2270       if (!DFSF.LabelReturnAlloca) {
2271         DFSF.LabelReturnAlloca = new AllocaInst(
2272             DFSF.DFS.PrimitiveShadowTy, getDataLayout().getAllocaAddrSpace(),
2273             "labelreturn", &DFSF.F->getEntryBlock().front());
2274       }
2275       Args.push_back(DFSF.LabelReturnAlloca);
2276     }
2277 
2278     // Adds variable arguments.
2279     append_range(Args, drop_begin(CB.args(), FT->getNumParams()));
2280 
2281     CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
2282     CustomCI->setCallingConv(CI->getCallingConv());
2283     CustomCI->setAttributes(TransformFunctionAttributes(
2284         CustomFn, CI->getContext(), CI->getAttributes()));
2285 
2286     // Update the parameter attributes of the custom call instruction to
2287     // zero extend the shadow parameters. This is required for targets
2288     // which consider PrimitiveShadowTy an illegal type.
2289     for (unsigned N = 0; N < FT->getNumParams(); N++) {
2290       const unsigned ArgNo = ShadowArgStart + N;
2291       if (CustomCI->getArgOperand(ArgNo)->getType() ==
2292           DFSF.DFS.PrimitiveShadowTy)
2293         CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
2294     }
2295 
2296     // Loads the return value shadow.
2297     if (!FT->getReturnType()->isVoidTy()) {
2298       LoadInst *LabelLoad =
2299           IRB.CreateLoad(DFSF.DFS.PrimitiveShadowTy, DFSF.LabelReturnAlloca);
2300       DFSF.setShadow(CustomCI, DFSF.expandFromPrimitiveShadow(
2301                                    FT->getReturnType(), LabelLoad, &CB));
2302     }
2303 
2304     CI->replaceAllUsesWith(CustomCI);
2305     CI->eraseFromParent();
2306     return true;
2307   }
2308   return false;
2309 }
2310 
2311 void DFSanVisitor::visitCallBase(CallBase &CB) {
2312   Function *F = CB.getCalledFunction();
2313   if ((F && F->isIntrinsic()) || CB.isInlineAsm()) {
2314     visitOperandShadowInst(CB);
2315     return;
2316   }
2317 
2318   // Calls to this function are synthesized in wrappers, and we shouldn't
2319   // instrument them.
2320   if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
2321     return;
2322 
2323   DenseMap<Value *, Function *>::iterator i =
2324       DFSF.DFS.UnwrappedFnMap.find(CB.getCalledOperand());
2325   if (i != DFSF.DFS.UnwrappedFnMap.end())
2326     if (visitWrappedCallBase(*i->second, CB))
2327       return;
2328 
2329   IRBuilder<> IRB(&CB);
2330 
2331   FunctionType *FT = CB.getFunctionType();
2332   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
2333     // Stores argument shadows.
2334     unsigned ArgOffset = 0;
2335     const DataLayout &DL = getDataLayout();
2336     for (unsigned I = 0, N = FT->getNumParams(); I != N; ++I) {
2337       unsigned Size =
2338           DL.getTypeAllocSize(DFSF.DFS.getShadowTy(FT->getParamType(I)));
2339       // Stop storing if arguments' size overflows. Inside a function, arguments
2340       // after overflow have zero shadow values.
2341       if (ArgOffset + Size > kArgTLSSize)
2342         break;
2343       IRB.CreateAlignedStore(
2344           DFSF.getShadow(CB.getArgOperand(I)),
2345           DFSF.getArgTLS(FT->getParamType(I), ArgOffset, IRB),
2346           kShadowTLSAlignment);
2347       ArgOffset += alignTo(Size, kShadowTLSAlignment);
2348     }
2349   }
2350 
2351   Instruction *Next = nullptr;
2352   if (!CB.getType()->isVoidTy()) {
2353     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2354       if (II->getNormalDest()->getSinglePredecessor()) {
2355         Next = &II->getNormalDest()->front();
2356       } else {
2357         BasicBlock *NewBB =
2358             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
2359         Next = &NewBB->front();
2360       }
2361     } else {
2362       assert(CB.getIterator() != CB.getParent()->end());
2363       Next = CB.getNextNode();
2364     }
2365 
2366     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
2367       // Loads the return value shadow.
2368       IRBuilder<> NextIRB(Next);
2369       const DataLayout &DL = getDataLayout();
2370       unsigned Size = DL.getTypeAllocSize(DFSF.DFS.getShadowTy(&CB));
2371       if (Size > kRetvalTLSSize) {
2372         // Set overflowed return shadow to be zero.
2373         DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2374       } else {
2375         LoadInst *LI = NextIRB.CreateAlignedLoad(
2376             DFSF.DFS.getShadowTy(&CB), DFSF.getRetvalTLS(CB.getType(), NextIRB),
2377             kShadowTLSAlignment, "_dfsret");
2378         DFSF.SkipInsts.insert(LI);
2379         DFSF.setShadow(&CB, LI);
2380         DFSF.NonZeroChecks.push_back(LI);
2381       }
2382     }
2383   }
2384 
2385   // Do all instrumentation for IA_Args down here to defer tampering with the
2386   // CFG in a way that SplitEdge may be able to detect.
2387   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
2388     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
2389     Value *Func =
2390         IRB.CreateBitCast(CB.getCalledOperand(), PointerType::getUnqual(NewFT));
2391     std::vector<Value *> Args;
2392 
2393     auto i = CB.arg_begin(), E = CB.arg_end();
2394     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
2395       Args.push_back(*i);
2396 
2397     i = CB.arg_begin();
2398     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
2399       Args.push_back(DFSF.getShadow(*i));
2400 
2401     if (FT->isVarArg()) {
2402       unsigned VarArgSize = CB.arg_size() - FT->getNumParams();
2403       ArrayType *VarArgArrayTy =
2404           ArrayType::get(DFSF.DFS.PrimitiveShadowTy, VarArgSize);
2405       AllocaInst *VarArgShadow =
2406         new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
2407                        "", &DFSF.F->getEntryBlock().front());
2408       Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
2409       for (unsigned n = 0; i != E; ++i, ++n) {
2410         IRB.CreateStore(
2411             DFSF.getShadow(*i),
2412             IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
2413         Args.push_back(*i);
2414       }
2415     }
2416 
2417     CallBase *NewCB;
2418     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2419       NewCB = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
2420                                II->getUnwindDest(), Args);
2421     } else {
2422       NewCB = IRB.CreateCall(NewFT, Func, Args);
2423     }
2424     NewCB->setCallingConv(CB.getCallingConv());
2425     NewCB->setAttributes(CB.getAttributes().removeAttributes(
2426         *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
2427         AttributeFuncs::typeIncompatible(NewCB->getType())));
2428 
2429     if (Next) {
2430       ExtractValueInst *ExVal = ExtractValueInst::Create(NewCB, 0, "", Next);
2431       DFSF.SkipInsts.insert(ExVal);
2432       ExtractValueInst *ExShadow = ExtractValueInst::Create(NewCB, 1, "", Next);
2433       DFSF.SkipInsts.insert(ExShadow);
2434       DFSF.setShadow(ExVal, ExShadow);
2435       DFSF.NonZeroChecks.push_back(ExShadow);
2436 
2437       CB.replaceAllUsesWith(ExVal);
2438     }
2439 
2440     CB.eraseFromParent();
2441   }
2442 }
2443 
2444 void DFSanVisitor::visitPHINode(PHINode &PN) {
2445   Type *ShadowTy = DFSF.DFS.getShadowTy(&PN);
2446   PHINode *ShadowPN =
2447       PHINode::Create(ShadowTy, PN.getNumIncomingValues(), "", &PN);
2448 
2449   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
2450   Value *UndefShadow = UndefValue::get(ShadowTy);
2451   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
2452        ++i) {
2453     ShadowPN->addIncoming(UndefShadow, *i);
2454   }
2455 
2456   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
2457   DFSF.setShadow(&PN, ShadowPN);
2458 }
2459 
2460 namespace {
2461 class DataFlowSanitizerLegacyPass : public ModulePass {
2462 private:
2463   std::vector<std::string> ABIListFiles;
2464 
2465 public:
2466   static char ID;
2467 
2468   DataFlowSanitizerLegacyPass(
2469       const std::vector<std::string> &ABIListFiles = std::vector<std::string>())
2470       : ModulePass(ID), ABIListFiles(ABIListFiles) {}
2471 
2472   bool runOnModule(Module &M) override {
2473     return DataFlowSanitizer(ABIListFiles).runImpl(M);
2474   }
2475 };
2476 } // namespace
2477 
2478 char DataFlowSanitizerLegacyPass::ID;
2479 
2480 INITIALIZE_PASS(DataFlowSanitizerLegacyPass, "dfsan",
2481                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
2482 
2483 ModulePass *llvm::createDataFlowSanitizerLegacyPassPass(
2484     const std::vector<std::string> &ABIListFiles) {
2485   return new DataFlowSanitizerLegacyPass(ABIListFiles);
2486 }
2487 
2488 PreservedAnalyses DataFlowSanitizerPass::run(Module &M,
2489                                              ModuleAnalysisManager &AM) {
2490   if (DataFlowSanitizer(ABIListFiles).runImpl(M)) {
2491     return PreservedAnalyses::none();
2492   }
2493   return PreservedAnalyses::all();
2494 }
2495