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.
20 ///
21 /// There are two possible memory layouts. In the first one, each byte of
22 /// application memory is backed by a shadow memory byte. The shadow byte can
23 /// represent up to 8 labels. To enable this you must specify the
24 /// -dfsan-fast-8-labels flag. On Linux/x86_64, memory is then laid out as
25 /// follows:
26 ///
27 /// +--------------------+ 0x800000000000 (top of memory)
28 /// | application memory |
29 /// +--------------------+ 0x700000008000 (kAppAddr)
30 /// |                    |
31 /// |       unused       |
32 /// |                    |
33 /// +--------------------+ 0x300200000000 (kUnusedAddr)
34 /// |    union table     |
35 /// +--------------------+ 0x300000000000 (kUnionTableAddr)
36 /// |       origin       |
37 /// +--------------------+ 0x200000008000 (kOriginAddr)
38 /// |   shadow memory    |
39 /// +--------------------+ 0x100000008000 (kShadowAddr)
40 /// |       unused       |
41 /// +--------------------+ 0x000000010000
42 /// | reserved by kernel |
43 /// +--------------------+ 0x000000000000
44 ///
45 ///
46 /// In the second memory layout, each byte of application memory is backed by
47 /// two bytes of shadow memory which hold the label. That means we can represent
48 /// either 16 labels (with -dfsan-fast-16-labels flag) or 2^16 labels (on the
49 /// default legacy mode) per byte. On Linux/x86_64, memory is then laid out as
50 /// follows:
51 ///
52 /// +--------------------+ 0x800000000000 (top of memory)
53 /// | application memory |
54 /// +--------------------+ 0x700000008000 (kAppAddr)
55 /// |                    |
56 /// |       unused       |
57 /// |                    |
58 /// +--------------------+ 0x300200000000 (kUnusedAddr)
59 /// |    union table     |
60 /// +--------------------+ 0x300000000000 (kUnionTableAddr)
61 /// |       origin       |
62 /// +--------------------+ 0x200000008000 (kOriginAddr)
63 /// |   shadow memory    |
64 /// +--------------------+ 0x000000010000 (kShadowAddr)
65 /// | reserved by kernel |
66 /// +--------------------+ 0x000000000000
67 ///
68 ///
69 /// To derive a shadow memory address from an application memory address,
70 /// bits 44-46 are cleared to bring the address into the range
71 /// [0x000000008000,0x100000000000).  Then the address is shifted left by 1 to
72 /// account for the double byte representation of shadow labels and move the
73 /// address into the shadow memory range.  See the function
74 /// DataFlowSanitizer::getShadowAddress below.
75 ///
76 /// For more information, please refer to the design document:
77 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
78 //
79 //===----------------------------------------------------------------------===//
80 
81 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
82 #include "llvm/ADT/DenseMap.h"
83 #include "llvm/ADT/DenseSet.h"
84 #include "llvm/ADT/DepthFirstIterator.h"
85 #include "llvm/ADT/None.h"
86 #include "llvm/ADT/SmallPtrSet.h"
87 #include "llvm/ADT/SmallVector.h"
88 #include "llvm/ADT/StringExtras.h"
89 #include "llvm/ADT/StringRef.h"
90 #include "llvm/ADT/Triple.h"
91 #include "llvm/ADT/iterator.h"
92 #include "llvm/Analysis/ValueTracking.h"
93 #include "llvm/IR/Argument.h"
94 #include "llvm/IR/Attributes.h"
95 #include "llvm/IR/BasicBlock.h"
96 #include "llvm/IR/Constant.h"
97 #include "llvm/IR/Constants.h"
98 #include "llvm/IR/DataLayout.h"
99 #include "llvm/IR/DerivedTypes.h"
100 #include "llvm/IR/Dominators.h"
101 #include "llvm/IR/Function.h"
102 #include "llvm/IR/GlobalAlias.h"
103 #include "llvm/IR/GlobalValue.h"
104 #include "llvm/IR/GlobalVariable.h"
105 #include "llvm/IR/IRBuilder.h"
106 #include "llvm/IR/InlineAsm.h"
107 #include "llvm/IR/InstVisitor.h"
108 #include "llvm/IR/InstrTypes.h"
109 #include "llvm/IR/Instruction.h"
110 #include "llvm/IR/Instructions.h"
111 #include "llvm/IR/IntrinsicInst.h"
112 #include "llvm/IR/LLVMContext.h"
113 #include "llvm/IR/MDBuilder.h"
114 #include "llvm/IR/Module.h"
115 #include "llvm/IR/PassManager.h"
116 #include "llvm/IR/Type.h"
117 #include "llvm/IR/User.h"
118 #include "llvm/IR/Value.h"
119 #include "llvm/InitializePasses.h"
120 #include "llvm/Pass.h"
121 #include "llvm/Support/Alignment.h"
122 #include "llvm/Support/Casting.h"
123 #include "llvm/Support/CommandLine.h"
124 #include "llvm/Support/ErrorHandling.h"
125 #include "llvm/Support/SpecialCaseList.h"
126 #include "llvm/Support/VirtualFileSystem.h"
127 #include "llvm/Transforms/Instrumentation.h"
128 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
129 #include "llvm/Transforms/Utils/Local.h"
130 #include <algorithm>
131 #include <cassert>
132 #include <cstddef>
133 #include <cstdint>
134 #include <iterator>
135 #include <memory>
136 #include <set>
137 #include <string>
138 #include <utility>
139 #include <vector>
140 
141 using namespace llvm;
142 
143 // This must be consistent with ShadowWidthBits.
144 static const Align ShadowTLSAlignment = Align(2);
145 
146 static const Align MinOriginAlignment = Align(4);
147 
148 // The size of TLS variables. These constants must be kept in sync with the ones
149 // in dfsan.cpp.
150 static const unsigned ArgTLSSize = 800;
151 static const unsigned RetvalTLSSize = 800;
152 
153 // External symbol to be used when generating the shadow address for
154 // architectures with multiple VMAs. Instead of using a constant integer
155 // the runtime will set the external mask based on the VMA range.
156 const char DFSanExternShadowPtrMask[] = "__dfsan_shadow_ptr_mask";
157 
158 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
159 // alignment requirements provided by the input IR are correct.  For example,
160 // if the input IR contains a load with alignment 8, this flag will cause
161 // the shadow load to have alignment 16.  This flag is disabled by default as
162 // we have unfortunately encountered too much code (including Clang itself;
163 // see PR14291) which performs misaligned access.
164 static cl::opt<bool> ClPreserveAlignment(
165     "dfsan-preserve-alignment",
166     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
167     cl::init(false));
168 
169 // The ABI list files control how shadow parameters are passed. The pass treats
170 // every function labelled "uninstrumented" in the ABI list file as conforming
171 // to the "native" (i.e. unsanitized) ABI.  Unless the ABI list contains
172 // additional annotations for those functions, a call to one of those functions
173 // will produce a warning message, as the labelling behaviour of the function is
174 // unknown.  The other supported annotations are "functional" and "discard",
175 // which are described below under DataFlowSanitizer::WrapperKind.
176 static cl::list<std::string> ClABIListFiles(
177     "dfsan-abilist",
178     cl::desc("File listing native ABI functions and how the pass treats them"),
179     cl::Hidden);
180 
181 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
182 // functions (see DataFlowSanitizer::InstrumentedABI below).
183 static cl::opt<bool>
184     ClArgsABI("dfsan-args-abi",
185               cl::desc("Use the argument ABI rather than the TLS ABI"),
186               cl::Hidden);
187 
188 // Controls whether the pass includes or ignores the labels of pointers in load
189 // instructions.
190 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
191     "dfsan-combine-pointer-labels-on-load",
192     cl::desc("Combine the label of the pointer with the label of the data when "
193              "loading from memory."),
194     cl::Hidden, cl::init(true));
195 
196 // Controls whether the pass includes or ignores the labels of pointers in
197 // stores instructions.
198 static cl::opt<bool> ClCombinePointerLabelsOnStore(
199     "dfsan-combine-pointer-labels-on-store",
200     cl::desc("Combine the label of the pointer with the label of the data when "
201              "storing in memory."),
202     cl::Hidden, cl::init(false));
203 
204 static cl::opt<bool> ClDebugNonzeroLabels(
205     "dfsan-debug-nonzero-labels",
206     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
207              "load or return with a nonzero label"),
208     cl::Hidden);
209 
210 // Experimental feature that inserts callbacks for certain data events.
211 // Currently callbacks are only inserted for loads, stores, memory transfers
212 // (i.e. memcpy and memmove), and comparisons.
213 //
214 // If this flag is set to true, the user must provide definitions for the
215 // following callback functions:
216 //   void __dfsan_load_callback(dfsan_label Label, void* addr);
217 //   void __dfsan_store_callback(dfsan_label Label, void* addr);
218 //   void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
219 //   void __dfsan_cmp_callback(dfsan_label CombinedLabel);
220 static cl::opt<bool> ClEventCallbacks(
221     "dfsan-event-callbacks",
222     cl::desc("Insert calls to __dfsan_*_callback functions on data events."),
223     cl::Hidden, cl::init(false));
224 
225 // Use a distinct bit for each base label, enabling faster unions with less
226 // instrumentation.  Limits the max number of base labels to 16.
227 static cl::opt<bool> ClFast16Labels(
228     "dfsan-fast-16-labels",
229     cl::desc("Use more efficient instrumentation, limiting the number of "
230              "labels to 16."),
231     cl::Hidden, cl::init(false));
232 
233 // Use a distinct bit for each base label, enabling faster unions with less
234 // instrumentation.  Limits the max number of base labels to 8.
235 static cl::opt<bool> ClFast8Labels(
236     "dfsan-fast-8-labels",
237     cl::desc("Use more efficient instrumentation, limiting the number of "
238              "labels to 8."),
239     cl::Hidden, cl::init(false));
240 
241 // Controls whether the pass tracks the control flow of select instructions.
242 static cl::opt<bool> ClTrackSelectControlFlow(
243     "dfsan-track-select-control-flow",
244     cl::desc("Propagate labels from condition values of select instructions "
245              "to results."),
246     cl::Hidden, cl::init(true));
247 
248 // TODO: This default value follows MSan. DFSan may use a different value.
249 static cl::opt<int> ClInstrumentWithCallThreshold(
250     "dfsan-instrument-with-call-threshold",
251     cl::desc("If the function being instrumented requires more than "
252              "this number of origin stores, use callbacks instead of "
253              "inline checks (-1 means never use callbacks)."),
254     cl::Hidden, cl::init(3500));
255 
256 // Controls how to track origins.
257 // * 0: do not track origins.
258 // * 1: track origins at memory store operations.
259 // * 2: TODO: track origins at memory store operations and callsites.
260 static cl::opt<int> ClTrackOrigins("dfsan-track-origins",
261                                    cl::desc("Track origins of labels"),
262                                    cl::Hidden, cl::init(0));
263 
264 static StringRef getGlobalTypeString(const GlobalValue &G) {
265   // Types of GlobalVariables are always pointer types.
266   Type *GType = G.getValueType();
267   // For now we support excluding struct types only.
268   if (StructType *SGType = dyn_cast<StructType>(GType)) {
269     if (!SGType->isLiteral())
270       return SGType->getName();
271   }
272   return "<unknown type>";
273 }
274 
275 namespace {
276 
277 class DFSanABIList {
278   std::unique_ptr<SpecialCaseList> SCL;
279 
280 public:
281   DFSanABIList() = default;
282 
283   void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
284 
285   /// Returns whether either this function or its source file are listed in the
286   /// given category.
287   bool isIn(const Function &F, StringRef Category) const {
288     return isIn(*F.getParent(), Category) ||
289            SCL->inSection("dataflow", "fun", F.getName(), Category);
290   }
291 
292   /// Returns whether this global alias is listed in the given category.
293   ///
294   /// If GA aliases a function, the alias's name is matched as a function name
295   /// would be.  Similarly, aliases of globals are matched like globals.
296   bool isIn(const GlobalAlias &GA, StringRef Category) const {
297     if (isIn(*GA.getParent(), Category))
298       return true;
299 
300     if (isa<FunctionType>(GA.getValueType()))
301       return SCL->inSection("dataflow", "fun", GA.getName(), Category);
302 
303     return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
304            SCL->inSection("dataflow", "type", getGlobalTypeString(GA),
305                           Category);
306   }
307 
308   /// Returns whether this module is listed in the given category.
309   bool isIn(const Module &M, StringRef Category) const {
310     return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
311   }
312 };
313 
314 /// TransformedFunction is used to express the result of transforming one
315 /// function type into another.  This struct is immutable.  It holds metadata
316 /// useful for updating calls of the old function to the new type.
317 struct TransformedFunction {
318   TransformedFunction(FunctionType *OriginalType, FunctionType *TransformedType,
319                       std::vector<unsigned> ArgumentIndexMapping)
320       : OriginalType(OriginalType), TransformedType(TransformedType),
321         ArgumentIndexMapping(ArgumentIndexMapping) {}
322 
323   // Disallow copies.
324   TransformedFunction(const TransformedFunction &) = delete;
325   TransformedFunction &operator=(const TransformedFunction &) = delete;
326 
327   // Allow moves.
328   TransformedFunction(TransformedFunction &&) = default;
329   TransformedFunction &operator=(TransformedFunction &&) = default;
330 
331   /// Type of the function before the transformation.
332   FunctionType *OriginalType;
333 
334   /// Type of the function after the transformation.
335   FunctionType *TransformedType;
336 
337   /// Transforming a function may change the position of arguments.  This
338   /// member records the mapping from each argument's old position to its new
339   /// position.  Argument positions are zero-indexed.  If the transformation
340   /// from F to F' made the first argument of F into the third argument of F',
341   /// then ArgumentIndexMapping[0] will equal 2.
342   std::vector<unsigned> ArgumentIndexMapping;
343 };
344 
345 /// Given function attributes from a call site for the original function,
346 /// return function attributes appropriate for a call to the transformed
347 /// function.
348 AttributeList
349 transformFunctionAttributes(const TransformedFunction &TransformedFunction,
350                             LLVMContext &Ctx, AttributeList CallSiteAttrs) {
351 
352   // Construct a vector of AttributeSet for each function argument.
353   std::vector<llvm::AttributeSet> ArgumentAttributes(
354       TransformedFunction.TransformedType->getNumParams());
355 
356   // Copy attributes from the parameter of the original function to the
357   // transformed version.  'ArgumentIndexMapping' holds the mapping from
358   // old argument position to new.
359   for (unsigned I = 0, IE = TransformedFunction.ArgumentIndexMapping.size();
360        I < IE; ++I) {
361     unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[I];
362     ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(I);
363   }
364 
365   // Copy annotations on varargs arguments.
366   for (unsigned I = TransformedFunction.OriginalType->getNumParams(),
367                 IE = CallSiteAttrs.getNumAttrSets();
368        I < IE; ++I) {
369     ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(I));
370   }
371 
372   return AttributeList::get(Ctx, CallSiteAttrs.getFnAttributes(),
373                             CallSiteAttrs.getRetAttributes(),
374                             llvm::makeArrayRef(ArgumentAttributes));
375 }
376 
377 class DataFlowSanitizer {
378   friend struct DFSanFunction;
379   friend class DFSanVisitor;
380 
381   enum {
382     OriginWidthBits = 32,
383     OriginWidthBytes = OriginWidthBits / 8
384   };
385 
386   /// Which ABI should be used for instrumented functions?
387   enum InstrumentedABI {
388     /// Argument and return value labels are passed through additional
389     /// arguments and by modifying the return type.
390     IA_Args,
391 
392     /// Argument and return value labels are passed through TLS variables
393     /// __dfsan_arg_tls and __dfsan_retval_tls.
394     IA_TLS
395   };
396 
397   /// How should calls to uninstrumented functions be handled?
398   enum WrapperKind {
399     /// This function is present in an uninstrumented form but we don't know
400     /// how it should be handled.  Print a warning and call the function anyway.
401     /// Don't label the return value.
402     WK_Warning,
403 
404     /// This function does not write to (user-accessible) memory, and its return
405     /// value is unlabelled.
406     WK_Discard,
407 
408     /// This function does not write to (user-accessible) memory, and the label
409     /// of its return value is the union of the label of its arguments.
410     WK_Functional,
411 
412     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
413     /// where F is the name of the function.  This function may wrap the
414     /// original function or provide its own implementation.  This is similar to
415     /// the IA_Args ABI, except that IA_Args uses a struct return type to
416     /// pass the return value shadow in a register, while WK_Custom uses an
417     /// extra pointer argument to return the shadow.  This allows the wrapped
418     /// form of the function type to be expressed in C.
419     WK_Custom
420   };
421 
422   unsigned ShadowWidthBits;
423   unsigned ShadowWidthBytes;
424 
425   Module *Mod;
426   LLVMContext *Ctx;
427   Type *Int8Ptr;
428   IntegerType *OriginTy;
429   PointerType *OriginPtrTy;
430   ConstantInt *OriginBase;
431   ConstantInt *ZeroOrigin;
432   /// The shadow type for all primitive types and vector types.
433   IntegerType *PrimitiveShadowTy;
434   PointerType *PrimitiveShadowPtrTy;
435   IntegerType *IntptrTy;
436   ConstantInt *ZeroPrimitiveShadow;
437   ConstantInt *ShadowPtrMask;
438   ConstantInt *ShadowPtrMul;
439   Constant *ArgTLS;
440   ArrayType *ArgOriginTLSTy;
441   Constant *ArgOriginTLS;
442   Constant *RetvalTLS;
443   Constant *RetvalOriginTLS;
444   Constant *ExternalShadowMask;
445   FunctionType *DFSanUnionFnTy;
446   FunctionType *DFSanUnionLoadFnTy;
447   FunctionType *DFSanLoadLabelAndOriginFnTy;
448   FunctionType *DFSanUnimplementedFnTy;
449   FunctionType *DFSanSetLabelFnTy;
450   FunctionType *DFSanNonzeroLabelFnTy;
451   FunctionType *DFSanVarargWrapperFnTy;
452   FunctionType *DFSanCmpCallbackFnTy;
453   FunctionType *DFSanLoadStoreCallbackFnTy;
454   FunctionType *DFSanMemTransferCallbackFnTy;
455   FunctionType *DFSanChainOriginFnTy;
456   FunctionType *DFSanMemOriginTransferFnTy;
457   FunctionType *DFSanMaybeStoreOriginFnTy;
458   FunctionCallee DFSanUnionFn;
459   FunctionCallee DFSanCheckedUnionFn;
460   FunctionCallee DFSanUnionLoadFn;
461   FunctionCallee DFSanUnionLoadFastLabelsFn;
462   FunctionCallee DFSanLoadLabelAndOriginFn;
463   FunctionCallee DFSanUnimplementedFn;
464   FunctionCallee DFSanSetLabelFn;
465   FunctionCallee DFSanNonzeroLabelFn;
466   FunctionCallee DFSanVarargWrapperFn;
467   FunctionCallee DFSanLoadCallbackFn;
468   FunctionCallee DFSanStoreCallbackFn;
469   FunctionCallee DFSanMemTransferCallbackFn;
470   FunctionCallee DFSanCmpCallbackFn;
471   FunctionCallee DFSanChainOriginFn;
472   FunctionCallee DFSanMemOriginTransferFn;
473   FunctionCallee DFSanMaybeStoreOriginFn;
474   SmallPtrSet<Value *, 16> DFSanRuntimeFunctions;
475   MDNode *ColdCallWeights;
476   MDNode *OriginStoreWeights;
477   DFSanABIList ABIList;
478   DenseMap<Value *, Function *> UnwrappedFnMap;
479   AttrBuilder ReadOnlyNoneAttrs;
480   bool DFSanRuntimeShadowMask = false;
481 
482   Value *getShadowOffset(Value *Addr, IRBuilder<> &IRB);
483   Value *getShadowAddress(Value *Addr, Instruction *Pos);
484   Value *getShadowAddress(Value *Addr, Instruction *Pos, Value *ShadowOffset);
485   std::pair<Value *, Value *>
486   getShadowOriginAddress(Value *Addr, Align InstAlignment, Instruction *Pos);
487   bool isInstrumented(const Function *F);
488   bool isInstrumented(const GlobalAlias *GA);
489   FunctionType *getArgsFunctionType(FunctionType *T);
490   FunctionType *getTrampolineFunctionType(FunctionType *T);
491   TransformedFunction getCustomFunctionType(FunctionType *T);
492   InstrumentedABI getInstrumentedABI();
493   WrapperKind getWrapperKind(Function *F);
494   void addGlobalNamePrefix(GlobalValue *GV);
495   Function *buildWrapperFunction(Function *F, StringRef NewFName,
496                                  GlobalValue::LinkageTypes NewFLink,
497                                  FunctionType *NewFT);
498   Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
499   void initializeCallbackFunctions(Module &M);
500   void initializeRuntimeFunctions(Module &M);
501   void injectMetadataGlobals(Module &M);
502 
503   bool init(Module &M);
504 
505   /// Returns whether fast8 or fast16 mode has been specified.
506   bool hasFastLabelsEnabled();
507 
508   /// Returns whether the pass tracks origins. Support only fast16 mode in TLS
509   /// ABI mode.
510   bool shouldTrackOrigins();
511 
512   /// Returns whether the pass tracks labels for struct fields and array
513   /// indices. Support only fast16 mode in TLS ABI mode.
514   bool shouldTrackFieldsAndIndices();
515 
516   /// Returns a zero constant with the shadow type of OrigTy.
517   ///
518   /// getZeroShadow({T1,T2,...}) = {getZeroShadow(T1),getZeroShadow(T2,...}
519   /// getZeroShadow([n x T]) = [n x getZeroShadow(T)]
520   /// getZeroShadow(other type) = i16(0)
521   ///
522   /// Note that a zero shadow is always i16(0) when shouldTrackFieldsAndIndices
523   /// returns false.
524   Constant *getZeroShadow(Type *OrigTy);
525   /// Returns a zero constant with the shadow type of V's type.
526   Constant *getZeroShadow(Value *V);
527 
528   /// Checks if V is a zero shadow.
529   bool isZeroShadow(Value *V);
530 
531   /// Returns the shadow type of OrigTy.
532   ///
533   /// getShadowTy({T1,T2,...}) = {getShadowTy(T1),getShadowTy(T2),...}
534   /// getShadowTy([n x T]) = [n x getShadowTy(T)]
535   /// getShadowTy(other type) = i16
536   ///
537   /// Note that a shadow type is always i16 when shouldTrackFieldsAndIndices
538   /// returns false.
539   Type *getShadowTy(Type *OrigTy);
540   /// Returns the shadow type of of V's type.
541   Type *getShadowTy(Value *V);
542 
543   const uint64_t NumOfElementsInArgOrgTLS = ArgTLSSize / OriginWidthBytes;
544 
545 public:
546   DataFlowSanitizer(const std::vector<std::string> &ABIListFiles);
547 
548   bool runImpl(Module &M);
549 };
550 
551 struct DFSanFunction {
552   DataFlowSanitizer &DFS;
553   Function *F;
554   DominatorTree DT;
555   DataFlowSanitizer::InstrumentedABI IA;
556   bool IsNativeABI;
557   AllocaInst *LabelReturnAlloca = nullptr;
558   AllocaInst *OriginReturnAlloca = nullptr;
559   DenseMap<Value *, Value *> ValShadowMap;
560   DenseMap<Value *, Value *> ValOriginMap;
561   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
562   DenseMap<AllocaInst *, AllocaInst *> AllocaOriginMap;
563 
564   struct PHIFixupElement {
565     PHINode *Phi;
566     PHINode *ShadowPhi;
567     PHINode *OriginPhi;
568   };
569   std::vector<PHIFixupElement> PHIFixups;
570 
571   DenseSet<Instruction *> SkipInsts;
572   std::vector<Value *> NonZeroChecks;
573   bool AvoidNewBlocks;
574 
575   struct CachedShadow {
576     BasicBlock *Block; // The block where Shadow is defined.
577     Value *Shadow;
578   };
579   /// Maps a value to its latest shadow value in terms of domination tree.
580   DenseMap<std::pair<Value *, Value *>, CachedShadow> CachedShadows;
581   /// Maps a value to its latest collapsed shadow value it was converted to in
582   /// terms of domination tree. When ClDebugNonzeroLabels is on, this cache is
583   /// used at a post process where CFG blocks are split. So it does not cache
584   /// BasicBlock like CachedShadows, but uses domination between values.
585   DenseMap<Value *, Value *> CachedCollapsedShadows;
586   DenseMap<Value *, std::set<Value *>> ShadowElements;
587 
588   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
589       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
590     DT.recalculate(*F);
591     // FIXME: Need to track down the register allocator issue which causes poor
592     // performance in pathological cases with large numbers of basic blocks.
593     AvoidNewBlocks = F->size() > 1000;
594   }
595 
596   /// Computes the shadow address for a given function argument.
597   ///
598   /// Shadow = ArgTLS+ArgOffset.
599   Value *getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB);
600 
601   /// Computes the shadow address for a return value.
602   Value *getRetvalTLS(Type *T, IRBuilder<> &IRB);
603 
604   /// Computes the origin address for a given function argument.
605   ///
606   /// Origin = ArgOriginTLS[ArgNo].
607   Value *getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB);
608 
609   /// Computes the origin address for a return value.
610   Value *getRetvalOriginTLS();
611 
612   Value *getOrigin(Value *V);
613   void setOrigin(Instruction *I, Value *Origin);
614   /// Generates IR to compute the origin of the last operand with a taint label.
615   Value *combineOperandOrigins(Instruction *Inst);
616   /// Before the instruction Pos, generates IR to compute the last origin with a
617   /// taint label. Labels and origins are from vectors Shadows and Origins
618   /// correspondingly. The generated IR is like
619   ///   Sn-1 != Zero ? On-1: ... S2 != Zero ? O2: S1 != Zero ? O1: O0
620   /// When Zero is nullptr, it uses ZeroPrimitiveShadow. Otherwise it can be
621   /// zeros with other bitwidths.
622   Value *combineOrigins(const std::vector<Value *> &Shadows,
623                         const std::vector<Value *> &Origins, Instruction *Pos,
624                         ConstantInt *Zero = nullptr);
625 
626   Value *getShadow(Value *V);
627   void setShadow(Instruction *I, Value *Shadow);
628   /// Generates IR to compute the union of the two given shadows, inserting it
629   /// before Pos. The combined value is with primitive type.
630   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
631   /// Combines the shadow values of V1 and V2, then converts the combined value
632   /// with primitive type into a shadow value with the original type T.
633   Value *combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
634                                    Instruction *Pos);
635   Value *combineOperandShadows(Instruction *Inst);
636   std::pair<Value *, Value *> loadShadowOrigin(Value *ShadowAddr, uint64_t Size,
637                                                Align InstAlignment,
638                                                Instruction *Pos);
639   void storePrimitiveShadowOrigin(Value *Addr, uint64_t Size,
640                                   Align InstAlignment, Value *PrimitiveShadow,
641                                   Value *Origin, Instruction *Pos);
642   /// Applies PrimitiveShadow to all primitive subtypes of T, returning
643   /// the expanded shadow value.
644   ///
645   /// EFP({T1,T2, ...}, PS) = {EFP(T1,PS),EFP(T2,PS),...}
646   /// EFP([n x T], PS) = [n x EFP(T,PS)]
647   /// EFP(other types, PS) = PS
648   Value *expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
649                                    Instruction *Pos);
650   /// Collapses Shadow into a single primitive shadow value, unioning all
651   /// primitive shadow values in the process. Returns the final primitive
652   /// shadow value.
653   ///
654   /// CTP({V1,V2, ...}) = UNION(CFP(V1,PS),CFP(V2,PS),...)
655   /// CTP([V1,V2,...]) = UNION(CFP(V1,PS),CFP(V2,PS),...)
656   /// CTP(other types, PS) = PS
657   Value *collapseToPrimitiveShadow(Value *Shadow, Instruction *Pos);
658 
659   void storeZeroPrimitiveShadow(Value *Addr, uint64_t Size, Align ShadowAlign,
660                                 Instruction *Pos);
661 
662   Align getShadowAlign(Align InstAlignment);
663 
664 private:
665   /// Collapses the shadow with aggregate type into a single primitive shadow
666   /// value.
667   template <class AggregateType>
668   Value *collapseAggregateShadow(AggregateType *AT, Value *Shadow,
669                                  IRBuilder<> &IRB);
670 
671   Value *collapseToPrimitiveShadow(Value *Shadow, IRBuilder<> &IRB);
672 
673   /// Returns the shadow value of an argument A.
674   Value *getShadowForTLSArgument(Argument *A);
675 
676   /// The fast path of loading shadow in legacy mode.
677   Value *loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size,
678                               Align ShadowAlign, Instruction *Pos);
679 
680   /// The fast path of loading shadow in fast-16-label mode.
681   std::pair<Value *, Value *>
682   loadFast16ShadowFast(Value *ShadowAddr, Value *OriginAddr, uint64_t Size,
683                        Align ShadowAlign, Align OriginAlign, Value *FirstOrigin,
684                        Instruction *Pos);
685 
686   Align getOriginAlign(Align InstAlignment);
687 
688   /// Because 4 contiguous bytes share one 4-byte origin, the most accurate load
689   /// is __dfsan_load_label_and_origin. This function returns the union of all
690   /// labels and the origin of the first taint label. However this is an
691   /// additional call with many instructions. To ensure common cases are fast,
692   /// checks if it is possible to load labels and origins without using the
693   /// callback function.
694   bool useCallbackLoadLabelAndOrigin(uint64_t Size, Align InstAlignment);
695 
696   /// Returns a chain at the current stack with previous origin V.
697   Value *updateOrigin(Value *V, IRBuilder<> &IRB);
698 
699   /// Creates an Intptr = Origin | Origin << 32 if Intptr's size is 64. Returns
700   /// Origin otherwise.
701   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin);
702 
703   /// Stores Origin into the address range [StoreOriginAddr, StoreOriginAddr +
704   /// Size).
705   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *StoreOriginAddr,
706                    uint64_t StoreOriginSize, Align Alignment);
707 
708   /// Stores Origin in terms of its Shadow value.
709   /// * Do not write origins for zero shadows because we do not trace origins
710   ///   for untainted sinks.
711   /// * Use __dfsan_maybe_store_origin if there are too many origin store
712   ///   instrumentations.
713   void storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size, Value *Shadow,
714                    Value *Origin, Value *StoreOriginAddr, Align InstAlignment);
715 
716   /// Convert a scalar value to an i1 by comparing with 0.
717   Value *convertToBool(Value *V, IRBuilder<> &IRB, const Twine &Name = "");
718 
719   bool shouldInstrumentWithCall();
720 
721   int NumOriginStores = 0;
722 };
723 
724 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
725 public:
726   DFSanFunction &DFSF;
727 
728   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
729 
730   const DataLayout &getDataLayout() const {
731     return DFSF.F->getParent()->getDataLayout();
732   }
733 
734   // Combines shadow values and origins for all of I's operands.
735   void visitInstOperands(Instruction &I);
736 
737   void visitUnaryOperator(UnaryOperator &UO);
738   void visitBinaryOperator(BinaryOperator &BO);
739   void visitCastInst(CastInst &CI);
740   void visitCmpInst(CmpInst &CI);
741   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
742   void visitLoadInst(LoadInst &LI);
743   void visitStoreInst(StoreInst &SI);
744   void visitAtomicRMWInst(AtomicRMWInst &I);
745   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
746   void visitReturnInst(ReturnInst &RI);
747   void visitCallBase(CallBase &CB);
748   void visitPHINode(PHINode &PN);
749   void visitExtractElementInst(ExtractElementInst &I);
750   void visitInsertElementInst(InsertElementInst &I);
751   void visitShuffleVectorInst(ShuffleVectorInst &I);
752   void visitExtractValueInst(ExtractValueInst &I);
753   void visitInsertValueInst(InsertValueInst &I);
754   void visitAllocaInst(AllocaInst &I);
755   void visitSelectInst(SelectInst &I);
756   void visitMemSetInst(MemSetInst &I);
757   void visitMemTransferInst(MemTransferInst &I);
758 
759 private:
760   void visitCASOrRMW(Align InstAlignment, Instruction &I);
761 
762   // Returns false when this is an invoke of a custom function.
763   bool visitWrappedCallBase(Function &F, CallBase &CB);
764 
765   // Combines origins for all of I's operands.
766   void visitInstOperandOrigins(Instruction &I);
767 
768   void addShadowArguments(Function &F, CallBase &CB, std::vector<Value *> &Args,
769                           IRBuilder<> &IRB);
770 
771   void addOriginArguments(Function &F, CallBase &CB, std::vector<Value *> &Args,
772                           IRBuilder<> &IRB);
773 };
774 
775 } // end anonymous namespace
776 
777 DataFlowSanitizer::DataFlowSanitizer(
778     const std::vector<std::string> &ABIListFiles) {
779   if (ClFast8Labels && ClFast16Labels) {
780     report_fatal_error(
781         "cannot set both -dfsan-fast-8-labels and -dfsan-fast-16-labels");
782   }
783 
784   ShadowWidthBits = ClFast8Labels ? 8 : 16;
785   ShadowWidthBytes = ShadowWidthBits / 8;
786 
787   std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
788   llvm::append_range(AllABIListFiles, ClABIListFiles);
789   // FIXME: should we propagate vfs::FileSystem to this constructor?
790   ABIList.set(
791       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
792 }
793 
794 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
795   SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
796   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
797   if (T->isVarArg())
798     ArgTypes.push_back(PrimitiveShadowPtrTy);
799   Type *RetType = T->getReturnType();
800   if (!RetType->isVoidTy())
801     RetType = StructType::get(RetType, PrimitiveShadowTy);
802   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
803 }
804 
805 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
806   assert(!T->isVarArg());
807   SmallVector<Type *, 4> ArgTypes;
808   ArgTypes.push_back(T->getPointerTo());
809   ArgTypes.append(T->param_begin(), T->param_end());
810   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
811   Type *RetType = T->getReturnType();
812   if (!RetType->isVoidTy())
813     ArgTypes.push_back(PrimitiveShadowPtrTy);
814 
815   if (shouldTrackOrigins()) {
816     ArgTypes.append(T->getNumParams(), OriginTy);
817     if (!RetType->isVoidTy())
818       ArgTypes.push_back(OriginPtrTy);
819   }
820 
821   return FunctionType::get(T->getReturnType(), ArgTypes, false);
822 }
823 
824 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
825   SmallVector<Type *, 4> ArgTypes;
826 
827   // Some parameters of the custom function being constructed are
828   // parameters of T.  Record the mapping from parameters of T to
829   // parameters of the custom function, so that parameter attributes
830   // at call sites can be updated.
831   std::vector<unsigned> ArgumentIndexMapping;
832   for (unsigned I = 0, E = T->getNumParams(); I != E; ++I) {
833     Type *ParamType = T->getParamType(I);
834     FunctionType *FT;
835     if (isa<PointerType>(ParamType) &&
836         (FT = dyn_cast<FunctionType>(ParamType->getPointerElementType()))) {
837       ArgumentIndexMapping.push_back(ArgTypes.size());
838       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
839       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
840     } else {
841       ArgumentIndexMapping.push_back(ArgTypes.size());
842       ArgTypes.push_back(ParamType);
843     }
844   }
845   for (unsigned I = 0, E = T->getNumParams(); I != E; ++I)
846     ArgTypes.push_back(PrimitiveShadowTy);
847   if (T->isVarArg())
848     ArgTypes.push_back(PrimitiveShadowPtrTy);
849   Type *RetType = T->getReturnType();
850   if (!RetType->isVoidTy())
851     ArgTypes.push_back(PrimitiveShadowPtrTy);
852 
853   if (shouldTrackOrigins()) {
854     for (unsigned I = 0, E = T->getNumParams(); I != E; ++I)
855       ArgTypes.push_back(OriginTy);
856     if (T->isVarArg())
857       ArgTypes.push_back(OriginPtrTy);
858     if (!RetType->isVoidTy())
859       ArgTypes.push_back(OriginPtrTy);
860   }
861 
862   return TransformedFunction(
863       T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
864       ArgumentIndexMapping);
865 }
866 
867 bool DataFlowSanitizer::isZeroShadow(Value *V) {
868   if (!shouldTrackFieldsAndIndices())
869     return ZeroPrimitiveShadow == V;
870 
871   Type *T = V->getType();
872   if (!isa<ArrayType>(T) && !isa<StructType>(T)) {
873     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
874       return CI->isZero();
875     return false;
876   }
877 
878   return isa<ConstantAggregateZero>(V);
879 }
880 
881 bool DataFlowSanitizer::hasFastLabelsEnabled() {
882   static const bool HasFastLabelsEnabled = ClFast8Labels || ClFast16Labels;
883   return HasFastLabelsEnabled;
884 }
885 
886 bool DataFlowSanitizer::shouldTrackOrigins() {
887   static const bool ShouldTrackOrigins =
888       ClTrackOrigins && getInstrumentedABI() == DataFlowSanitizer::IA_TLS &&
889       ClFast16Labels;
890   return ShouldTrackOrigins;
891 }
892 
893 bool DataFlowSanitizer::shouldTrackFieldsAndIndices() {
894   return getInstrumentedABI() == DataFlowSanitizer::IA_TLS &&
895          hasFastLabelsEnabled();
896 }
897 
898 Constant *DataFlowSanitizer::getZeroShadow(Type *OrigTy) {
899   if (!shouldTrackFieldsAndIndices())
900     return ZeroPrimitiveShadow;
901 
902   if (!isa<ArrayType>(OrigTy) && !isa<StructType>(OrigTy))
903     return ZeroPrimitiveShadow;
904   Type *ShadowTy = getShadowTy(OrigTy);
905   return ConstantAggregateZero::get(ShadowTy);
906 }
907 
908 Constant *DataFlowSanitizer::getZeroShadow(Value *V) {
909   return getZeroShadow(V->getType());
910 }
911 
912 static Value *expandFromPrimitiveShadowRecursive(
913     Value *Shadow, SmallVector<unsigned, 4> &Indices, Type *SubShadowTy,
914     Value *PrimitiveShadow, IRBuilder<> &IRB) {
915   if (!isa<ArrayType>(SubShadowTy) && !isa<StructType>(SubShadowTy))
916     return IRB.CreateInsertValue(Shadow, PrimitiveShadow, Indices);
917 
918   if (ArrayType *AT = dyn_cast<ArrayType>(SubShadowTy)) {
919     for (unsigned Idx = 0; Idx < AT->getNumElements(); Idx++) {
920       Indices.push_back(Idx);
921       Shadow = expandFromPrimitiveShadowRecursive(
922           Shadow, Indices, AT->getElementType(), PrimitiveShadow, IRB);
923       Indices.pop_back();
924     }
925     return Shadow;
926   }
927 
928   if (StructType *ST = dyn_cast<StructType>(SubShadowTy)) {
929     for (unsigned Idx = 0; Idx < ST->getNumElements(); Idx++) {
930       Indices.push_back(Idx);
931       Shadow = expandFromPrimitiveShadowRecursive(
932           Shadow, Indices, ST->getElementType(Idx), PrimitiveShadow, IRB);
933       Indices.pop_back();
934     }
935     return Shadow;
936   }
937   llvm_unreachable("Unexpected shadow type");
938 }
939 
940 bool DFSanFunction::shouldInstrumentWithCall() {
941   return ClInstrumentWithCallThreshold >= 0 &&
942          NumOriginStores >= ClInstrumentWithCallThreshold;
943 }
944 
945 Value *DFSanFunction::expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
946                                                 Instruction *Pos) {
947   Type *ShadowTy = DFS.getShadowTy(T);
948 
949   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
950     return PrimitiveShadow;
951 
952   if (DFS.isZeroShadow(PrimitiveShadow))
953     return DFS.getZeroShadow(ShadowTy);
954 
955   IRBuilder<> IRB(Pos);
956   SmallVector<unsigned, 4> Indices;
957   Value *Shadow = UndefValue::get(ShadowTy);
958   Shadow = expandFromPrimitiveShadowRecursive(Shadow, Indices, ShadowTy,
959                                               PrimitiveShadow, IRB);
960 
961   // Caches the primitive shadow value that built the shadow value.
962   CachedCollapsedShadows[Shadow] = PrimitiveShadow;
963   return Shadow;
964 }
965 
966 template <class AggregateType>
967 Value *DFSanFunction::collapseAggregateShadow(AggregateType *AT, Value *Shadow,
968                                               IRBuilder<> &IRB) {
969   if (!AT->getNumElements())
970     return DFS.ZeroPrimitiveShadow;
971 
972   Value *FirstItem = IRB.CreateExtractValue(Shadow, 0);
973   Value *Aggregator = collapseToPrimitiveShadow(FirstItem, IRB);
974 
975   for (unsigned Idx = 1; Idx < AT->getNumElements(); Idx++) {
976     Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
977     Value *ShadowInner = collapseToPrimitiveShadow(ShadowItem, IRB);
978     Aggregator = IRB.CreateOr(Aggregator, ShadowInner);
979   }
980   return Aggregator;
981 }
982 
983 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
984                                                 IRBuilder<> &IRB) {
985   Type *ShadowTy = Shadow->getType();
986   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
987     return Shadow;
988   if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy))
989     return collapseAggregateShadow<>(AT, Shadow, IRB);
990   if (StructType *ST = dyn_cast<StructType>(ShadowTy))
991     return collapseAggregateShadow<>(ST, Shadow, IRB);
992   llvm_unreachable("Unexpected shadow type");
993 }
994 
995 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
996                                                 Instruction *Pos) {
997   Type *ShadowTy = Shadow->getType();
998   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
999     return Shadow;
1000 
1001   assert(DFS.shouldTrackFieldsAndIndices());
1002 
1003   // Checks if the cached collapsed shadow value dominates Pos.
1004   Value *&CS = CachedCollapsedShadows[Shadow];
1005   if (CS && DT.dominates(CS, Pos))
1006     return CS;
1007 
1008   IRBuilder<> IRB(Pos);
1009   Value *PrimitiveShadow = collapseToPrimitiveShadow(Shadow, IRB);
1010   // Caches the converted primitive shadow value.
1011   CS = PrimitiveShadow;
1012   return PrimitiveShadow;
1013 }
1014 
1015 Type *DataFlowSanitizer::getShadowTy(Type *OrigTy) {
1016   if (!shouldTrackFieldsAndIndices())
1017     return PrimitiveShadowTy;
1018 
1019   if (!OrigTy->isSized())
1020     return PrimitiveShadowTy;
1021   if (isa<IntegerType>(OrigTy))
1022     return PrimitiveShadowTy;
1023   if (isa<VectorType>(OrigTy))
1024     return PrimitiveShadowTy;
1025   if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy))
1026     return ArrayType::get(getShadowTy(AT->getElementType()),
1027                           AT->getNumElements());
1028   if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
1029     SmallVector<Type *, 4> Elements;
1030     for (unsigned I = 0, N = ST->getNumElements(); I < N; ++I)
1031       Elements.push_back(getShadowTy(ST->getElementType(I)));
1032     return StructType::get(*Ctx, Elements);
1033   }
1034   return PrimitiveShadowTy;
1035 }
1036 
1037 Type *DataFlowSanitizer::getShadowTy(Value *V) {
1038   return getShadowTy(V->getType());
1039 }
1040 
1041 bool DataFlowSanitizer::init(Module &M) {
1042   Triple TargetTriple(M.getTargetTriple());
1043   const DataLayout &DL = M.getDataLayout();
1044 
1045   Mod = &M;
1046   Ctx = &M.getContext();
1047   Int8Ptr = Type::getInt8PtrTy(*Ctx);
1048   OriginTy = IntegerType::get(*Ctx, OriginWidthBits);
1049   OriginPtrTy = PointerType::getUnqual(OriginTy);
1050   PrimitiveShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
1051   PrimitiveShadowPtrTy = PointerType::getUnqual(PrimitiveShadowTy);
1052   IntptrTy = DL.getIntPtrType(*Ctx);
1053   ZeroPrimitiveShadow = ConstantInt::getSigned(PrimitiveShadowTy, 0);
1054   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidthBytes);
1055   OriginBase = ConstantInt::get(IntptrTy, 0x200000000000LL);
1056   ZeroOrigin = ConstantInt::getSigned(OriginTy, 0);
1057 
1058   switch (TargetTriple.getArch()) {
1059   case Triple::x86_64:
1060     ShadowPtrMask = ClFast8Labels
1061                         ? ConstantInt::getSigned(IntptrTy, ~0x600000000000LL)
1062                         : ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
1063     break;
1064   case Triple::mips64:
1065   case Triple::mips64el:
1066     ShadowPtrMask = ClFast8Labels
1067                         ? ConstantInt::getSigned(IntptrTy, ~0xE000000000LL)
1068                         : ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
1069     break;
1070   case Triple::aarch64:
1071   case Triple::aarch64_be:
1072     // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
1073     DFSanRuntimeShadowMask = true;
1074     break;
1075   default:
1076     report_fatal_error("unsupported triple");
1077   }
1078 
1079   Type *DFSanUnionArgs[2] = {PrimitiveShadowTy, PrimitiveShadowTy};
1080   DFSanUnionFnTy =
1081       FunctionType::get(PrimitiveShadowTy, DFSanUnionArgs, /*isVarArg=*/false);
1082   Type *DFSanUnionLoadArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
1083   DFSanUnionLoadFnTy = FunctionType::get(PrimitiveShadowTy, DFSanUnionLoadArgs,
1084                                          /*isVarArg=*/false);
1085   Type *DFSanLoadLabelAndOriginArgs[2] = {Int8Ptr, IntptrTy};
1086   DFSanLoadLabelAndOriginFnTy =
1087       FunctionType::get(IntegerType::get(*Ctx, 64), DFSanLoadLabelAndOriginArgs,
1088                         /*isVarArg=*/false);
1089   DFSanUnimplementedFnTy = FunctionType::get(
1090       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
1091   Type *DFSanSetLabelArgs[4] = {PrimitiveShadowTy, OriginTy,
1092                                 Type::getInt8PtrTy(*Ctx), IntptrTy};
1093   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
1094                                         DFSanSetLabelArgs, /*isVarArg=*/false);
1095   DFSanNonzeroLabelFnTy =
1096       FunctionType::get(Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
1097   DFSanVarargWrapperFnTy = FunctionType::get(
1098       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
1099   DFSanCmpCallbackFnTy =
1100       FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy,
1101                         /*isVarArg=*/false);
1102   DFSanChainOriginFnTy =
1103       FunctionType::get(OriginTy, OriginTy, /*isVarArg=*/false);
1104   Type *DFSanMaybeStoreOriginArgs[4] = {IntegerType::get(*Ctx, ShadowWidthBits),
1105                                         Int8Ptr, IntptrTy, OriginTy};
1106   DFSanMaybeStoreOriginFnTy = FunctionType::get(
1107       Type::getVoidTy(*Ctx), DFSanMaybeStoreOriginArgs, /*isVarArg=*/false);
1108   Type *DFSanMemOriginTransferArgs[3] = {Int8Ptr, Int8Ptr, IntptrTy};
1109   DFSanMemOriginTransferFnTy = FunctionType::get(
1110       Type::getVoidTy(*Ctx), DFSanMemOriginTransferArgs, /*isVarArg=*/false);
1111   Type *DFSanLoadStoreCallbackArgs[2] = {PrimitiveShadowTy, Int8Ptr};
1112   DFSanLoadStoreCallbackFnTy =
1113       FunctionType::get(Type::getVoidTy(*Ctx), DFSanLoadStoreCallbackArgs,
1114                         /*isVarArg=*/false);
1115   Type *DFSanMemTransferCallbackArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
1116   DFSanMemTransferCallbackFnTy =
1117       FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs,
1118                         /*isVarArg=*/false);
1119 
1120   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
1121   OriginStoreWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
1122   return true;
1123 }
1124 
1125 bool DataFlowSanitizer::isInstrumented(const Function *F) {
1126   return !ABIList.isIn(*F, "uninstrumented");
1127 }
1128 
1129 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
1130   return !ABIList.isIn(*GA, "uninstrumented");
1131 }
1132 
1133 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
1134   return ClArgsABI ? IA_Args : IA_TLS;
1135 }
1136 
1137 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
1138   if (ABIList.isIn(*F, "functional"))
1139     return WK_Functional;
1140   if (ABIList.isIn(*F, "discard"))
1141     return WK_Discard;
1142   if (ABIList.isIn(*F, "custom"))
1143     return WK_Custom;
1144 
1145   return WK_Warning;
1146 }
1147 
1148 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
1149   std::string GVName = std::string(GV->getName()), Prefix = "dfs$";
1150   GV->setName(Prefix + GVName);
1151 
1152   // Try to change the name of the function in module inline asm.  We only do
1153   // this for specific asm directives, currently only ".symver", to try to avoid
1154   // corrupting asm which happens to contain the symbol name as a substring.
1155   // Note that the substitution for .symver assumes that the versioned symbol
1156   // also has an instrumented name.
1157   std::string Asm = GV->getParent()->getModuleInlineAsm();
1158   std::string SearchStr = ".symver " + GVName + ",";
1159   size_t Pos = Asm.find(SearchStr);
1160   if (Pos != std::string::npos) {
1161     Asm.replace(Pos, SearchStr.size(),
1162                 ".symver " + Prefix + GVName + "," + Prefix);
1163     GV->getParent()->setModuleInlineAsm(Asm);
1164   }
1165 }
1166 
1167 Function *
1168 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
1169                                         GlobalValue::LinkageTypes NewFLink,
1170                                         FunctionType *NewFT) {
1171   FunctionType *FT = F->getFunctionType();
1172   Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
1173                                     NewFName, F->getParent());
1174   NewF->copyAttributesFrom(F);
1175   NewF->removeAttributes(
1176       AttributeList::ReturnIndex,
1177       AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1178 
1179   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
1180   if (F->isVarArg()) {
1181     NewF->removeAttributes(AttributeList::FunctionIndex,
1182                            AttrBuilder().addAttribute("split-stack"));
1183     CallInst::Create(DFSanVarargWrapperFn,
1184                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
1185                      BB);
1186     new UnreachableInst(*Ctx, BB);
1187   } else {
1188     auto ArgIt = pointer_iterator<Argument *>(NewF->arg_begin());
1189     std::vector<Value *> Args(ArgIt, ArgIt + FT->getNumParams());
1190 
1191     CallInst *CI = CallInst::Create(F, Args, "", BB);
1192     if (FT->getReturnType()->isVoidTy())
1193       ReturnInst::Create(*Ctx, BB);
1194     else
1195       ReturnInst::Create(*Ctx, CI, BB);
1196   }
1197 
1198   return NewF;
1199 }
1200 
1201 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
1202                                                           StringRef FName) {
1203   FunctionType *FTT = getTrampolineFunctionType(FT);
1204   FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
1205   Function *F = dyn_cast<Function>(C.getCallee());
1206   if (F && F->isDeclaration()) {
1207     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
1208     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
1209     std::vector<Value *> Args;
1210     Function::arg_iterator AI = F->arg_begin() + 1;
1211     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
1212       Args.push_back(&*AI);
1213     CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
1214     Type *RetType = FT->getReturnType();
1215     ReturnInst *RI = RetType->isVoidTy() ? ReturnInst::Create(*Ctx, BB)
1216                                          : ReturnInst::Create(*Ctx, CI, BB);
1217 
1218     // F is called by a wrapped custom function with primitive shadows. So
1219     // its arguments and return value need conversion.
1220     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
1221     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI;
1222     ++ValAI;
1223     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N) {
1224       Value *Shadow =
1225           DFSF.expandFromPrimitiveShadow(ValAI->getType(), &*ShadowAI, CI);
1226       DFSF.ValShadowMap[&*ValAI] = Shadow;
1227     }
1228     Function::arg_iterator RetShadowAI = ShadowAI;
1229     const bool ShouldTrackOrigins = shouldTrackOrigins();
1230     if (ShouldTrackOrigins) {
1231       ValAI = F->arg_begin();
1232       ++ValAI;
1233       Function::arg_iterator OriginAI = ShadowAI;
1234       if (!RetType->isVoidTy())
1235         ++OriginAI;
1236       for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++OriginAI, --N) {
1237         DFSF.ValOriginMap[&*ValAI] = &*OriginAI;
1238       }
1239     }
1240     DFSanVisitor(DFSF).visitCallInst(*CI);
1241     if (!RetType->isVoidTy()) {
1242       Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(
1243           DFSF.getShadow(RI->getReturnValue()), RI);
1244       new StoreInst(PrimitiveShadow, &*RetShadowAI, RI);
1245       if (ShouldTrackOrigins) {
1246         Value *Origin = DFSF.getOrigin(RI->getReturnValue());
1247         new StoreInst(Origin, &*std::prev(F->arg_end()), RI);
1248       }
1249     }
1250   }
1251 
1252   return cast<Constant>(C.getCallee());
1253 }
1254 
1255 // Initialize DataFlowSanitizer runtime functions and declare them in the module
1256 void DataFlowSanitizer::initializeRuntimeFunctions(Module &M) {
1257   {
1258     AttributeList AL;
1259     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1260                          Attribute::NoUnwind);
1261     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1262                          Attribute::ReadNone);
1263     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1264                          Attribute::ZExt);
1265     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1266     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1267     DFSanUnionFn =
1268         Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL);
1269   }
1270   {
1271     AttributeList AL;
1272     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1273                          Attribute::NoUnwind);
1274     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1275                          Attribute::ReadNone);
1276     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1277                          Attribute::ZExt);
1278     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1279     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1280     DFSanCheckedUnionFn =
1281         Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL);
1282   }
1283   {
1284     AttributeList AL;
1285     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1286                          Attribute::NoUnwind);
1287     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1288                          Attribute::ReadOnly);
1289     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1290                          Attribute::ZExt);
1291     DFSanUnionLoadFn =
1292         Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
1293   }
1294   {
1295     AttributeList AL;
1296     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1297                          Attribute::NoUnwind);
1298     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1299                          Attribute::ReadOnly);
1300     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1301                          Attribute::ZExt);
1302     DFSanUnionLoadFastLabelsFn = Mod->getOrInsertFunction(
1303         "__dfsan_union_load_fast16labels", DFSanUnionLoadFnTy, AL);
1304   }
1305   {
1306     AttributeList AL;
1307     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1308                          Attribute::NoUnwind);
1309     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1310                          Attribute::ReadOnly);
1311     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1312                          Attribute::ZExt);
1313     DFSanLoadLabelAndOriginFn = Mod->getOrInsertFunction(
1314         "__dfsan_load_label_and_origin", DFSanLoadLabelAndOriginFnTy, AL);
1315   }
1316   DFSanUnimplementedFn =
1317       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
1318   {
1319     AttributeList AL;
1320     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1321     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1322     DFSanSetLabelFn =
1323         Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
1324   }
1325   DFSanNonzeroLabelFn =
1326       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
1327   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
1328                                                   DFSanVarargWrapperFnTy);
1329   {
1330     AttributeList AL;
1331     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1332     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1333                          Attribute::ZExt);
1334     DFSanChainOriginFn = Mod->getOrInsertFunction("__dfsan_chain_origin",
1335                                                   DFSanChainOriginFnTy, AL);
1336   }
1337   DFSanMemOriginTransferFn = Mod->getOrInsertFunction(
1338       "__dfsan_mem_origin_transfer", DFSanMemOriginTransferFnTy);
1339 
1340   {
1341     AttributeList AL;
1342     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1343     AL = AL.addParamAttribute(M.getContext(), 3, Attribute::ZExt);
1344     DFSanMaybeStoreOriginFn = Mod->getOrInsertFunction(
1345         "__dfsan_maybe_store_origin", DFSanMaybeStoreOriginFnTy, AL);
1346   }
1347 
1348   DFSanRuntimeFunctions.insert(DFSanUnionFn.getCallee()->stripPointerCasts());
1349   DFSanRuntimeFunctions.insert(
1350       DFSanCheckedUnionFn.getCallee()->stripPointerCasts());
1351   DFSanRuntimeFunctions.insert(
1352       DFSanUnionLoadFn.getCallee()->stripPointerCasts());
1353   DFSanRuntimeFunctions.insert(
1354       DFSanUnionLoadFastLabelsFn.getCallee()->stripPointerCasts());
1355   DFSanRuntimeFunctions.insert(
1356       DFSanLoadLabelAndOriginFn.getCallee()->stripPointerCasts());
1357   DFSanRuntimeFunctions.insert(
1358       DFSanUnimplementedFn.getCallee()->stripPointerCasts());
1359   DFSanRuntimeFunctions.insert(
1360       DFSanSetLabelFn.getCallee()->stripPointerCasts());
1361   DFSanRuntimeFunctions.insert(
1362       DFSanNonzeroLabelFn.getCallee()->stripPointerCasts());
1363   DFSanRuntimeFunctions.insert(
1364       DFSanVarargWrapperFn.getCallee()->stripPointerCasts());
1365   DFSanRuntimeFunctions.insert(
1366       DFSanLoadCallbackFn.getCallee()->stripPointerCasts());
1367   DFSanRuntimeFunctions.insert(
1368       DFSanStoreCallbackFn.getCallee()->stripPointerCasts());
1369   DFSanRuntimeFunctions.insert(
1370       DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts());
1371   DFSanRuntimeFunctions.insert(
1372       DFSanCmpCallbackFn.getCallee()->stripPointerCasts());
1373   DFSanRuntimeFunctions.insert(
1374       DFSanChainOriginFn.getCallee()->stripPointerCasts());
1375   DFSanRuntimeFunctions.insert(
1376       DFSanMemOriginTransferFn.getCallee()->stripPointerCasts());
1377   DFSanRuntimeFunctions.insert(
1378       DFSanMaybeStoreOriginFn.getCallee()->stripPointerCasts());
1379 }
1380 
1381 // Initializes event callback functions and declare them in the module
1382 void DataFlowSanitizer::initializeCallbackFunctions(Module &M) {
1383   DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback",
1384                                                  DFSanLoadStoreCallbackFnTy);
1385   DFSanStoreCallbackFn = Mod->getOrInsertFunction("__dfsan_store_callback",
1386                                                   DFSanLoadStoreCallbackFnTy);
1387   DFSanMemTransferCallbackFn = Mod->getOrInsertFunction(
1388       "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy);
1389   DFSanCmpCallbackFn =
1390       Mod->getOrInsertFunction("__dfsan_cmp_callback", DFSanCmpCallbackFnTy);
1391 }
1392 
1393 void DataFlowSanitizer::injectMetadataGlobals(Module &M) {
1394   // These variables can be used:
1395   // - by the runtime (to discover what the shadow width was, during
1396   //   compilation)
1397   // - in testing (to avoid hardcoding the shadow width and type but instead
1398   //   extract them by pattern matching)
1399   Type *IntTy = Type::getInt32Ty(*Ctx);
1400   (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bits", IntTy, [&] {
1401     return new GlobalVariable(
1402         M, IntTy, /*isConstant=*/true, GlobalValue::WeakODRLinkage,
1403         ConstantInt::get(IntTy, ShadowWidthBits), "__dfsan_shadow_width_bits");
1404   });
1405   (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bytes", IntTy, [&] {
1406     return new GlobalVariable(M, IntTy, /*isConstant=*/true,
1407                               GlobalValue::WeakODRLinkage,
1408                               ConstantInt::get(IntTy, ShadowWidthBytes),
1409                               "__dfsan_shadow_width_bytes");
1410   });
1411 }
1412 
1413 bool DataFlowSanitizer::runImpl(Module &M) {
1414   init(M);
1415 
1416   if (ABIList.isIn(M, "skip"))
1417     return false;
1418 
1419   const unsigned InitialGlobalSize = M.global_size();
1420   const unsigned InitialModuleSize = M.size();
1421 
1422   bool Changed = false;
1423 
1424   auto GetOrInsertGlobal = [this, &Changed](StringRef Name,
1425                                             Type *Ty) -> Constant * {
1426     Constant *C = Mod->getOrInsertGlobal(Name, Ty);
1427     if (GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1428       Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel;
1429       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
1430     }
1431     return C;
1432   };
1433 
1434   // These globals must be kept in sync with the ones in dfsan.cpp.
1435   ArgTLS =
1436       GetOrInsertGlobal("__dfsan_arg_tls",
1437                         ArrayType::get(Type::getInt64Ty(*Ctx), ArgTLSSize / 8));
1438   RetvalTLS = GetOrInsertGlobal(
1439       "__dfsan_retval_tls",
1440       ArrayType::get(Type::getInt64Ty(*Ctx), RetvalTLSSize / 8));
1441   ArgOriginTLSTy = ArrayType::get(OriginTy, NumOfElementsInArgOrgTLS);
1442   ArgOriginTLS = GetOrInsertGlobal("__dfsan_arg_origin_tls", ArgOriginTLSTy);
1443   RetvalOriginTLS = GetOrInsertGlobal("__dfsan_retval_origin_tls", OriginTy);
1444 
1445   (void)Mod->getOrInsertGlobal("__dfsan_track_origins", OriginTy, [&] {
1446     Changed = true;
1447     return new GlobalVariable(
1448         M, OriginTy, true, GlobalValue::WeakODRLinkage,
1449         ConstantInt::getSigned(OriginTy, shouldTrackOrigins()),
1450         "__dfsan_track_origins");
1451   });
1452 
1453   injectMetadataGlobals(M);
1454 
1455   ExternalShadowMask =
1456       Mod->getOrInsertGlobal(DFSanExternShadowPtrMask, IntptrTy);
1457 
1458   initializeCallbackFunctions(M);
1459   initializeRuntimeFunctions(M);
1460 
1461   std::vector<Function *> FnsToInstrument;
1462   SmallPtrSet<Function *, 2> FnsWithNativeABI;
1463   for (Function &F : M)
1464     if (!F.isIntrinsic() && !DFSanRuntimeFunctions.contains(&F))
1465       FnsToInstrument.push_back(&F);
1466 
1467   // Give function aliases prefixes when necessary, and build wrappers where the
1468   // instrumentedness is inconsistent.
1469   for (Module::alias_iterator AI = M.alias_begin(), AE = M.alias_end();
1470        AI != AE;) {
1471     GlobalAlias *GA = &*AI;
1472     ++AI;
1473     // Don't stop on weak.  We assume people aren't playing games with the
1474     // instrumentedness of overridden weak aliases.
1475     auto *F = dyn_cast<Function>(GA->getBaseObject());
1476     if (!F)
1477       continue;
1478 
1479     bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
1480     if (GAInst && FInst) {
1481       addGlobalNamePrefix(GA);
1482     } else if (GAInst != FInst) {
1483       // Non-instrumented alias of an instrumented function, or vice versa.
1484       // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
1485       // below will take care of instrumenting it.
1486       Function *NewF =
1487           buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
1488       GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
1489       NewF->takeName(GA);
1490       GA->eraseFromParent();
1491       FnsToInstrument.push_back(NewF);
1492     }
1493   }
1494 
1495   ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
1496       .addAttribute(Attribute::ReadNone);
1497 
1498   // First, change the ABI of every function in the module.  ABI-listed
1499   // functions keep their original ABI and get a wrapper function.
1500   for (std::vector<Function *>::iterator FI = FnsToInstrument.begin(),
1501                                          FE = FnsToInstrument.end();
1502        FI != FE; ++FI) {
1503     Function &F = **FI;
1504     FunctionType *FT = F.getFunctionType();
1505 
1506     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
1507                               FT->getReturnType()->isVoidTy());
1508 
1509     if (isInstrumented(&F)) {
1510       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
1511       // easily identify cases of mismatching ABIs.
1512       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
1513         FunctionType *NewFT = getArgsFunctionType(FT);
1514         Function *NewF = Function::Create(NewFT, F.getLinkage(),
1515                                           F.getAddressSpace(), "", &M);
1516         NewF->copyAttributesFrom(&F);
1517         NewF->removeAttributes(
1518             AttributeList::ReturnIndex,
1519             AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1520         for (Function::arg_iterator FArg = F.arg_begin(),
1521                                     NewFArg = NewF->arg_begin(),
1522                                     FArgEnd = F.arg_end();
1523              FArg != FArgEnd; ++FArg, ++NewFArg) {
1524           FArg->replaceAllUsesWith(&*NewFArg);
1525         }
1526         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
1527 
1528         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
1529              UI != UE;) {
1530           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
1531           ++UI;
1532           if (BA) {
1533             BA->replaceAllUsesWith(
1534                 BlockAddress::get(NewF, BA->getBasicBlock()));
1535             delete BA;
1536           }
1537         }
1538         F.replaceAllUsesWith(
1539             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
1540         NewF->takeName(&F);
1541         F.eraseFromParent();
1542         *FI = NewF;
1543         addGlobalNamePrefix(NewF);
1544       } else {
1545         addGlobalNamePrefix(&F);
1546       }
1547     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
1548       // Build a wrapper function for F.  The wrapper simply calls F, and is
1549       // added to FnsToInstrument so that any instrumentation according to its
1550       // WrapperKind is done in the second pass below.
1551       FunctionType *NewFT =
1552           getInstrumentedABI() == IA_Args ? getArgsFunctionType(FT) : FT;
1553 
1554       // If the function being wrapped has local linkage, then preserve the
1555       // function's linkage in the wrapper function.
1556       GlobalValue::LinkageTypes WrapperLinkage =
1557           F.hasLocalLinkage() ? F.getLinkage()
1558                               : GlobalValue::LinkOnceODRLinkage;
1559 
1560       Function *NewF = buildWrapperFunction(
1561           &F,
1562           (shouldTrackOrigins() ? std::string("dfso$") : std::string("dfsw$")) +
1563               std::string(F.getName()),
1564           WrapperLinkage, NewFT);
1565       if (getInstrumentedABI() == IA_TLS)
1566         NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
1567 
1568       Value *WrappedFnCst =
1569           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
1570       F.replaceAllUsesWith(WrappedFnCst);
1571 
1572       UnwrappedFnMap[WrappedFnCst] = &F;
1573       *FI = NewF;
1574 
1575       if (!F.isDeclaration()) {
1576         // This function is probably defining an interposition of an
1577         // uninstrumented function and hence needs to keep the original ABI.
1578         // But any functions it may call need to use the instrumented ABI, so
1579         // we instrument it in a mode which preserves the original ABI.
1580         FnsWithNativeABI.insert(&F);
1581 
1582         // This code needs to rebuild the iterators, as they may be invalidated
1583         // by the push_back, taking care that the new range does not include
1584         // any functions added by this code.
1585         size_t N = FI - FnsToInstrument.begin(),
1586                Count = FE - FnsToInstrument.begin();
1587         FnsToInstrument.push_back(&F);
1588         FI = FnsToInstrument.begin() + N;
1589         FE = FnsToInstrument.begin() + Count;
1590       }
1591       // Hopefully, nobody will try to indirectly call a vararg
1592       // function... yet.
1593     } else if (FT->isVarArg()) {
1594       UnwrappedFnMap[&F] = &F;
1595       *FI = nullptr;
1596     }
1597   }
1598 
1599   for (Function *F : FnsToInstrument) {
1600     if (!F || F->isDeclaration())
1601       continue;
1602 
1603     removeUnreachableBlocks(*F);
1604 
1605     DFSanFunction DFSF(*this, F, FnsWithNativeABI.count(F));
1606 
1607     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
1608     // Build a copy of the list before iterating over it.
1609     SmallVector<BasicBlock *, 4> BBList(depth_first(&F->getEntryBlock()));
1610 
1611     for (BasicBlock *BB : BBList) {
1612       Instruction *Inst = &BB->front();
1613       while (true) {
1614         // DFSanVisitor may split the current basic block, changing the current
1615         // instruction's next pointer and moving the next instruction to the
1616         // tail block from which we should continue.
1617         Instruction *Next = Inst->getNextNode();
1618         // DFSanVisitor may delete Inst, so keep track of whether it was a
1619         // terminator.
1620         bool IsTerminator = Inst->isTerminator();
1621         if (!DFSF.SkipInsts.count(Inst))
1622           DFSanVisitor(DFSF).visit(Inst);
1623         if (IsTerminator)
1624           break;
1625         Inst = Next;
1626       }
1627     }
1628 
1629     // We will not necessarily be able to compute the shadow for every phi node
1630     // until we have visited every block.  Therefore, the code that handles phi
1631     // nodes adds them to the PHIFixups list so that they can be properly
1632     // handled here.
1633     for (DFSanFunction::PHIFixupElement &P : DFSF.PHIFixups) {
1634       for (unsigned Val = 0, N = P.Phi->getNumIncomingValues(); Val != N;
1635            ++Val) {
1636         P.ShadowPhi->setIncomingValue(
1637             Val, DFSF.getShadow(P.Phi->getIncomingValue(Val)));
1638         if (P.OriginPhi)
1639           P.OriginPhi->setIncomingValue(
1640               Val, DFSF.getOrigin(P.Phi->getIncomingValue(Val)));
1641       }
1642     }
1643 
1644     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
1645     // places (i.e. instructions in basic blocks we haven't even begun visiting
1646     // yet).  To make our life easier, do this work in a pass after the main
1647     // instrumentation.
1648     if (ClDebugNonzeroLabels) {
1649       for (Value *V : DFSF.NonZeroChecks) {
1650         Instruction *Pos;
1651         if (Instruction *I = dyn_cast<Instruction>(V))
1652           Pos = I->getNextNode();
1653         else
1654           Pos = &DFSF.F->getEntryBlock().front();
1655         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
1656           Pos = Pos->getNextNode();
1657         IRBuilder<> IRB(Pos);
1658         Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(V, Pos);
1659         Value *Ne =
1660             IRB.CreateICmpNE(PrimitiveShadow, DFSF.DFS.ZeroPrimitiveShadow);
1661         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1662             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
1663         IRBuilder<> ThenIRB(BI);
1664         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1665       }
1666     }
1667   }
1668 
1669   return Changed || !FnsToInstrument.empty() ||
1670          M.global_size() != InitialGlobalSize || M.size() != InitialModuleSize;
1671 }
1672 
1673 Value *DFSanFunction::getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB) {
1674   Value *Base = IRB.CreatePointerCast(DFS.ArgTLS, DFS.IntptrTy);
1675   if (ArgOffset)
1676     Base = IRB.CreateAdd(Base, ConstantInt::get(DFS.IntptrTy, ArgOffset));
1677   return IRB.CreateIntToPtr(Base, PointerType::get(DFS.getShadowTy(T), 0),
1678                             "_dfsarg");
1679 }
1680 
1681 Value *DFSanFunction::getRetvalTLS(Type *T, IRBuilder<> &IRB) {
1682   return IRB.CreatePointerCast(
1683       DFS.RetvalTLS, PointerType::get(DFS.getShadowTy(T), 0), "_dfsret");
1684 }
1685 
1686 Value *DFSanFunction::getRetvalOriginTLS() { return DFS.RetvalOriginTLS; }
1687 
1688 Value *DFSanFunction::getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB) {
1689   return IRB.CreateConstGEP2_64(DFS.ArgOriginTLSTy, DFS.ArgOriginTLS, 0, ArgNo,
1690                                 "_dfsarg_o");
1691 }
1692 
1693 Value *DFSanFunction::getOrigin(Value *V) {
1694   assert(DFS.shouldTrackOrigins());
1695   if (!isa<Argument>(V) && !isa<Instruction>(V))
1696     return DFS.ZeroOrigin;
1697   Value *&Origin = ValOriginMap[V];
1698   if (!Origin) {
1699     if (Argument *A = dyn_cast<Argument>(V)) {
1700       if (IsNativeABI)
1701         return DFS.ZeroOrigin;
1702       switch (IA) {
1703       case DataFlowSanitizer::IA_TLS: {
1704         if (A->getArgNo() < DFS.NumOfElementsInArgOrgTLS) {
1705           Instruction *ArgOriginTLSPos = &*F->getEntryBlock().begin();
1706           IRBuilder<> IRB(ArgOriginTLSPos);
1707           Value *ArgOriginPtr = getArgOriginTLS(A->getArgNo(), IRB);
1708           Origin = IRB.CreateLoad(DFS.OriginTy, ArgOriginPtr);
1709         } else {
1710           // Overflow
1711           Origin = DFS.ZeroOrigin;
1712         }
1713         break;
1714       }
1715       case DataFlowSanitizer::IA_Args: {
1716         Origin = DFS.ZeroOrigin;
1717         break;
1718       }
1719       }
1720     } else {
1721       Origin = DFS.ZeroOrigin;
1722     }
1723   }
1724   return Origin;
1725 }
1726 
1727 void DFSanFunction::setOrigin(Instruction *I, Value *Origin) {
1728   if (!DFS.shouldTrackOrigins())
1729     return;
1730   assert(!ValOriginMap.count(I));
1731   assert(Origin->getType() == DFS.OriginTy);
1732   ValOriginMap[I] = Origin;
1733 }
1734 
1735 Value *DFSanFunction::getShadowForTLSArgument(Argument *A) {
1736   unsigned ArgOffset = 0;
1737   const DataLayout &DL = F->getParent()->getDataLayout();
1738   for (auto &FArg : F->args()) {
1739     if (!FArg.getType()->isSized()) {
1740       if (A == &FArg)
1741         break;
1742       continue;
1743     }
1744 
1745     unsigned Size = DL.getTypeAllocSize(DFS.getShadowTy(&FArg));
1746     if (A != &FArg) {
1747       ArgOffset += alignTo(Size, ShadowTLSAlignment);
1748       if (ArgOffset > ArgTLSSize)
1749         break; // ArgTLS overflows, uses a zero shadow.
1750       continue;
1751     }
1752 
1753     if (ArgOffset + Size > ArgTLSSize)
1754       break; // ArgTLS overflows, uses a zero shadow.
1755 
1756     Instruction *ArgTLSPos = &*F->getEntryBlock().begin();
1757     IRBuilder<> IRB(ArgTLSPos);
1758     Value *ArgShadowPtr = getArgTLS(FArg.getType(), ArgOffset, IRB);
1759     return IRB.CreateAlignedLoad(DFS.getShadowTy(&FArg), ArgShadowPtr,
1760                                  ShadowTLSAlignment);
1761   }
1762 
1763   return DFS.getZeroShadow(A);
1764 }
1765 
1766 Value *DFSanFunction::getShadow(Value *V) {
1767   if (!isa<Argument>(V) && !isa<Instruction>(V))
1768     return DFS.getZeroShadow(V);
1769   Value *&Shadow = ValShadowMap[V];
1770   if (!Shadow) {
1771     if (Argument *A = dyn_cast<Argument>(V)) {
1772       if (IsNativeABI)
1773         return DFS.getZeroShadow(V);
1774       switch (IA) {
1775       case DataFlowSanitizer::IA_TLS: {
1776         Shadow = getShadowForTLSArgument(A);
1777         break;
1778       }
1779       case DataFlowSanitizer::IA_Args: {
1780         unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
1781         Function::arg_iterator Arg = F->arg_begin();
1782         std::advance(Arg, ArgIdx);
1783         Shadow = &*Arg;
1784         assert(Shadow->getType() == DFS.PrimitiveShadowTy);
1785         break;
1786       }
1787       }
1788       NonZeroChecks.push_back(Shadow);
1789     } else {
1790       Shadow = DFS.getZeroShadow(V);
1791     }
1792   }
1793   return Shadow;
1794 }
1795 
1796 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1797   assert(!ValShadowMap.count(I));
1798   assert(DFS.shouldTrackFieldsAndIndices() ||
1799          Shadow->getType() == DFS.PrimitiveShadowTy);
1800   ValShadowMap[I] = Shadow;
1801 }
1802 
1803 Value *DataFlowSanitizer::getShadowOffset(Value *Addr, IRBuilder<> &IRB) {
1804   // Returns Addr & shadow_mask
1805   assert(Addr != RetvalTLS && "Reinstrumenting?");
1806   Value *ShadowPtrMaskValue;
1807   if (DFSanRuntimeShadowMask)
1808     ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
1809   else
1810     ShadowPtrMaskValue = ShadowPtrMask;
1811   return IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
1812                        IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy));
1813 }
1814 
1815 std::pair<Value *, Value *>
1816 DataFlowSanitizer::getShadowOriginAddress(Value *Addr, Align InstAlignment,
1817                                           Instruction *Pos) {
1818   // Returns ((Addr & shadow_mask) + origin_base) & ~4UL
1819   IRBuilder<> IRB(Pos);
1820   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1821   Value *ShadowPtr = getShadowAddress(Addr, Pos, ShadowOffset);
1822   Value *OriginPtr = nullptr;
1823   if (shouldTrackOrigins()) {
1824     Value *OriginLong = IRB.CreateAdd(ShadowOffset, OriginBase);
1825     const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1826     // When alignment is >= 4, Addr must be aligned to 4, otherwise it is UB.
1827     // So Mask is unnecessary.
1828     if (Alignment < MinOriginAlignment) {
1829       uint64_t Mask = MinOriginAlignment.value() - 1;
1830       OriginLong = IRB.CreateAnd(OriginLong, ConstantInt::get(IntptrTy, ~Mask));
1831     }
1832     OriginPtr = IRB.CreateIntToPtr(OriginLong, OriginPtrTy);
1833   }
1834   return {ShadowPtr, OriginPtr};
1835 }
1836 
1837 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos,
1838                                            Value *ShadowOffset) {
1839   IRBuilder<> IRB(Pos);
1840 
1841   if (!ShadowPtrMul->isOne())
1842     ShadowOffset = IRB.CreateMul(ShadowOffset, ShadowPtrMul);
1843 
1844   return IRB.CreateIntToPtr(ShadowOffset, PrimitiveShadowPtrTy);
1845 }
1846 
1847 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1848   // Returns (Addr & shadow_mask) x 2
1849   IRBuilder<> IRB(Pos);
1850   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1851   return getShadowAddress(Addr, Pos, ShadowOffset);
1852 }
1853 
1854 Value *DFSanFunction::combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
1855                                                 Instruction *Pos) {
1856   Value *PrimitiveValue = combineShadows(V1, V2, Pos);
1857   return expandFromPrimitiveShadow(T, PrimitiveValue, Pos);
1858 }
1859 
1860 // Generates IR to compute the union of the two given shadows, inserting it
1861 // before Pos. The combined value is with primitive type.
1862 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1863   if (DFS.isZeroShadow(V1))
1864     return collapseToPrimitiveShadow(V2, Pos);
1865   if (DFS.isZeroShadow(V2))
1866     return collapseToPrimitiveShadow(V1, Pos);
1867   if (V1 == V2)
1868     return collapseToPrimitiveShadow(V1, Pos);
1869 
1870   auto V1Elems = ShadowElements.find(V1);
1871   auto V2Elems = ShadowElements.find(V2);
1872   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1873     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1874                       V2Elems->second.begin(), V2Elems->second.end())) {
1875       return collapseToPrimitiveShadow(V1, Pos);
1876     }
1877     if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1878                       V1Elems->second.begin(), V1Elems->second.end())) {
1879       return collapseToPrimitiveShadow(V2, Pos);
1880     }
1881   } else if (V1Elems != ShadowElements.end()) {
1882     if (V1Elems->second.count(V2))
1883       return collapseToPrimitiveShadow(V1, Pos);
1884   } else if (V2Elems != ShadowElements.end()) {
1885     if (V2Elems->second.count(V1))
1886       return collapseToPrimitiveShadow(V2, Pos);
1887   }
1888 
1889   auto Key = std::make_pair(V1, V2);
1890   if (V1 > V2)
1891     std::swap(Key.first, Key.second);
1892   CachedShadow &CCS = CachedShadows[Key];
1893   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1894     return CCS.Shadow;
1895 
1896   // Converts inputs shadows to shadows with primitive types.
1897   Value *PV1 = collapseToPrimitiveShadow(V1, Pos);
1898   Value *PV2 = collapseToPrimitiveShadow(V2, Pos);
1899 
1900   IRBuilder<> IRB(Pos);
1901   if (DFS.hasFastLabelsEnabled()) {
1902     CCS.Block = Pos->getParent();
1903     CCS.Shadow = IRB.CreateOr(PV1, PV2);
1904   } else if (AvoidNewBlocks) {
1905     CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {PV1, PV2});
1906     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1907     Call->addParamAttr(0, Attribute::ZExt);
1908     Call->addParamAttr(1, Attribute::ZExt);
1909 
1910     CCS.Block = Pos->getParent();
1911     CCS.Shadow = Call;
1912   } else {
1913     BasicBlock *Head = Pos->getParent();
1914     Value *Ne = IRB.CreateICmpNE(PV1, PV2);
1915     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1916         Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1917     IRBuilder<> ThenIRB(BI);
1918     CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {PV1, PV2});
1919     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1920     Call->addParamAttr(0, Attribute::ZExt);
1921     Call->addParamAttr(1, Attribute::ZExt);
1922 
1923     BasicBlock *Tail = BI->getSuccessor(0);
1924     PHINode *Phi =
1925         PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
1926     Phi->addIncoming(Call, Call->getParent());
1927     Phi->addIncoming(PV1, Head);
1928 
1929     CCS.Block = Tail;
1930     CCS.Shadow = Phi;
1931   }
1932 
1933   std::set<Value *> UnionElems;
1934   if (V1Elems != ShadowElements.end()) {
1935     UnionElems = V1Elems->second;
1936   } else {
1937     UnionElems.insert(V1);
1938   }
1939   if (V2Elems != ShadowElements.end()) {
1940     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1941   } else {
1942     UnionElems.insert(V2);
1943   }
1944   ShadowElements[CCS.Shadow] = std::move(UnionElems);
1945 
1946   return CCS.Shadow;
1947 }
1948 
1949 // A convenience function which folds the shadows of each of the operands
1950 // of the provided instruction Inst, inserting the IR before Inst.  Returns
1951 // the computed union Value.
1952 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1953   if (Inst->getNumOperands() == 0)
1954     return DFS.getZeroShadow(Inst);
1955 
1956   Value *Shadow = getShadow(Inst->getOperand(0));
1957   for (unsigned I = 1, N = Inst->getNumOperands(); I < N; ++I)
1958     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(I)), Inst);
1959 
1960   return expandFromPrimitiveShadow(Inst->getType(), Shadow, Inst);
1961 }
1962 
1963 void DFSanVisitor::visitInstOperands(Instruction &I) {
1964   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1965   DFSF.setShadow(&I, CombinedShadow);
1966   visitInstOperandOrigins(I);
1967 }
1968 
1969 Value *DFSanFunction::combineOrigins(const std::vector<Value *> &Shadows,
1970                                      const std::vector<Value *> &Origins,
1971                                      Instruction *Pos, ConstantInt *Zero) {
1972   assert(Shadows.size() == Origins.size());
1973   size_t Size = Origins.size();
1974   if (Size == 0)
1975     return DFS.ZeroOrigin;
1976   Value *Origin = nullptr;
1977   if (!Zero)
1978     Zero = DFS.ZeroPrimitiveShadow;
1979   for (size_t I = 0; I != Size; ++I) {
1980     Value *OpOrigin = Origins[I];
1981     Constant *ConstOpOrigin = dyn_cast<Constant>(OpOrigin);
1982     if (ConstOpOrigin && ConstOpOrigin->isNullValue())
1983       continue;
1984     if (!Origin) {
1985       Origin = OpOrigin;
1986       continue;
1987     }
1988     Value *OpShadow = Shadows[I];
1989     Value *PrimitiveShadow = collapseToPrimitiveShadow(OpShadow, Pos);
1990     IRBuilder<> IRB(Pos);
1991     Value *Cond = IRB.CreateICmpNE(PrimitiveShadow, Zero);
1992     Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1993   }
1994   return Origin ? Origin : DFS.ZeroOrigin;
1995 }
1996 
1997 Value *DFSanFunction::combineOperandOrigins(Instruction *Inst) {
1998   size_t Size = Inst->getNumOperands();
1999   std::vector<Value *> Shadows(Size);
2000   std::vector<Value *> Origins(Size);
2001   for (unsigned I = 0; I != Size; ++I) {
2002     Shadows[I] = getShadow(Inst->getOperand(I));
2003     Origins[I] = getOrigin(Inst->getOperand(I));
2004   }
2005   return combineOrigins(Shadows, Origins, Inst);
2006 }
2007 
2008 void DFSanVisitor::visitInstOperandOrigins(Instruction &I) {
2009   if (!DFSF.DFS.shouldTrackOrigins())
2010     return;
2011   Value *CombinedOrigin = DFSF.combineOperandOrigins(&I);
2012   DFSF.setOrigin(&I, CombinedOrigin);
2013 }
2014 
2015 Align DFSanFunction::getShadowAlign(Align InstAlignment) {
2016   const Align Alignment = ClPreserveAlignment ? InstAlignment : Align(1);
2017   return Align(Alignment.value() * DFS.ShadowWidthBytes);
2018 }
2019 
2020 Align DFSanFunction::getOriginAlign(Align InstAlignment) {
2021   const Align Alignment = llvm::assumeAligned(InstAlignment.value());
2022   return Align(std::max(MinOriginAlignment, Alignment));
2023 }
2024 
2025 bool DFSanFunction::useCallbackLoadLabelAndOrigin(uint64_t Size,
2026                                                   Align InstAlignment) {
2027   assert(Size != 0);
2028   // * if Size == 1, it is sufficient to load its origin aligned at 4.
2029   // * if Size == 2, we assume most cases Addr % 2 == 0, so it is sufficient to
2030   //   load its origin aligned at 4. If not, although origins may be lost, it
2031   //   should not happen very often.
2032   // * if align >= 4, Addr must be aligned to 4, otherwise it is UB. When
2033   //   Size % 4 == 0, it is more efficient to load origins without callbacks.
2034   // * Otherwise we use __dfsan_load_label_and_origin.
2035   // This should ensure that common cases run efficiently.
2036   if (Size <= 2)
2037     return false;
2038 
2039   const Align Alignment = llvm::assumeAligned(InstAlignment.value());
2040   if (Alignment >= MinOriginAlignment &&
2041       Size % (64 / DFS.ShadowWidthBits) == 0)
2042     return false;
2043 
2044   return true;
2045 }
2046 
2047 std::pair<Value *, Value *> DFSanFunction::loadFast16ShadowFast(
2048     Value *ShadowAddr, Value *OriginAddr, uint64_t Size, Align ShadowAlign,
2049     Align OriginAlign, Value *FirstOrigin, Instruction *Pos) {
2050   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins();
2051   const uint64_t ShadowSize = Size * DFS.ShadowWidthBytes;
2052 
2053   assert(Size >= 4 && "Not large enough load size for fast path!");
2054 
2055   // Used for origin tracking.
2056   std::vector<Value *> Shadows;
2057   std::vector<Value *> Origins;
2058 
2059   // Load instructions in LLVM can have arbitrary byte sizes (e.g., 3, 12, 20)
2060   // but this function is only used in a subset of cases that make it possible
2061   // to optimize the instrumentation.
2062   //
2063   // Specifically, when the shadow size in bytes (i.e., loaded bytes x shadow
2064   // per byte) is either:
2065   // - a multiple of 8  (common)
2066   // - equal to 4       (only for load32 in fast-8 mode)
2067   //
2068   // For the second case, we can fit the wide shadow in a 32-bit integer. In all
2069   // other cases, we use a 64-bit integer to hold the wide shadow.
2070   Type *WideShadowTy =
2071       ShadowSize == 4 ? Type::getInt32Ty(*DFS.Ctx) : Type::getInt64Ty(*DFS.Ctx);
2072 
2073   IRBuilder<> IRB(Pos);
2074   Value *WideAddr = IRB.CreateBitCast(ShadowAddr, WideShadowTy->getPointerTo());
2075   Value *CombinedWideShadow =
2076       IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
2077 
2078   if (ShouldTrackOrigins) {
2079     Shadows.push_back(CombinedWideShadow);
2080     Origins.push_back(FirstOrigin);
2081   }
2082 
2083   // First OR all the WideShadows (i.e., 64bit or 32bit shadow chunks) linearly;
2084   // then OR individual shadows within the combined WideShadow by binary ORing.
2085   // This is fewer instructions than ORing shadows individually, since it
2086   // needs logN shift/or instructions (N being the bytes of the combined wide
2087   // shadow).
2088   unsigned WideShadowBitWidth = WideShadowTy->getIntegerBitWidth();
2089   const uint64_t BytesPerWideShadow = WideShadowBitWidth / DFS.ShadowWidthBits;
2090 
2091   for (uint64_t ByteOfs = BytesPerWideShadow; ByteOfs < Size;
2092        ByteOfs += BytesPerWideShadow) {
2093     WideAddr = IRB.CreateGEP(WideShadowTy, WideAddr,
2094                              ConstantInt::get(DFS.IntptrTy, 1));
2095     Value *NextWideShadow =
2096         IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
2097     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, NextWideShadow);
2098     if (ShouldTrackOrigins) {
2099       Shadows.push_back(NextWideShadow);
2100       OriginAddr = IRB.CreateGEP(DFS.OriginTy, OriginAddr,
2101                                  ConstantInt::get(DFS.IntptrTy, 1));
2102       Origins.push_back(
2103           IRB.CreateAlignedLoad(DFS.OriginTy, OriginAddr, OriginAlign));
2104     }
2105   }
2106   for (unsigned Width = WideShadowBitWidth / 2; Width >= DFS.ShadowWidthBits;
2107        Width >>= 1) {
2108     Value *ShrShadow = IRB.CreateLShr(CombinedWideShadow, Width);
2109     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, ShrShadow);
2110   }
2111   return {IRB.CreateTrunc(CombinedWideShadow, DFS.PrimitiveShadowTy),
2112           ShouldTrackOrigins
2113               ? combineOrigins(Shadows, Origins, Pos,
2114                                ConstantInt::getSigned(IRB.getInt64Ty(), 0))
2115               : DFS.ZeroOrigin};
2116 }
2117 
2118 Value *DFSanFunction::loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size,
2119                                            Align ShadowAlign,
2120                                            Instruction *Pos) {
2121   // Fast path for the common case where each byte has identical shadow: load
2122   // shadow 64 (or 32) bits at a time, fall out to a __dfsan_union_load call if
2123   // any shadow is non-equal.
2124   BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
2125   IRBuilder<> FallbackIRB(FallbackBB);
2126   CallInst *FallbackCall = FallbackIRB.CreateCall(
2127       DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
2128   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
2129 
2130   const uint64_t ShadowSize = Size * DFS.ShadowWidthBytes;
2131   assert(Size >= 4 && "Not large enough load size for fast path!");
2132 
2133   // Same as in loadFast16AShadowsFast. In the case of load32, we can fit the
2134   // wide shadow in a 32-bit integer instead.
2135   Type *WideShadowTy =
2136       ShadowSize == 4 ? Type::getInt32Ty(*DFS.Ctx) : Type::getInt64Ty(*DFS.Ctx);
2137 
2138   // Compare each of the shadows stored in the loaded 64 bits to each other,
2139   // by computing (WideShadow rotl ShadowWidthBits) == WideShadow.
2140   IRBuilder<> IRB(Pos);
2141   unsigned WideShadowBitWidth = WideShadowTy->getIntegerBitWidth();
2142   Value *WideAddr = IRB.CreateBitCast(ShadowAddr, WideShadowTy->getPointerTo());
2143   Value *WideShadow =
2144       IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
2145   Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.PrimitiveShadowTy);
2146   Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidthBits);
2147   Value *ShrShadow =
2148       IRB.CreateLShr(WideShadow, WideShadowBitWidth - DFS.ShadowWidthBits);
2149   Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
2150   Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
2151 
2152   BasicBlock *Head = Pos->getParent();
2153   BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
2154 
2155   if (DomTreeNode *OldNode = DT.getNode(Head)) {
2156     std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
2157 
2158     DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
2159     for (auto *Child : Children)
2160       DT.changeImmediateDominator(Child, NewNode);
2161   }
2162 
2163   // In the following code LastBr will refer to the previous basic block's
2164   // conditional branch instruction, whose true successor is fixed up to point
2165   // to the next block during the loop below or to the tail after the final
2166   // iteration.
2167   BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
2168   ReplaceInstWithInst(Head->getTerminator(), LastBr);
2169   DT.addNewBlock(FallbackBB, Head);
2170 
2171   const uint64_t BytesPerWideShadow = WideShadowBitWidth / DFS.ShadowWidthBits;
2172 
2173   for (uint64_t ByteOfs = BytesPerWideShadow; ByteOfs < Size;
2174        ByteOfs += BytesPerWideShadow) {
2175     BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
2176     DT.addNewBlock(NextBB, LastBr->getParent());
2177     IRBuilder<> NextIRB(NextBB);
2178     WideAddr = NextIRB.CreateGEP(WideShadowTy, WideAddr,
2179                                  ConstantInt::get(DFS.IntptrTy, 1));
2180     Value *NextWideShadow =
2181         NextIRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
2182     ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
2183     LastBr->setSuccessor(0, NextBB);
2184     LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
2185   }
2186 
2187   LastBr->setSuccessor(0, Tail);
2188   FallbackIRB.CreateBr(Tail);
2189   PHINode *Shadow =
2190       PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
2191   Shadow->addIncoming(FallbackCall, FallbackBB);
2192   Shadow->addIncoming(TruncShadow, LastBr->getParent());
2193   return Shadow;
2194 }
2195 
2196 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
2197 // Addr has alignment Align, and take the union of each of those shadows. The
2198 // returned shadow always has primitive type.
2199 std::pair<Value *, Value *> DFSanFunction::loadShadowOrigin(Value *Addr,
2200                                                             uint64_t Size,
2201                                                             Align InstAlignment,
2202                                                             Instruction *Pos) {
2203   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins();
2204 
2205   // Non-escaped loads.
2206   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
2207     const auto SI = AllocaShadowMap.find(AI);
2208     if (SI != AllocaShadowMap.end()) {
2209       IRBuilder<> IRB(Pos);
2210       Value *ShadowLI = IRB.CreateLoad(DFS.PrimitiveShadowTy, SI->second);
2211       const auto OI = AllocaOriginMap.find(AI);
2212       assert(!ShouldTrackOrigins || OI != AllocaOriginMap.end());
2213       return {ShadowLI, ShouldTrackOrigins
2214                             ? IRB.CreateLoad(DFS.OriginTy, OI->second)
2215                             : nullptr};
2216     }
2217   }
2218 
2219   // Load from constant addresses.
2220   SmallVector<const Value *, 2> Objs;
2221   getUnderlyingObjects(Addr, Objs);
2222   bool AllConstants = true;
2223   for (const Value *Obj : Objs) {
2224     if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
2225       continue;
2226     if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
2227       continue;
2228 
2229     AllConstants = false;
2230     break;
2231   }
2232   if (AllConstants)
2233     return {DFS.ZeroPrimitiveShadow,
2234             ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr};
2235 
2236   if (Size == 0)
2237     return {DFS.ZeroPrimitiveShadow,
2238             ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr};
2239 
2240   // Use callback to load if this is not an optimizable case for origin
2241   // tracking.
2242   if (ShouldTrackOrigins &&
2243       useCallbackLoadLabelAndOrigin(Size, InstAlignment)) {
2244     IRBuilder<> IRB(Pos);
2245     CallInst *Call =
2246         IRB.CreateCall(DFS.DFSanLoadLabelAndOriginFn,
2247                        {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
2248                         ConstantInt::get(DFS.IntptrTy, Size)});
2249     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
2250     return {IRB.CreateTrunc(IRB.CreateLShr(Call, DFS.OriginWidthBits),
2251                             DFS.PrimitiveShadowTy),
2252             IRB.CreateTrunc(Call, DFS.OriginTy)};
2253   }
2254 
2255   // Other cases that support loading shadows or origins in a fast way.
2256   Value *ShadowAddr, *OriginAddr;
2257   std::tie(ShadowAddr, OriginAddr) =
2258       DFS.getShadowOriginAddress(Addr, InstAlignment, Pos);
2259 
2260   const Align ShadowAlign = getShadowAlign(InstAlignment);
2261   const Align OriginAlign = getOriginAlign(InstAlignment);
2262   Value *Origin = nullptr;
2263   if (ShouldTrackOrigins) {
2264     IRBuilder<> IRB(Pos);
2265     Origin = IRB.CreateAlignedLoad(DFS.OriginTy, OriginAddr, OriginAlign);
2266   }
2267 
2268   // When the byte size is small enough, we can load the shadow directly with
2269   // just a few instructions.
2270   switch (Size) {
2271   case 1: {
2272     LoadInst *LI = new LoadInst(DFS.PrimitiveShadowTy, ShadowAddr, "", Pos);
2273     LI->setAlignment(ShadowAlign);
2274     return {LI, Origin};
2275   }
2276   case 2: {
2277     IRBuilder<> IRB(Pos);
2278     Value *ShadowAddr1 = IRB.CreateGEP(DFS.PrimitiveShadowTy, ShadowAddr,
2279                                        ConstantInt::get(DFS.IntptrTy, 1));
2280     Value *Load =
2281         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr, ShadowAlign);
2282     Value *Load1 =
2283         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr1, ShadowAlign);
2284     return {combineShadows(Load, Load1, Pos), Origin};
2285   }
2286   }
2287   uint64_t ShadowSize = Size * DFS.ShadowWidthBytes;
2288   bool HasSizeForFastPath = ShadowSize % 8 == 0 || ShadowSize == 4;
2289   bool HasFastLabelsEnabled = DFS.hasFastLabelsEnabled();
2290 
2291   if (HasFastLabelsEnabled && HasSizeForFastPath)
2292     return loadFast16ShadowFast(ShadowAddr, OriginAddr, Size, ShadowAlign,
2293                                 OriginAlign, Origin, Pos);
2294 
2295   if (!AvoidNewBlocks && HasSizeForFastPath)
2296     return {loadLegacyShadowFast(ShadowAddr, Size, ShadowAlign, Pos), Origin};
2297 
2298   IRBuilder<> IRB(Pos);
2299   FunctionCallee &UnionLoadFn = HasFastLabelsEnabled
2300                                     ? DFS.DFSanUnionLoadFastLabelsFn
2301                                     : DFS.DFSanUnionLoadFn;
2302   CallInst *FallbackCall = IRB.CreateCall(
2303       UnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
2304   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
2305   return {FallbackCall, Origin};
2306 }
2307 
2308 static AtomicOrdering addAcquireOrdering(AtomicOrdering AO) {
2309   switch (AO) {
2310   case AtomicOrdering::NotAtomic:
2311     return AtomicOrdering::NotAtomic;
2312   case AtomicOrdering::Unordered:
2313   case AtomicOrdering::Monotonic:
2314   case AtomicOrdering::Acquire:
2315     return AtomicOrdering::Acquire;
2316   case AtomicOrdering::Release:
2317   case AtomicOrdering::AcquireRelease:
2318     return AtomicOrdering::AcquireRelease;
2319   case AtomicOrdering::SequentiallyConsistent:
2320     return AtomicOrdering::SequentiallyConsistent;
2321   }
2322   llvm_unreachable("Unknown ordering");
2323 }
2324 
2325 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
2326   auto &DL = LI.getModule()->getDataLayout();
2327   uint64_t Size = DL.getTypeStoreSize(LI.getType());
2328   if (Size == 0) {
2329     DFSF.setShadow(&LI, DFSF.DFS.getZeroShadow(&LI));
2330     DFSF.setOrigin(&LI, DFSF.DFS.ZeroOrigin);
2331     return;
2332   }
2333 
2334   // When an application load is atomic, increase atomic ordering between
2335   // atomic application loads and stores to ensure happen-before order; load
2336   // shadow data after application data; store zero shadow data before
2337   // application data. This ensure shadow loads return either labels of the
2338   // initial application data or zeros.
2339   if (LI.isAtomic())
2340     LI.setOrdering(addAcquireOrdering(LI.getOrdering()));
2341 
2342   Instruction *Pos = LI.isAtomic() ? LI.getNextNode() : &LI;
2343   std::vector<Value *> Shadows;
2344   std::vector<Value *> Origins;
2345   Value *PrimitiveShadow, *Origin;
2346   std::tie(PrimitiveShadow, Origin) =
2347       DFSF.loadShadowOrigin(LI.getPointerOperand(), Size, LI.getAlign(), Pos);
2348   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2349   if (ShouldTrackOrigins) {
2350     Shadows.push_back(PrimitiveShadow);
2351     Origins.push_back(Origin);
2352   }
2353   if (ClCombinePointerLabelsOnLoad) {
2354     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
2355     PrimitiveShadow = DFSF.combineShadows(PrimitiveShadow, PtrShadow, Pos);
2356     if (ShouldTrackOrigins) {
2357       Shadows.push_back(PtrShadow);
2358       Origins.push_back(DFSF.getOrigin(LI.getPointerOperand()));
2359     }
2360   }
2361   if (!DFSF.DFS.isZeroShadow(PrimitiveShadow))
2362     DFSF.NonZeroChecks.push_back(PrimitiveShadow);
2363 
2364   Value *Shadow =
2365       DFSF.expandFromPrimitiveShadow(LI.getType(), PrimitiveShadow, Pos);
2366   DFSF.setShadow(&LI, Shadow);
2367 
2368   if (ShouldTrackOrigins) {
2369     DFSF.setOrigin(&LI, DFSF.combineOrigins(Shadows, Origins, Pos));
2370   }
2371 
2372   if (ClEventCallbacks) {
2373     IRBuilder<> IRB(Pos);
2374     Value *Addr8 = IRB.CreateBitCast(LI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2375     IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, {PrimitiveShadow, Addr8});
2376   }
2377 }
2378 
2379 Value *DFSanFunction::updateOrigin(Value *V, IRBuilder<> &IRB) {
2380   if (!DFS.shouldTrackOrigins())
2381     return V;
2382   return IRB.CreateCall(DFS.DFSanChainOriginFn, V);
2383 }
2384 
2385 Value *DFSanFunction::originToIntptr(IRBuilder<> &IRB, Value *Origin) {
2386   const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes;
2387   const DataLayout &DL = F->getParent()->getDataLayout();
2388   unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy);
2389   if (IntptrSize == OriginSize)
2390     return Origin;
2391   assert(IntptrSize == OriginSize * 2);
2392   Origin = IRB.CreateIntCast(Origin, DFS.IntptrTy, /* isSigned */ false);
2393   return IRB.CreateOr(Origin, IRB.CreateShl(Origin, OriginSize * 8));
2394 }
2395 
2396 void DFSanFunction::paintOrigin(IRBuilder<> &IRB, Value *Origin,
2397                                 Value *StoreOriginAddr,
2398                                 uint64_t StoreOriginSize, Align Alignment) {
2399   const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes;
2400   const DataLayout &DL = F->getParent()->getDataLayout();
2401   const Align IntptrAlignment = DL.getABITypeAlign(DFS.IntptrTy);
2402   unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy);
2403   assert(IntptrAlignment >= MinOriginAlignment);
2404   assert(IntptrSize >= OriginSize);
2405 
2406   unsigned Ofs = 0;
2407   Align CurrentAlignment = Alignment;
2408   if (Alignment >= IntptrAlignment && IntptrSize > OriginSize) {
2409     Value *IntptrOrigin = originToIntptr(IRB, Origin);
2410     Value *IntptrStoreOriginPtr = IRB.CreatePointerCast(
2411         StoreOriginAddr, PointerType::get(DFS.IntptrTy, 0));
2412     for (unsigned I = 0; I < StoreOriginSize / IntptrSize; ++I) {
2413       Value *Ptr =
2414           I ? IRB.CreateConstGEP1_32(DFS.IntptrTy, IntptrStoreOriginPtr, I)
2415             : IntptrStoreOriginPtr;
2416       IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
2417       Ofs += IntptrSize / OriginSize;
2418       CurrentAlignment = IntptrAlignment;
2419     }
2420   }
2421 
2422   for (unsigned I = Ofs; I < (StoreOriginSize + OriginSize - 1) / OriginSize;
2423        ++I) {
2424     Value *GEP = I ? IRB.CreateConstGEP1_32(DFS.OriginTy, StoreOriginAddr, I)
2425                    : StoreOriginAddr;
2426     IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
2427     CurrentAlignment = MinOriginAlignment;
2428   }
2429 }
2430 
2431 Value *DFSanFunction::convertToBool(Value *V, IRBuilder<> &IRB,
2432                                     const Twine &Name) {
2433   Type *VTy = V->getType();
2434   assert(VTy->isIntegerTy());
2435   if (VTy->getIntegerBitWidth() == 1)
2436     // Just converting a bool to a bool, so do nothing.
2437     return V;
2438   return IRB.CreateICmpNE(V, ConstantInt::get(VTy, 0), Name);
2439 }
2440 
2441 void DFSanFunction::storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size,
2442                                 Value *Shadow, Value *Origin,
2443                                 Value *StoreOriginAddr, Align InstAlignment) {
2444   // Do not write origins for zero shadows because we do not trace origins for
2445   // untainted sinks.
2446   const Align OriginAlignment = getOriginAlign(InstAlignment);
2447   Value *CollapsedShadow = collapseToPrimitiveShadow(Shadow, Pos);
2448   IRBuilder<> IRB(Pos);
2449   if (auto *ConstantShadow = dyn_cast<Constant>(CollapsedShadow)) {
2450     if (!ConstantShadow->isZeroValue())
2451       paintOrigin(IRB, updateOrigin(Origin, IRB), StoreOriginAddr, Size,
2452                   OriginAlignment);
2453     return;
2454   }
2455 
2456   if (shouldInstrumentWithCall()) {
2457     IRB.CreateCall(DFS.DFSanMaybeStoreOriginFn,
2458                    {CollapsedShadow,
2459                     IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
2460                     ConstantInt::get(DFS.IntptrTy, Size), Origin});
2461   } else {
2462     Value *Cmp = convertToBool(CollapsedShadow, IRB, "_dfscmp");
2463     Instruction *CheckTerm = SplitBlockAndInsertIfThen(
2464         Cmp, &*IRB.GetInsertPoint(), false, DFS.OriginStoreWeights, &DT);
2465     IRBuilder<> IRBNew(CheckTerm);
2466     paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), StoreOriginAddr, Size,
2467                 OriginAlignment);
2468     ++NumOriginStores;
2469   }
2470 }
2471 
2472 void DFSanFunction::storeZeroPrimitiveShadow(Value *Addr, uint64_t Size,
2473                                              Align ShadowAlign,
2474                                              Instruction *Pos) {
2475   IRBuilder<> IRB(Pos);
2476   IntegerType *ShadowTy =
2477       IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits);
2478   Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
2479   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
2480   Value *ExtShadowAddr =
2481       IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
2482   IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
2483   // Do not write origins for 0 shadows because we do not trace origins for
2484   // untainted sinks.
2485 }
2486 
2487 void DFSanFunction::storePrimitiveShadowOrigin(Value *Addr, uint64_t Size,
2488                                                Align InstAlignment,
2489                                                Value *PrimitiveShadow,
2490                                                Value *Origin,
2491                                                Instruction *Pos) {
2492   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins() && Origin;
2493 
2494   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
2495     const auto SI = AllocaShadowMap.find(AI);
2496     if (SI != AllocaShadowMap.end()) {
2497       IRBuilder<> IRB(Pos);
2498       IRB.CreateStore(PrimitiveShadow, SI->second);
2499 
2500       // Do not write origins for 0 shadows because we do not trace origins for
2501       // untainted sinks.
2502       if (ShouldTrackOrigins && !DFS.isZeroShadow(PrimitiveShadow)) {
2503         const auto OI = AllocaOriginMap.find(AI);
2504         assert(OI != AllocaOriginMap.end() && Origin);
2505         IRB.CreateStore(Origin, OI->second);
2506       }
2507       return;
2508     }
2509   }
2510 
2511   const Align ShadowAlign = getShadowAlign(InstAlignment);
2512   if (DFS.isZeroShadow(PrimitiveShadow)) {
2513     storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, Pos);
2514     return;
2515   }
2516 
2517   IRBuilder<> IRB(Pos);
2518   Value *ShadowAddr, *OriginAddr;
2519   std::tie(ShadowAddr, OriginAddr) =
2520       DFS.getShadowOriginAddress(Addr, InstAlignment, Pos);
2521 
2522   const unsigned ShadowVecSize = 8;
2523   assert(ShadowVecSize * DFS.ShadowWidthBits <= 128 &&
2524          "Shadow vector is too large!");
2525 
2526   uint64_t Offset = 0;
2527   uint64_t LeftSize = Size;
2528   if (LeftSize >= ShadowVecSize) {
2529     auto *ShadowVecTy =
2530         FixedVectorType::get(DFS.PrimitiveShadowTy, ShadowVecSize);
2531     Value *ShadowVec = UndefValue::get(ShadowVecTy);
2532     for (unsigned I = 0; I != ShadowVecSize; ++I) {
2533       ShadowVec = IRB.CreateInsertElement(
2534           ShadowVec, PrimitiveShadow,
2535           ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), I));
2536     }
2537     Value *ShadowVecAddr =
2538         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
2539     do {
2540       Value *CurShadowVecAddr =
2541           IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
2542       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
2543       LeftSize -= ShadowVecSize;
2544       ++Offset;
2545     } while (LeftSize >= ShadowVecSize);
2546     Offset *= ShadowVecSize;
2547   }
2548   while (LeftSize > 0) {
2549     Value *CurShadowAddr =
2550         IRB.CreateConstGEP1_32(DFS.PrimitiveShadowTy, ShadowAddr, Offset);
2551     IRB.CreateAlignedStore(PrimitiveShadow, CurShadowAddr, ShadowAlign);
2552     --LeftSize;
2553     ++Offset;
2554   }
2555 
2556   if (ShouldTrackOrigins) {
2557     storeOrigin(Pos, Addr, Size, PrimitiveShadow, Origin, OriginAddr,
2558                 InstAlignment);
2559   }
2560 }
2561 
2562 static AtomicOrdering addReleaseOrdering(AtomicOrdering AO) {
2563   switch (AO) {
2564   case AtomicOrdering::NotAtomic:
2565     return AtomicOrdering::NotAtomic;
2566   case AtomicOrdering::Unordered:
2567   case AtomicOrdering::Monotonic:
2568   case AtomicOrdering::Release:
2569     return AtomicOrdering::Release;
2570   case AtomicOrdering::Acquire:
2571   case AtomicOrdering::AcquireRelease:
2572     return AtomicOrdering::AcquireRelease;
2573   case AtomicOrdering::SequentiallyConsistent:
2574     return AtomicOrdering::SequentiallyConsistent;
2575   }
2576   llvm_unreachable("Unknown ordering");
2577 }
2578 
2579 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
2580   auto &DL = SI.getModule()->getDataLayout();
2581   Value *Val = SI.getValueOperand();
2582   uint64_t Size = DL.getTypeStoreSize(Val->getType());
2583   if (Size == 0)
2584     return;
2585 
2586   // When an application store is atomic, increase atomic ordering between
2587   // atomic application loads and stores to ensure happen-before order; load
2588   // shadow data after application data; store zero shadow data before
2589   // application data. This ensure shadow loads return either labels of the
2590   // initial application data or zeros.
2591   if (SI.isAtomic())
2592     SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
2593 
2594   const bool ShouldTrackOrigins =
2595       DFSF.DFS.shouldTrackOrigins() && !SI.isAtomic();
2596   std::vector<Value *> Shadows;
2597   std::vector<Value *> Origins;
2598 
2599   Value *Shadow =
2600       SI.isAtomic() ? DFSF.DFS.getZeroShadow(Val) : DFSF.getShadow(Val);
2601 
2602   if (ShouldTrackOrigins) {
2603     Shadows.push_back(Shadow);
2604     Origins.push_back(DFSF.getOrigin(Val));
2605   }
2606 
2607   Value *PrimitiveShadow;
2608   if (ClCombinePointerLabelsOnStore) {
2609     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
2610     if (ShouldTrackOrigins) {
2611       Shadows.push_back(PtrShadow);
2612       Origins.push_back(DFSF.getOrigin(SI.getPointerOperand()));
2613     }
2614     PrimitiveShadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
2615   } else {
2616     PrimitiveShadow = DFSF.collapseToPrimitiveShadow(Shadow, &SI);
2617   }
2618   Value *Origin = nullptr;
2619   if (ShouldTrackOrigins)
2620     Origin = DFSF.combineOrigins(Shadows, Origins, &SI);
2621   DFSF.storePrimitiveShadowOrigin(SI.getPointerOperand(), Size, SI.getAlign(),
2622                                   PrimitiveShadow, Origin, &SI);
2623   if (ClEventCallbacks) {
2624     IRBuilder<> IRB(&SI);
2625     Value *Addr8 = IRB.CreateBitCast(SI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2626     IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, {PrimitiveShadow, Addr8});
2627   }
2628 }
2629 
2630 void DFSanVisitor::visitCASOrRMW(Align InstAlignment, Instruction &I) {
2631   assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
2632 
2633   Value *Val = I.getOperand(1);
2634   const auto &DL = I.getModule()->getDataLayout();
2635   uint64_t Size = DL.getTypeStoreSize(Val->getType());
2636   if (Size == 0)
2637     return;
2638 
2639   // Conservatively set data at stored addresses and return with zero shadow to
2640   // prevent shadow data races.
2641   IRBuilder<> IRB(&I);
2642   Value *Addr = I.getOperand(0);
2643   const Align ShadowAlign = DFSF.getShadowAlign(InstAlignment);
2644   DFSF.storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, &I);
2645   DFSF.setShadow(&I, DFSF.DFS.getZeroShadow(&I));
2646   DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin);
2647 }
2648 
2649 void DFSanVisitor::visitAtomicRMWInst(AtomicRMWInst &I) {
2650   visitCASOrRMW(I.getAlign(), I);
2651   // TODO: The ordering change follows MSan. It is possible not to change
2652   // ordering because we always set and use 0 shadows.
2653   I.setOrdering(addReleaseOrdering(I.getOrdering()));
2654 }
2655 
2656 void DFSanVisitor::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
2657   visitCASOrRMW(I.getAlign(), I);
2658   // TODO: The ordering change follows MSan. It is possible not to change
2659   // ordering because we always set and use 0 shadows.
2660   I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
2661 }
2662 
2663 void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
2664   visitInstOperands(UO);
2665 }
2666 
2667 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
2668   visitInstOperands(BO);
2669 }
2670 
2671 void DFSanVisitor::visitCastInst(CastInst &CI) { visitInstOperands(CI); }
2672 
2673 void DFSanVisitor::visitCmpInst(CmpInst &CI) {
2674   visitInstOperands(CI);
2675   if (ClEventCallbacks) {
2676     IRBuilder<> IRB(&CI);
2677     Value *CombinedShadow = DFSF.getShadow(&CI);
2678     IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow);
2679   }
2680 }
2681 
2682 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2683   visitInstOperands(GEPI);
2684 }
2685 
2686 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
2687   visitInstOperands(I);
2688 }
2689 
2690 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
2691   visitInstOperands(I);
2692 }
2693 
2694 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
2695   visitInstOperands(I);
2696 }
2697 
2698 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
2699   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2700     visitInstOperands(I);
2701     return;
2702   }
2703 
2704   IRBuilder<> IRB(&I);
2705   Value *Agg = I.getAggregateOperand();
2706   Value *AggShadow = DFSF.getShadow(Agg);
2707   Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2708   DFSF.setShadow(&I, ResShadow);
2709   visitInstOperandOrigins(I);
2710 }
2711 
2712 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
2713   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2714     visitInstOperands(I);
2715     return;
2716   }
2717 
2718   IRBuilder<> IRB(&I);
2719   Value *AggShadow = DFSF.getShadow(I.getAggregateOperand());
2720   Value *InsShadow = DFSF.getShadow(I.getInsertedValueOperand());
2721   Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2722   DFSF.setShadow(&I, Res);
2723   visitInstOperandOrigins(I);
2724 }
2725 
2726 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
2727   bool AllLoadsStores = true;
2728   for (User *U : I.users()) {
2729     if (isa<LoadInst>(U))
2730       continue;
2731 
2732     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2733       if (SI->getPointerOperand() == &I)
2734         continue;
2735     }
2736 
2737     AllLoadsStores = false;
2738     break;
2739   }
2740   if (AllLoadsStores) {
2741     IRBuilder<> IRB(&I);
2742     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.PrimitiveShadowTy);
2743     if (DFSF.DFS.shouldTrackOrigins()) {
2744       DFSF.AllocaOriginMap[&I] =
2745           IRB.CreateAlloca(DFSF.DFS.OriginTy, nullptr, "_dfsa");
2746     }
2747   }
2748   DFSF.setShadow(&I, DFSF.DFS.ZeroPrimitiveShadow);
2749   DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin);
2750 }
2751 
2752 void DFSanVisitor::visitSelectInst(SelectInst &I) {
2753   Value *CondShadow = DFSF.getShadow(I.getCondition());
2754   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
2755   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
2756   Value *ShadowSel = nullptr;
2757   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2758   std::vector<Value *> Shadows;
2759   std::vector<Value *> Origins;
2760   Value *TrueOrigin =
2761       ShouldTrackOrigins ? DFSF.getOrigin(I.getTrueValue()) : nullptr;
2762   Value *FalseOrigin =
2763       ShouldTrackOrigins ? DFSF.getOrigin(I.getFalseValue()) : nullptr;
2764 
2765   if (isa<VectorType>(I.getCondition()->getType())) {
2766     ShadowSel = DFSF.combineShadowsThenConvert(I.getType(), TrueShadow,
2767                                                FalseShadow, &I);
2768     if (ShouldTrackOrigins) {
2769       Shadows.push_back(TrueShadow);
2770       Shadows.push_back(FalseShadow);
2771       Origins.push_back(TrueOrigin);
2772       Origins.push_back(FalseOrigin);
2773     }
2774   } else {
2775     if (TrueShadow == FalseShadow) {
2776       ShadowSel = TrueShadow;
2777       if (ShouldTrackOrigins) {
2778         Shadows.push_back(TrueShadow);
2779         Origins.push_back(TrueOrigin);
2780       }
2781     } else {
2782       ShadowSel =
2783           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
2784       if (ShouldTrackOrigins) {
2785         Shadows.push_back(ShadowSel);
2786         Origins.push_back(SelectInst::Create(I.getCondition(), TrueOrigin,
2787                                              FalseOrigin, "", &I));
2788       }
2789     }
2790   }
2791   DFSF.setShadow(&I, ClTrackSelectControlFlow
2792                          ? DFSF.combineShadowsThenConvert(
2793                                I.getType(), CondShadow, ShadowSel, &I)
2794                          : ShadowSel);
2795   if (ShouldTrackOrigins) {
2796     if (ClTrackSelectControlFlow) {
2797       Shadows.push_back(CondShadow);
2798       Origins.push_back(DFSF.getOrigin(I.getCondition()));
2799     }
2800     DFSF.setOrigin(&I, DFSF.combineOrigins(Shadows, Origins, &I));
2801   }
2802 }
2803 
2804 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
2805   IRBuilder<> IRB(&I);
2806   Value *ValShadow = DFSF.getShadow(I.getValue());
2807   Value *ValOrigin = DFSF.DFS.shouldTrackOrigins()
2808                          ? DFSF.getOrigin(I.getValue())
2809                          : DFSF.DFS.ZeroOrigin;
2810   IRB.CreateCall(
2811       DFSF.DFS.DFSanSetLabelFn,
2812       {ValShadow, ValOrigin,
2813        IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
2814        IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2815 }
2816 
2817 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
2818   IRBuilder<> IRB(&I);
2819 
2820   // CopyOrMoveOrigin transfers origins by refering to their shadows. So we
2821   // need to move origins before moving shadows.
2822   if (DFSF.DFS.shouldTrackOrigins()) {
2823     IRB.CreateCall(
2824         DFSF.DFS.DFSanMemOriginTransferFn,
2825         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2826          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
2827          IRB.CreateIntCast(I.getArgOperand(2), DFSF.DFS.IntptrTy, false)});
2828   }
2829 
2830   Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
2831   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
2832   Value *LenShadow =
2833       IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(),
2834                                                     DFSF.DFS.ShadowWidthBytes));
2835   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
2836   Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr);
2837   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
2838   auto *MTI = cast<MemTransferInst>(
2839       IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
2840                      {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
2841   if (ClPreserveAlignment) {
2842     MTI->setDestAlignment(I.getDestAlign() * DFSF.DFS.ShadowWidthBytes);
2843     MTI->setSourceAlignment(I.getSourceAlign() * DFSF.DFS.ShadowWidthBytes);
2844   } else {
2845     MTI->setDestAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2846     MTI->setSourceAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2847   }
2848   if (ClEventCallbacks) {
2849     IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn,
2850                    {RawDestShadow, I.getLength()});
2851   }
2852 }
2853 
2854 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
2855   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
2856     switch (DFSF.IA) {
2857     case DataFlowSanitizer::IA_TLS: {
2858       Value *S = DFSF.getShadow(RI.getReturnValue());
2859       IRBuilder<> IRB(&RI);
2860       Type *RT = DFSF.F->getFunctionType()->getReturnType();
2861       unsigned Size =
2862           getDataLayout().getTypeAllocSize(DFSF.DFS.getShadowTy(RT));
2863       if (Size <= RetvalTLSSize) {
2864         // If the size overflows, stores nothing. At callsite, oversized return
2865         // shadows are set to zero.
2866         IRB.CreateAlignedStore(S, DFSF.getRetvalTLS(RT, IRB),
2867                                ShadowTLSAlignment);
2868       }
2869       if (DFSF.DFS.shouldTrackOrigins()) {
2870         Value *O = DFSF.getOrigin(RI.getReturnValue());
2871         IRB.CreateStore(O, DFSF.getRetvalOriginTLS());
2872       }
2873       break;
2874     }
2875     case DataFlowSanitizer::IA_Args: {
2876       IRBuilder<> IRB(&RI);
2877       Type *RT = DFSF.F->getFunctionType()->getReturnType();
2878       Value *InsVal =
2879           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
2880       Value *InsShadow =
2881           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
2882       RI.setOperand(0, InsShadow);
2883       break;
2884     }
2885     }
2886   }
2887 }
2888 
2889 void DFSanVisitor::addShadowArguments(Function &F, CallBase &CB,
2890                                       std::vector<Value *> &Args,
2891                                       IRBuilder<> &IRB) {
2892   FunctionType *FT = F.getFunctionType();
2893 
2894   auto *I = CB.arg_begin();
2895 
2896   // Adds non-variable argument shadows.
2897   for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2898     Args.push_back(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB));
2899 
2900   // Adds variable argument shadows.
2901   if (FT->isVarArg()) {
2902     auto *LabelVATy = ArrayType::get(DFSF.DFS.PrimitiveShadowTy,
2903                                      CB.arg_size() - FT->getNumParams());
2904     auto *LabelVAAlloca =
2905         new AllocaInst(LabelVATy, getDataLayout().getAllocaAddrSpace(),
2906                        "labelva", &DFSF.F->getEntryBlock().front());
2907 
2908     for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2909       auto *LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, N);
2910       IRB.CreateStore(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB),
2911                       LabelVAPtr);
2912     }
2913 
2914     Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
2915   }
2916 
2917   // Adds the return value shadow.
2918   if (!FT->getReturnType()->isVoidTy()) {
2919     if (!DFSF.LabelReturnAlloca) {
2920       DFSF.LabelReturnAlloca = new AllocaInst(
2921           DFSF.DFS.PrimitiveShadowTy, getDataLayout().getAllocaAddrSpace(),
2922           "labelreturn", &DFSF.F->getEntryBlock().front());
2923     }
2924     Args.push_back(DFSF.LabelReturnAlloca);
2925   }
2926 }
2927 
2928 void DFSanVisitor::addOriginArguments(Function &F, CallBase &CB,
2929                                       std::vector<Value *> &Args,
2930                                       IRBuilder<> &IRB) {
2931   FunctionType *FT = F.getFunctionType();
2932 
2933   auto *I = CB.arg_begin();
2934 
2935   // Add non-variable argument origins.
2936   for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2937     Args.push_back(DFSF.getOrigin(*I));
2938 
2939   // Add variable argument origins.
2940   if (FT->isVarArg()) {
2941     auto *OriginVATy =
2942         ArrayType::get(DFSF.DFS.OriginTy, CB.arg_size() - FT->getNumParams());
2943     auto *OriginVAAlloca =
2944         new AllocaInst(OriginVATy, getDataLayout().getAllocaAddrSpace(),
2945                        "originva", &DFSF.F->getEntryBlock().front());
2946 
2947     for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2948       auto *OriginVAPtr = IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, N);
2949       IRB.CreateStore(DFSF.getOrigin(*I), OriginVAPtr);
2950     }
2951 
2952     Args.push_back(IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, 0));
2953   }
2954 
2955   // Add the return value origin.
2956   if (!FT->getReturnType()->isVoidTy()) {
2957     if (!DFSF.OriginReturnAlloca) {
2958       DFSF.OriginReturnAlloca = new AllocaInst(
2959           DFSF.DFS.OriginTy, getDataLayout().getAllocaAddrSpace(),
2960           "originreturn", &DFSF.F->getEntryBlock().front());
2961     }
2962     Args.push_back(DFSF.OriginReturnAlloca);
2963   }
2964 }
2965 
2966 bool DFSanVisitor::visitWrappedCallBase(Function &F, CallBase &CB) {
2967   IRBuilder<> IRB(&CB);
2968   switch (DFSF.DFS.getWrapperKind(&F)) {
2969   case DataFlowSanitizer::WK_Warning:
2970     CB.setCalledFunction(&F);
2971     IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
2972                    IRB.CreateGlobalStringPtr(F.getName()));
2973     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2974     DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin);
2975     return true;
2976   case DataFlowSanitizer::WK_Discard:
2977     CB.setCalledFunction(&F);
2978     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2979     DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin);
2980     return true;
2981   case DataFlowSanitizer::WK_Functional:
2982     CB.setCalledFunction(&F);
2983     visitInstOperands(CB);
2984     return true;
2985   case DataFlowSanitizer::WK_Custom:
2986     // Don't try to handle invokes of custom functions, it's too complicated.
2987     // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
2988     // wrapper.
2989     CallInst *CI = dyn_cast<CallInst>(&CB);
2990     if (!CI)
2991       return false;
2992 
2993     const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2994     FunctionType *FT = F.getFunctionType();
2995     TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
2996     std::string CustomFName = ShouldTrackOrigins ? "__dfso_" : "__dfsw_";
2997     CustomFName += F.getName();
2998     FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
2999         CustomFName, CustomFn.TransformedType);
3000     if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
3001       CustomFn->copyAttributesFrom(&F);
3002 
3003       // Custom functions returning non-void will write to the return label.
3004       if (!FT->getReturnType()->isVoidTy()) {
3005         CustomFn->removeAttributes(AttributeList::FunctionIndex,
3006                                    DFSF.DFS.ReadOnlyNoneAttrs);
3007       }
3008     }
3009 
3010     std::vector<Value *> Args;
3011 
3012     // Adds non-variable arguments.
3013     auto *I = CB.arg_begin();
3014     for (unsigned N = FT->getNumParams(); N != 0; ++I, --N) {
3015       Type *T = (*I)->getType();
3016       FunctionType *ParamFT;
3017       if (isa<PointerType>(T) &&
3018           (ParamFT = dyn_cast<FunctionType>(T->getPointerElementType()))) {
3019         std::string TName = "dfst";
3020         TName += utostr(FT->getNumParams() - N);
3021         TName += "$";
3022         TName += F.getName();
3023         Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
3024         Args.push_back(T);
3025         Args.push_back(
3026             IRB.CreateBitCast(*I, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
3027       } else {
3028         Args.push_back(*I);
3029       }
3030     }
3031 
3032     // Adds shadow arguments.
3033     const unsigned ShadowArgStart = Args.size();
3034     addShadowArguments(F, CB, Args, IRB);
3035 
3036     // Adds origin arguments.
3037     const unsigned OriginArgStart = Args.size();
3038     if (ShouldTrackOrigins)
3039       addOriginArguments(F, CB, Args, IRB);
3040 
3041     // Adds variable arguments.
3042     append_range(Args, drop_begin(CB.args(), FT->getNumParams()));
3043 
3044     CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
3045     CustomCI->setCallingConv(CI->getCallingConv());
3046     CustomCI->setAttributes(transformFunctionAttributes(
3047         CustomFn, CI->getContext(), CI->getAttributes()));
3048 
3049     // Update the parameter attributes of the custom call instruction to
3050     // zero extend the shadow parameters. This is required for targets
3051     // which consider PrimitiveShadowTy an illegal type.
3052     for (unsigned N = 0; N < FT->getNumParams(); N++) {
3053       const unsigned ArgNo = ShadowArgStart + N;
3054       if (CustomCI->getArgOperand(ArgNo)->getType() ==
3055           DFSF.DFS.PrimitiveShadowTy)
3056         CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
3057       if (ShouldTrackOrigins) {
3058         const unsigned OriginArgNo = OriginArgStart + N;
3059         if (CustomCI->getArgOperand(OriginArgNo)->getType() ==
3060             DFSF.DFS.OriginTy)
3061           CustomCI->addParamAttr(OriginArgNo, Attribute::ZExt);
3062       }
3063     }
3064 
3065     // Loads the return value shadow and origin.
3066     if (!FT->getReturnType()->isVoidTy()) {
3067       LoadInst *LabelLoad =
3068           IRB.CreateLoad(DFSF.DFS.PrimitiveShadowTy, DFSF.LabelReturnAlloca);
3069       DFSF.setShadow(CustomCI, DFSF.expandFromPrimitiveShadow(
3070                                    FT->getReturnType(), LabelLoad, &CB));
3071       if (ShouldTrackOrigins) {
3072         LoadInst *OriginLoad =
3073             IRB.CreateLoad(DFSF.DFS.OriginTy, DFSF.OriginReturnAlloca);
3074         DFSF.setOrigin(CustomCI, OriginLoad);
3075       }
3076     }
3077 
3078     CI->replaceAllUsesWith(CustomCI);
3079     CI->eraseFromParent();
3080     return true;
3081   }
3082   return false;
3083 }
3084 
3085 void DFSanVisitor::visitCallBase(CallBase &CB) {
3086   Function *F = CB.getCalledFunction();
3087   if ((F && F->isIntrinsic()) || CB.isInlineAsm()) {
3088     visitInstOperands(CB);
3089     return;
3090   }
3091 
3092   // Calls to this function are synthesized in wrappers, and we shouldn't
3093   // instrument them.
3094   if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
3095     return;
3096 
3097   DenseMap<Value *, Function *>::iterator UnwrappedFnIt =
3098       DFSF.DFS.UnwrappedFnMap.find(CB.getCalledOperand());
3099   if (UnwrappedFnIt != DFSF.DFS.UnwrappedFnMap.end())
3100     if (visitWrappedCallBase(*UnwrappedFnIt->second, CB))
3101       return;
3102 
3103   IRBuilder<> IRB(&CB);
3104 
3105   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
3106   FunctionType *FT = CB.getFunctionType();
3107   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
3108     // Stores argument shadows.
3109     unsigned ArgOffset = 0;
3110     const DataLayout &DL = getDataLayout();
3111     for (unsigned I = 0, N = FT->getNumParams(); I != N; ++I) {
3112       if (ShouldTrackOrigins) {
3113         // Ignore overflowed origins
3114         Value *ArgShadow = DFSF.getShadow(CB.getArgOperand(I));
3115         if (I < DFSF.DFS.NumOfElementsInArgOrgTLS &&
3116             !DFSF.DFS.isZeroShadow(ArgShadow))
3117           IRB.CreateStore(DFSF.getOrigin(CB.getArgOperand(I)),
3118                           DFSF.getArgOriginTLS(I, IRB));
3119       }
3120 
3121       unsigned Size =
3122           DL.getTypeAllocSize(DFSF.DFS.getShadowTy(FT->getParamType(I)));
3123       // Stop storing if arguments' size overflows. Inside a function, arguments
3124       // after overflow have zero shadow values.
3125       if (ArgOffset + Size > ArgTLSSize)
3126         break;
3127       IRB.CreateAlignedStore(
3128           DFSF.getShadow(CB.getArgOperand(I)),
3129           DFSF.getArgTLS(FT->getParamType(I), ArgOffset, IRB),
3130           ShadowTLSAlignment);
3131       ArgOffset += alignTo(Size, ShadowTLSAlignment);
3132     }
3133   }
3134 
3135   Instruction *Next = nullptr;
3136   if (!CB.getType()->isVoidTy()) {
3137     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
3138       if (II->getNormalDest()->getSinglePredecessor()) {
3139         Next = &II->getNormalDest()->front();
3140       } else {
3141         BasicBlock *NewBB =
3142             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
3143         Next = &NewBB->front();
3144       }
3145     } else {
3146       assert(CB.getIterator() != CB.getParent()->end());
3147       Next = CB.getNextNode();
3148     }
3149 
3150     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
3151       // Loads the return value shadow.
3152       IRBuilder<> NextIRB(Next);
3153       const DataLayout &DL = getDataLayout();
3154       unsigned Size = DL.getTypeAllocSize(DFSF.DFS.getShadowTy(&CB));
3155       if (Size > RetvalTLSSize) {
3156         // Set overflowed return shadow to be zero.
3157         DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
3158       } else {
3159         LoadInst *LI = NextIRB.CreateAlignedLoad(
3160             DFSF.DFS.getShadowTy(&CB), DFSF.getRetvalTLS(CB.getType(), NextIRB),
3161             ShadowTLSAlignment, "_dfsret");
3162         DFSF.SkipInsts.insert(LI);
3163         DFSF.setShadow(&CB, LI);
3164         DFSF.NonZeroChecks.push_back(LI);
3165       }
3166 
3167       if (ShouldTrackOrigins) {
3168         LoadInst *LI = NextIRB.CreateLoad(
3169             DFSF.DFS.OriginTy, DFSF.getRetvalOriginTLS(), "_dfsret_o");
3170         DFSF.SkipInsts.insert(LI);
3171         DFSF.setOrigin(&CB, LI);
3172       }
3173     }
3174   }
3175 
3176   // Do all instrumentation for IA_Args down here to defer tampering with the
3177   // CFG in a way that SplitEdge may be able to detect.
3178   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
3179     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
3180     Value *Func =
3181         IRB.CreateBitCast(CB.getCalledOperand(), PointerType::getUnqual(NewFT));
3182 
3183     const unsigned NumParams = FT->getNumParams();
3184 
3185     // Copy original arguments.
3186     auto *ArgIt = CB.arg_begin(), *ArgEnd = CB.arg_end();
3187     std::vector<Value *> Args(NumParams);
3188     std::copy_n(ArgIt, NumParams, Args.begin());
3189 
3190     // Add shadow arguments by transforming original arguments.
3191     std::generate_n(std::back_inserter(Args), NumParams,
3192                     [&]() { return DFSF.getShadow(*ArgIt++); });
3193 
3194     if (FT->isVarArg()) {
3195       unsigned VarArgSize = CB.arg_size() - NumParams;
3196       ArrayType *VarArgArrayTy =
3197           ArrayType::get(DFSF.DFS.PrimitiveShadowTy, VarArgSize);
3198       AllocaInst *VarArgShadow =
3199           new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
3200                          "", &DFSF.F->getEntryBlock().front());
3201       Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
3202 
3203       // Copy remaining var args.
3204       unsigned GepIndex = 0;
3205       std::for_each(ArgIt, ArgEnd, [&](Value *Arg) {
3206         IRB.CreateStore(
3207             DFSF.getShadow(Arg),
3208             IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, GepIndex++));
3209         Args.push_back(Arg);
3210       });
3211     }
3212 
3213     CallBase *NewCB;
3214     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
3215       NewCB = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
3216                                II->getUnwindDest(), Args);
3217     } else {
3218       NewCB = IRB.CreateCall(NewFT, Func, Args);
3219     }
3220     NewCB->setCallingConv(CB.getCallingConv());
3221     NewCB->setAttributes(CB.getAttributes().removeAttributes(
3222         *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
3223         AttributeFuncs::typeIncompatible(NewCB->getType())));
3224 
3225     if (Next) {
3226       ExtractValueInst *ExVal = ExtractValueInst::Create(NewCB, 0, "", Next);
3227       DFSF.SkipInsts.insert(ExVal);
3228       ExtractValueInst *ExShadow = ExtractValueInst::Create(NewCB, 1, "", Next);
3229       DFSF.SkipInsts.insert(ExShadow);
3230       DFSF.setShadow(ExVal, ExShadow);
3231       DFSF.NonZeroChecks.push_back(ExShadow);
3232 
3233       CB.replaceAllUsesWith(ExVal);
3234     }
3235 
3236     CB.eraseFromParent();
3237   }
3238 }
3239 
3240 void DFSanVisitor::visitPHINode(PHINode &PN) {
3241   Type *ShadowTy = DFSF.DFS.getShadowTy(&PN);
3242   PHINode *ShadowPN =
3243       PHINode::Create(ShadowTy, PN.getNumIncomingValues(), "", &PN);
3244 
3245   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
3246   Value *UndefShadow = UndefValue::get(ShadowTy);
3247   for (BasicBlock *BB : PN.blocks())
3248     ShadowPN->addIncoming(UndefShadow, BB);
3249 
3250   DFSF.setShadow(&PN, ShadowPN);
3251 
3252   PHINode *OriginPN = nullptr;
3253   if (DFSF.DFS.shouldTrackOrigins()) {
3254     OriginPN =
3255         PHINode::Create(DFSF.DFS.OriginTy, PN.getNumIncomingValues(), "", &PN);
3256     Value *UndefOrigin = UndefValue::get(DFSF.DFS.OriginTy);
3257     for (BasicBlock *BB : PN.blocks())
3258       OriginPN->addIncoming(UndefOrigin, BB);
3259     DFSF.setOrigin(&PN, OriginPN);
3260   }
3261 
3262   DFSF.PHIFixups.push_back({&PN, ShadowPN, OriginPN});
3263 }
3264 
3265 namespace {
3266 class DataFlowSanitizerLegacyPass : public ModulePass {
3267 private:
3268   std::vector<std::string> ABIListFiles;
3269 
3270 public:
3271   static char ID;
3272 
3273   DataFlowSanitizerLegacyPass(
3274       const std::vector<std::string> &ABIListFiles = std::vector<std::string>())
3275       : ModulePass(ID), ABIListFiles(ABIListFiles) {}
3276 
3277   bool runOnModule(Module &M) override {
3278     return DataFlowSanitizer(ABIListFiles).runImpl(M);
3279   }
3280 };
3281 } // namespace
3282 
3283 char DataFlowSanitizerLegacyPass::ID;
3284 
3285 INITIALIZE_PASS(DataFlowSanitizerLegacyPass, "dfsan",
3286                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
3287 
3288 ModulePass *llvm::createDataFlowSanitizerLegacyPassPass(
3289     const std::vector<std::string> &ABIListFiles) {
3290   return new DataFlowSanitizerLegacyPass(ABIListFiles);
3291 }
3292 
3293 PreservedAnalyses DataFlowSanitizerPass::run(Module &M,
3294                                              ModuleAnalysisManager &AM) {
3295   if (DataFlowSanitizer(ABIListFiles).runImpl(M)) {
3296     return PreservedAnalyses::none();
3297   }
3298   return PreservedAnalyses::all();
3299 }
3300