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