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