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