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