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.  Each
20 /// byte of application memory is backed by two bytes of shadow memory which
21 /// hold the label.  On Linux/x86_64, memory is laid out as follows:
22 ///
23 /// +--------------------+ 0x800000000000 (top of memory)
24 /// | application memory |
25 /// +--------------------+ 0x700000008000 (kAppAddr)
26 /// |                    |
27 /// |       unused       |
28 /// |                    |
29 /// +--------------------+ 0x300200000000 (kUnusedAddr)
30 /// |    union table     |
31 /// +--------------------+ 0x300000000000 (kUnionTableAddr)
32 /// |       origin       |
33 /// +--------------------+ 0x200000008000 (kOriginAddr)
34 /// |   shadow memory    |
35 /// +--------------------+ 0x000000010000 (kShadowAddr)
36 /// | reserved by kernel |
37 /// +--------------------+ 0x000000000000
38 ///
39 /// To derive a shadow memory address from an application memory address,
40 /// bits 44-46 are cleared to bring the address into the range
41 /// [0x000000008000,0x100000000000).  Then the address is shifted left by 1 to
42 /// account for the double byte representation of shadow labels and move the
43 /// address into the shadow memory range.  See the function
44 /// DataFlowSanitizer::getShadowAddress below.
45 ///
46 /// For more information, please refer to the design document:
47 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
48 //
49 //===----------------------------------------------------------------------===//
50 
51 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
52 #include "llvm/ADT/DenseMap.h"
53 #include "llvm/ADT/DenseSet.h"
54 #include "llvm/ADT/DepthFirstIterator.h"
55 #include "llvm/ADT/None.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/Triple.h"
61 #include "llvm/Analysis/ValueTracking.h"
62 #include "llvm/IR/Argument.h"
63 #include "llvm/IR/Attributes.h"
64 #include "llvm/IR/BasicBlock.h"
65 #include "llvm/IR/Constant.h"
66 #include "llvm/IR/Constants.h"
67 #include "llvm/IR/DataLayout.h"
68 #include "llvm/IR/DerivedTypes.h"
69 #include "llvm/IR/Dominators.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/GlobalAlias.h"
72 #include "llvm/IR/GlobalValue.h"
73 #include "llvm/IR/GlobalVariable.h"
74 #include "llvm/IR/IRBuilder.h"
75 #include "llvm/IR/InlineAsm.h"
76 #include "llvm/IR/InstVisitor.h"
77 #include "llvm/IR/InstrTypes.h"
78 #include "llvm/IR/Instruction.h"
79 #include "llvm/IR/Instructions.h"
80 #include "llvm/IR/IntrinsicInst.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/MDBuilder.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/PassManager.h"
85 #include "llvm/IR/Type.h"
86 #include "llvm/IR/User.h"
87 #include "llvm/IR/Value.h"
88 #include "llvm/InitializePasses.h"
89 #include "llvm/Pass.h"
90 #include "llvm/Support/Casting.h"
91 #include "llvm/Support/CommandLine.h"
92 #include "llvm/Support/ErrorHandling.h"
93 #include "llvm/Support/SpecialCaseList.h"
94 #include "llvm/Support/VirtualFileSystem.h"
95 #include "llvm/Transforms/Instrumentation.h"
96 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
97 #include "llvm/Transforms/Utils/Local.h"
98 #include <algorithm>
99 #include <cassert>
100 #include <cstddef>
101 #include <cstdint>
102 #include <iterator>
103 #include <memory>
104 #include <set>
105 #include <string>
106 #include <utility>
107 #include <vector>
108 
109 using namespace llvm;
110 
111 // This must be consistent with ShadowWidthBits.
112 static const Align kShadowTLSAlignment = Align(2);
113 
114 static const Align kMinOriginAlignment = Align(4);
115 
116 // The size of TLS variables. These constants must be kept in sync with the ones
117 // in dfsan.cpp.
118 static const unsigned kArgTLSSize = 800;
119 static const unsigned kRetvalTLSSize = 800;
120 
121 // External symbol to be used when generating the shadow address for
122 // architectures with multiple VMAs. Instead of using a constant integer
123 // the runtime will set the external mask based on the VMA range.
124 const char kDFSanExternShadowPtrMask[] = "__dfsan_shadow_ptr_mask";
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> ClArgsABI(
152     "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 static cl::opt<bool> ClDebugNonzeroLabels(
173     "dfsan-debug-nonzero-labels",
174     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
175              "load or return with a nonzero label"),
176     cl::Hidden);
177 
178 // Experimental feature that inserts callbacks for certain data events.
179 // Currently callbacks are only inserted for loads, stores, memory transfers
180 // (i.e. memcpy and memmove), and comparisons.
181 //
182 // If this flag is set to true, the user must provide definitions for the
183 // following callback functions:
184 //   void __dfsan_load_callback(dfsan_label Label, void* addr);
185 //   void __dfsan_store_callback(dfsan_label Label, void* addr);
186 //   void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
187 //   void __dfsan_cmp_callback(dfsan_label CombinedLabel);
188 static cl::opt<bool> ClEventCallbacks(
189     "dfsan-event-callbacks",
190     cl::desc("Insert calls to __dfsan_*_callback functions on data events."),
191     cl::Hidden, cl::init(false));
192 
193 // Use a distinct bit for each base label, enabling faster unions with less
194 // instrumentation.  Limits the max number of base labels to 16.
195 static cl::opt<bool> ClFast16Labels(
196     "dfsan-fast-16-labels",
197     cl::desc("Use more efficient instrumentation, limiting the number of "
198              "labels to 16."),
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 // Controls how to track origins.
209 // * 0: do not track origins.
210 // * 1: track origins at memory store operations.
211 // * 2: TODO: track origins at memory store operations and callsites.
212 static cl::opt<int> ClTrackOrigins("dfsan-track-origins",
213                                    cl::desc("Track origins of labels"),
214                                    cl::Hidden, cl::init(0));
215 
216 static StringRef GetGlobalTypeString(const GlobalValue &G) {
217   // Types of GlobalVariables are always pointer types.
218   Type *GType = G.getValueType();
219   // For now we support excluding struct types only.
220   if (StructType *SGType = dyn_cast<StructType>(GType)) {
221     if (!SGType->isLiteral())
222       return SGType->getName();
223   }
224   return "<unknown type>";
225 }
226 
227 namespace {
228 
229 class DFSanABIList {
230   std::unique_ptr<SpecialCaseList> SCL;
231 
232  public:
233   DFSanABIList() = default;
234 
235   void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
236 
237   /// Returns whether either this function or its source file are listed in the
238   /// given category.
239   bool isIn(const Function &F, StringRef Category) const {
240     return isIn(*F.getParent(), Category) ||
241            SCL->inSection("dataflow", "fun", F.getName(), Category);
242   }
243 
244   /// Returns whether this global alias is listed in the given category.
245   ///
246   /// If GA aliases a function, the alias's name is matched as a function name
247   /// would be.  Similarly, aliases of globals are matched like globals.
248   bool isIn(const GlobalAlias &GA, StringRef Category) const {
249     if (isIn(*GA.getParent(), Category))
250       return true;
251 
252     if (isa<FunctionType>(GA.getValueType()))
253       return SCL->inSection("dataflow", "fun", GA.getName(), Category);
254 
255     return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
256            SCL->inSection("dataflow", "type", GetGlobalTypeString(GA),
257                           Category);
258   }
259 
260   /// Returns whether this module is listed in the given category.
261   bool isIn(const Module &M, StringRef Category) const {
262     return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
263   }
264 };
265 
266 /// TransformedFunction is used to express the result of transforming one
267 /// function type into another.  This struct is immutable.  It holds metadata
268 /// useful for updating calls of the old function to the new type.
269 struct TransformedFunction {
270   TransformedFunction(FunctionType* OriginalType,
271                       FunctionType* TransformedType,
272                       std::vector<unsigned> ArgumentIndexMapping)
273       : OriginalType(OriginalType),
274         TransformedType(TransformedType),
275         ArgumentIndexMapping(ArgumentIndexMapping) {}
276 
277   // Disallow copies.
278   TransformedFunction(const TransformedFunction&) = delete;
279   TransformedFunction& operator=(const TransformedFunction&) = delete;
280 
281   // Allow moves.
282   TransformedFunction(TransformedFunction&&) = default;
283   TransformedFunction& operator=(TransformedFunction&&) = default;
284 
285   /// Type of the function before the transformation.
286   FunctionType *OriginalType;
287 
288   /// Type of the function after the transformation.
289   FunctionType *TransformedType;
290 
291   /// Transforming a function may change the position of arguments.  This
292   /// member records the mapping from each argument's old position to its new
293   /// position.  Argument positions are zero-indexed.  If the transformation
294   /// from F to F' made the first argument of F into the third argument of F',
295   /// then ArgumentIndexMapping[0] will equal 2.
296   std::vector<unsigned> ArgumentIndexMapping;
297 };
298 
299 /// Given function attributes from a call site for the original function,
300 /// return function attributes appropriate for a call to the transformed
301 /// function.
302 AttributeList TransformFunctionAttributes(
303     const TransformedFunction& TransformedFunction,
304     LLVMContext& Ctx, AttributeList CallSiteAttrs) {
305 
306   // Construct a vector of AttributeSet for each function argument.
307   std::vector<llvm::AttributeSet> ArgumentAttributes(
308       TransformedFunction.TransformedType->getNumParams());
309 
310   // Copy attributes from the parameter of the original function to the
311   // transformed version.  'ArgumentIndexMapping' holds the mapping from
312   // old argument position to new.
313   for (unsigned i=0, ie = TransformedFunction.ArgumentIndexMapping.size();
314        i < ie; ++i) {
315     unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[i];
316     ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(i);
317   }
318 
319   // Copy annotations on varargs arguments.
320   for (unsigned i = TransformedFunction.OriginalType->getNumParams(),
321        ie = CallSiteAttrs.getNumAttrSets(); i<ie; ++i) {
322     ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(i));
323   }
324 
325   return AttributeList::get(
326       Ctx,
327       CallSiteAttrs.getFnAttributes(),
328       CallSiteAttrs.getRetAttributes(),
329       llvm::makeArrayRef(ArgumentAttributes));
330 }
331 
332 class DataFlowSanitizer {
333   friend struct DFSanFunction;
334   friend class DFSanVisitor;
335 
336   enum {
337     ShadowWidthBits = 16,
338     ShadowWidthBytes = ShadowWidthBits / 8,
339     OriginWidthBits = 32,
340     OriginWidthBytes = OriginWidthBits / 8
341   };
342 
343   /// Which ABI should be used for instrumented functions?
344   enum InstrumentedABI {
345     /// Argument and return value labels are passed through additional
346     /// arguments and by modifying the return type.
347     IA_Args,
348 
349     /// Argument and return value labels are passed through TLS variables
350     /// __dfsan_arg_tls and __dfsan_retval_tls.
351     IA_TLS
352   };
353 
354   /// How should calls to uninstrumented functions be handled?
355   enum WrapperKind {
356     /// This function is present in an uninstrumented form but we don't know
357     /// how it should be handled.  Print a warning and call the function anyway.
358     /// Don't label the return value.
359     WK_Warning,
360 
361     /// This function does not write to (user-accessible) memory, and its return
362     /// value is unlabelled.
363     WK_Discard,
364 
365     /// This function does not write to (user-accessible) memory, and the label
366     /// of its return value is the union of the label of its arguments.
367     WK_Functional,
368 
369     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
370     /// where F is the name of the function.  This function may wrap the
371     /// original function or provide its own implementation.  This is similar to
372     /// the IA_Args ABI, except that IA_Args uses a struct return type to
373     /// pass the return value shadow in a register, while WK_Custom uses an
374     /// extra pointer argument to return the shadow.  This allows the wrapped
375     /// form of the function type to be expressed in C.
376     WK_Custom
377   };
378 
379   Module *Mod;
380   LLVMContext *Ctx;
381   Type *Int8Ptr;
382   IntegerType *OriginTy;
383   PointerType *OriginPtrTy;
384   ConstantInt *OriginBase;
385   ConstantInt *ZeroOrigin;
386   /// The shadow type for all primitive types and vector types.
387   IntegerType *PrimitiveShadowTy;
388   PointerType *PrimitiveShadowPtrTy;
389   IntegerType *IntptrTy;
390   ConstantInt *ZeroPrimitiveShadow;
391   ConstantInt *ShadowPtrMask;
392   ConstantInt *ShadowPtrMul;
393   Constant *ArgTLS;
394   ArrayType *ArgOriginTLSTy;
395   Constant *ArgOriginTLS;
396   Constant *RetvalTLS;
397   Constant *RetvalOriginTLS;
398   Constant *ExternalShadowMask;
399   FunctionType *DFSanUnionFnTy;
400   FunctionType *DFSanUnionLoadFnTy;
401   FunctionType *DFSanLoadLabelAndOriginFnTy;
402   FunctionType *DFSanUnimplementedFnTy;
403   FunctionType *DFSanSetLabelFnTy;
404   FunctionType *DFSanNonzeroLabelFnTy;
405   FunctionType *DFSanVarargWrapperFnTy;
406   FunctionType *DFSanCmpCallbackFnTy;
407   FunctionType *DFSanLoadStoreCallbackFnTy;
408   FunctionType *DFSanMemTransferCallbackFnTy;
409   FunctionType *DFSanChainOriginFnTy;
410   FunctionType *DFSanMemOriginTransferFnTy;
411   FunctionType *DFSanMaybeStoreOriginFnTy;
412   FunctionCallee DFSanUnionFn;
413   FunctionCallee DFSanCheckedUnionFn;
414   FunctionCallee DFSanUnionLoadFn;
415   FunctionCallee DFSanUnionLoadFast16LabelsFn;
416   FunctionCallee DFSanLoadLabelAndOriginFn;
417   FunctionCallee DFSanUnimplementedFn;
418   FunctionCallee DFSanSetLabelFn;
419   FunctionCallee DFSanNonzeroLabelFn;
420   FunctionCallee DFSanVarargWrapperFn;
421   FunctionCallee DFSanLoadCallbackFn;
422   FunctionCallee DFSanStoreCallbackFn;
423   FunctionCallee DFSanMemTransferCallbackFn;
424   FunctionCallee DFSanCmpCallbackFn;
425   FunctionCallee DFSanChainOriginFn;
426   FunctionCallee DFSanMemOriginTransferFn;
427   FunctionCallee DFSanMaybeStoreOriginFn;
428   SmallPtrSet<Value *, 16> DFSanRuntimeFunctions;
429   MDNode *ColdCallWeights;
430   DFSanABIList ABIList;
431   DenseMap<Value *, Function *> UnwrappedFnMap;
432   AttrBuilder ReadOnlyNoneAttrs;
433   bool DFSanRuntimeShadowMask = false;
434 
435   Value *getShadowOffset(Value *Addr, IRBuilder<> &IRB);
436   Value *getShadowAddress(Value *Addr, Instruction *Pos);
437   // std::pair<Value *, Value *>
438   // getShadowOriginAddress(Value *Addr, Align InstAlignment, Instruction *Pos);
439   bool isInstrumented(const Function *F);
440   bool isInstrumented(const GlobalAlias *GA);
441   FunctionType *getArgsFunctionType(FunctionType *T);
442   FunctionType *getTrampolineFunctionType(FunctionType *T);
443   TransformedFunction getCustomFunctionType(FunctionType *T);
444   InstrumentedABI getInstrumentedABI();
445   WrapperKind getWrapperKind(Function *F);
446   void addGlobalNamePrefix(GlobalValue *GV);
447   Function *buildWrapperFunction(Function *F, StringRef NewFName,
448                                  GlobalValue::LinkageTypes NewFLink,
449                                  FunctionType *NewFT);
450   Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
451   void initializeCallbackFunctions(Module &M);
452   void initializeRuntimeFunctions(Module &M);
453 
454   bool init(Module &M);
455 
456   /// Returns whether the pass tracks origins. Support only fast16 mode in TLS
457   /// ABI mode.
458   bool shouldTrackOrigins();
459 
460   /// Returns whether the pass tracks labels for struct fields and array
461   /// indices. Support only fast16 mode in TLS ABI mode.
462   bool shouldTrackFieldsAndIndices();
463 
464   /// Returns a zero constant with the shadow type of OrigTy.
465   ///
466   /// getZeroShadow({T1,T2,...}) = {getZeroShadow(T1),getZeroShadow(T2,...}
467   /// getZeroShadow([n x T]) = [n x getZeroShadow(T)]
468   /// getZeroShadow(other type) = i16(0)
469   ///
470   /// Note that a zero shadow is always i16(0) when shouldTrackFieldsAndIndices
471   /// returns false.
472   Constant *getZeroShadow(Type *OrigTy);
473   /// Returns a zero constant with the shadow type of V's type.
474   Constant *getZeroShadow(Value *V);
475 
476   /// Checks if V is a zero shadow.
477   bool isZeroShadow(Value *V);
478 
479   /// Returns the shadow type of OrigTy.
480   ///
481   /// getShadowTy({T1,T2,...}) = {getShadowTy(T1),getShadowTy(T2),...}
482   /// getShadowTy([n x T]) = [n x getShadowTy(T)]
483   /// getShadowTy(other type) = i16
484   ///
485   /// Note that a shadow type is always i16 when shouldTrackFieldsAndIndices
486   /// returns false.
487   Type *getShadowTy(Type *OrigTy);
488   /// Returns the shadow type of of V's type.
489   Type *getShadowTy(Value *V);
490 
491   const uint64_t kNumOfElementsInArgOrgTLS = kArgTLSSize / OriginWidthBytes;
492 
493 public:
494   DataFlowSanitizer(const std::vector<std::string> &ABIListFiles);
495 
496   bool runImpl(Module &M);
497 };
498 
499 struct DFSanFunction {
500   DataFlowSanitizer &DFS;
501   Function *F;
502   DominatorTree DT;
503   DataFlowSanitizer::InstrumentedABI IA;
504   bool IsNativeABI;
505   AllocaInst *LabelReturnAlloca = nullptr;
506   DenseMap<Value *, Value *> ValShadowMap;
507   DenseMap<Value *, Value *> ValOriginMap;
508   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
509   std::vector<std::pair<PHINode *, PHINode *>> PHIFixups;
510   DenseSet<Instruction *> SkipInsts;
511   std::vector<Value *> NonZeroChecks;
512   bool AvoidNewBlocks;
513 
514   struct CachedShadow {
515     BasicBlock *Block; // The block where Shadow is defined.
516     Value *Shadow;
517   };
518   /// Maps a value to its latest shadow value in terms of domination tree.
519   DenseMap<std::pair<Value *, Value *>, CachedShadow> CachedShadows;
520   /// Maps a value to its latest collapsed shadow value it was converted to in
521   /// terms of domination tree. When ClDebugNonzeroLabels is on, this cache is
522   /// used at a post process where CFG blocks are split. So it does not cache
523   /// BasicBlock like CachedShadows, but uses domination between values.
524   DenseMap<Value *, Value *> CachedCollapsedShadows;
525   DenseMap<Value *, std::set<Value *>> ShadowElements;
526 
527   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
528       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
529     DT.recalculate(*F);
530     // FIXME: Need to track down the register allocator issue which causes poor
531     // performance in pathological cases with large numbers of basic blocks.
532     AvoidNewBlocks = F->size() > 1000;
533   }
534 
535   /// Computes the shadow address for a given function argument.
536   ///
537   /// Shadow = ArgTLS+ArgOffset.
538   Value *getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB);
539 
540   /// Computes the shadow address for a return value.
541   Value *getRetvalTLS(Type *T, IRBuilder<> &IRB);
542 
543   /// Computes the origin address for a given function argument.
544   ///
545   /// Origin = ArgOriginTLS[ArgNo].
546   Value *getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB);
547 
548   /// Computes the origin address for a return value.
549   Value *getRetvalOriginTLS();
550 
551   Value *getOrigin(Value *V);
552   void setOrigin(Instruction *I, Value *Origin);
553   /// Generates IR to compute the origin of the last operand with a taint label.
554   Value *combineOperandOrigins(Instruction *Inst);
555   /// Before the instruction Pos, generates IR to compute the last origin with a
556   /// taint label. Labels and origins are from vectors Shadows and Origins
557   /// correspondingly. The generated IR is like
558   ///   Sn-1 != Zero ? On-1: ... S2 != Zero ? O2: S1 != Zero ? O1: O0
559   /// When Zero is nullptr, it uses ZeroPrimitiveShadow. Otherwise it can be
560   /// zeros with other bitwidths.
561   Value *combineOrigins(const std::vector<Value *> &Shadows,
562                         const std::vector<Value *> &Origins, Instruction *Pos,
563                         ConstantInt *Zero = nullptr);
564 
565   Value *getShadow(Value *V);
566   void setShadow(Instruction *I, Value *Shadow);
567   /// Generates IR to compute the union of the two given shadows, inserting it
568   /// before Pos. The combined value is with primitive type.
569   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
570   /// Combines the shadow values of V1 and V2, then converts the combined value
571   /// with primitive type into a shadow value with the original type T.
572   Value *combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
573                                    Instruction *Pos);
574   Value *combineOperandShadows(Instruction *Inst);
575   Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
576                     Instruction *Pos);
577   void storePrimitiveShadow(Value *Addr, uint64_t Size, Align Alignment,
578                             Value *PrimitiveShadow, Instruction *Pos);
579   /// Applies PrimitiveShadow to all primitive subtypes of T, returning
580   /// the expanded shadow value.
581   ///
582   /// EFP({T1,T2, ...}, PS) = {EFP(T1,PS),EFP(T2,PS),...}
583   /// EFP([n x T], PS) = [n x EFP(T,PS)]
584   /// EFP(other types, PS) = PS
585   Value *expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
586                                    Instruction *Pos);
587   /// Collapses Shadow into a single primitive shadow value, unioning all
588   /// primitive shadow values in the process. Returns the final primitive
589   /// shadow value.
590   ///
591   /// CTP({V1,V2, ...}) = UNION(CFP(V1,PS),CFP(V2,PS),...)
592   /// CTP([V1,V2,...]) = UNION(CFP(V1,PS),CFP(V2,PS),...)
593   /// CTP(other types, PS) = PS
594   Value *collapseToPrimitiveShadow(Value *Shadow, Instruction *Pos);
595 
596 private:
597   /// Collapses the shadow with aggregate type into a single primitive shadow
598   /// value.
599   template <class AggregateType>
600   Value *collapseAggregateShadow(AggregateType *AT, Value *Shadow,
601                                  IRBuilder<> &IRB);
602 
603   Value *collapseToPrimitiveShadow(Value *Shadow, IRBuilder<> &IRB);
604 
605   /// Returns the shadow value of an argument A.
606   Value *getShadowForTLSArgument(Argument *A);
607 
608   /// The fast path of loading shadow in legacy mode.
609   Value *loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size,
610                               Align ShadowAlign, Instruction *Pos);
611 
612   /// The fast path of loading shadow in fast-16-label mode.
613   Value *loadFast16ShadowFast(Value *ShadowAddr, uint64_t Size,
614                               Align ShadowAlign, Instruction *Pos);
615 };
616 
617 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
618 public:
619   DFSanFunction &DFSF;
620 
621   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
622 
623   const DataLayout &getDataLayout() const {
624     return DFSF.F->getParent()->getDataLayout();
625   }
626 
627   // Combines shadow values and origins for all of I's operands.
628   void visitInstOperands(Instruction &I);
629 
630   void visitUnaryOperator(UnaryOperator &UO);
631   void visitBinaryOperator(BinaryOperator &BO);
632   void visitCastInst(CastInst &CI);
633   void visitCmpInst(CmpInst &CI);
634   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
635   void visitLoadInst(LoadInst &LI);
636   void visitStoreInst(StoreInst &SI);
637   void visitReturnInst(ReturnInst &RI);
638   void visitCallBase(CallBase &CB);
639   void visitPHINode(PHINode &PN);
640   void visitExtractElementInst(ExtractElementInst &I);
641   void visitInsertElementInst(InsertElementInst &I);
642   void visitShuffleVectorInst(ShuffleVectorInst &I);
643   void visitExtractValueInst(ExtractValueInst &I);
644   void visitInsertValueInst(InsertValueInst &I);
645   void visitAllocaInst(AllocaInst &I);
646   void visitSelectInst(SelectInst &I);
647   void visitMemSetInst(MemSetInst &I);
648   void visitMemTransferInst(MemTransferInst &I);
649 
650 private:
651   // Returns false when this is an invoke of a custom function.
652   bool visitWrappedCallBase(Function &F, CallBase &CB);
653 
654   // Combines origins for all of I's operands.
655   void visitInstOperandOrigins(Instruction &I);
656 };
657 
658 } // end anonymous namespace
659 
660 DataFlowSanitizer::DataFlowSanitizer(
661     const std::vector<std::string> &ABIListFiles) {
662   std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
663   llvm::append_range(AllABIListFiles, ClABIListFiles);
664   // FIXME: should we propagate vfs::FileSystem to this constructor?
665   ABIList.set(
666       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
667 }
668 
669 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
670   SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
671   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
672   if (T->isVarArg())
673     ArgTypes.push_back(PrimitiveShadowPtrTy);
674   Type *RetType = T->getReturnType();
675   if (!RetType->isVoidTy())
676     RetType = StructType::get(RetType, PrimitiveShadowTy);
677   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
678 }
679 
680 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
681   assert(!T->isVarArg());
682   SmallVector<Type *, 4> ArgTypes;
683   ArgTypes.push_back(T->getPointerTo());
684   ArgTypes.append(T->param_begin(), T->param_end());
685   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
686   Type *RetType = T->getReturnType();
687   if (!RetType->isVoidTy())
688     ArgTypes.push_back(PrimitiveShadowPtrTy);
689   return FunctionType::get(T->getReturnType(), ArgTypes, false);
690 }
691 
692 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
693   SmallVector<Type *, 4> ArgTypes;
694 
695   // Some parameters of the custom function being constructed are
696   // parameters of T.  Record the mapping from parameters of T to
697   // parameters of the custom function, so that parameter attributes
698   // at call sites can be updated.
699   std::vector<unsigned> ArgumentIndexMapping;
700   for (unsigned i = 0, ie = T->getNumParams(); i != ie; ++i) {
701     Type* param_type = T->getParamType(i);
702     FunctionType *FT;
703     if (isa<PointerType>(param_type) && (FT = dyn_cast<FunctionType>(
704             cast<PointerType>(param_type)->getElementType()))) {
705       ArgumentIndexMapping.push_back(ArgTypes.size());
706       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
707       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
708     } else {
709       ArgumentIndexMapping.push_back(ArgTypes.size());
710       ArgTypes.push_back(param_type);
711     }
712   }
713   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
714     ArgTypes.push_back(PrimitiveShadowTy);
715   if (T->isVarArg())
716     ArgTypes.push_back(PrimitiveShadowPtrTy);
717   Type *RetType = T->getReturnType();
718   if (!RetType->isVoidTy())
719     ArgTypes.push_back(PrimitiveShadowPtrTy);
720   return TransformedFunction(
721       T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
722       ArgumentIndexMapping);
723 }
724 
725 bool DataFlowSanitizer::isZeroShadow(Value *V) {
726   if (!shouldTrackFieldsAndIndices())
727     return ZeroPrimitiveShadow == V;
728 
729   Type *T = V->getType();
730   if (!isa<ArrayType>(T) && !isa<StructType>(T)) {
731     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
732       return CI->isZero();
733     return false;
734   }
735 
736   return isa<ConstantAggregateZero>(V);
737 }
738 
739 bool DataFlowSanitizer::shouldTrackOrigins() {
740   return ClTrackOrigins && getInstrumentedABI() == DataFlowSanitizer::IA_TLS &&
741          ClFast16Labels;
742 }
743 
744 bool DataFlowSanitizer::shouldTrackFieldsAndIndices() {
745   return getInstrumentedABI() == DataFlowSanitizer::IA_TLS && ClFast16Labels;
746 }
747 
748 Constant *DataFlowSanitizer::getZeroShadow(Type *OrigTy) {
749   if (!shouldTrackFieldsAndIndices())
750     return ZeroPrimitiveShadow;
751 
752   if (!isa<ArrayType>(OrigTy) && !isa<StructType>(OrigTy))
753     return ZeroPrimitiveShadow;
754   Type *ShadowTy = getShadowTy(OrigTy);
755   return ConstantAggregateZero::get(ShadowTy);
756 }
757 
758 Constant *DataFlowSanitizer::getZeroShadow(Value *V) {
759   return getZeroShadow(V->getType());
760 }
761 
762 static Value *expandFromPrimitiveShadowRecursive(
763     Value *Shadow, SmallVector<unsigned, 4> &Indices, Type *SubShadowTy,
764     Value *PrimitiveShadow, IRBuilder<> &IRB) {
765   if (!isa<ArrayType>(SubShadowTy) && !isa<StructType>(SubShadowTy))
766     return IRB.CreateInsertValue(Shadow, PrimitiveShadow, Indices);
767 
768   if (ArrayType *AT = dyn_cast<ArrayType>(SubShadowTy)) {
769     for (unsigned Idx = 0; Idx < AT->getNumElements(); Idx++) {
770       Indices.push_back(Idx);
771       Shadow = expandFromPrimitiveShadowRecursive(
772           Shadow, Indices, AT->getElementType(), PrimitiveShadow, IRB);
773       Indices.pop_back();
774     }
775     return Shadow;
776   }
777 
778   if (StructType *ST = dyn_cast<StructType>(SubShadowTy)) {
779     for (unsigned Idx = 0; Idx < ST->getNumElements(); Idx++) {
780       Indices.push_back(Idx);
781       Shadow = expandFromPrimitiveShadowRecursive(
782           Shadow, Indices, ST->getElementType(Idx), PrimitiveShadow, IRB);
783       Indices.pop_back();
784     }
785     return Shadow;
786   }
787   llvm_unreachable("Unexpected shadow type");
788 }
789 
790 Value *DFSanFunction::expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
791                                                 Instruction *Pos) {
792   Type *ShadowTy = DFS.getShadowTy(T);
793 
794   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
795     return PrimitiveShadow;
796 
797   if (DFS.isZeroShadow(PrimitiveShadow))
798     return DFS.getZeroShadow(ShadowTy);
799 
800   IRBuilder<> IRB(Pos);
801   SmallVector<unsigned, 4> Indices;
802   Value *Shadow = UndefValue::get(ShadowTy);
803   Shadow = expandFromPrimitiveShadowRecursive(Shadow, Indices, ShadowTy,
804                                               PrimitiveShadow, IRB);
805 
806   // Caches the primitive shadow value that built the shadow value.
807   CachedCollapsedShadows[Shadow] = PrimitiveShadow;
808   return Shadow;
809 }
810 
811 template <class AggregateType>
812 Value *DFSanFunction::collapseAggregateShadow(AggregateType *AT, Value *Shadow,
813                                               IRBuilder<> &IRB) {
814   if (!AT->getNumElements())
815     return DFS.ZeroPrimitiveShadow;
816 
817   Value *FirstItem = IRB.CreateExtractValue(Shadow, 0);
818   Value *Aggregator = collapseToPrimitiveShadow(FirstItem, IRB);
819 
820   for (unsigned Idx = 1; Idx < AT->getNumElements(); Idx++) {
821     Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
822     Value *ShadowInner = collapseToPrimitiveShadow(ShadowItem, IRB);
823     Aggregator = IRB.CreateOr(Aggregator, ShadowInner);
824   }
825   return Aggregator;
826 }
827 
828 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
829                                                 IRBuilder<> &IRB) {
830   Type *ShadowTy = Shadow->getType();
831   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
832     return Shadow;
833   if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy))
834     return collapseAggregateShadow<>(AT, Shadow, IRB);
835   if (StructType *ST = dyn_cast<StructType>(ShadowTy))
836     return collapseAggregateShadow<>(ST, Shadow, IRB);
837   llvm_unreachable("Unexpected shadow type");
838 }
839 
840 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
841                                                 Instruction *Pos) {
842   Type *ShadowTy = Shadow->getType();
843   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
844     return Shadow;
845 
846   assert(DFS.shouldTrackFieldsAndIndices());
847 
848   // Checks if the cached collapsed shadow value dominates Pos.
849   Value *&CS = CachedCollapsedShadows[Shadow];
850   if (CS && DT.dominates(CS, Pos))
851     return CS;
852 
853   IRBuilder<> IRB(Pos);
854   Value *PrimitiveShadow = collapseToPrimitiveShadow(Shadow, IRB);
855   // Caches the converted primitive shadow value.
856   CS = PrimitiveShadow;
857   return PrimitiveShadow;
858 }
859 
860 Type *DataFlowSanitizer::getShadowTy(Type *OrigTy) {
861   if (!shouldTrackFieldsAndIndices())
862     return PrimitiveShadowTy;
863 
864   if (!OrigTy->isSized())
865     return PrimitiveShadowTy;
866   if (isa<IntegerType>(OrigTy))
867     return PrimitiveShadowTy;
868   if (isa<VectorType>(OrigTy))
869     return PrimitiveShadowTy;
870   if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy))
871     return ArrayType::get(getShadowTy(AT->getElementType()),
872                           AT->getNumElements());
873   if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
874     SmallVector<Type *, 4> Elements;
875     for (unsigned I = 0, N = ST->getNumElements(); I < N; ++I)
876       Elements.push_back(getShadowTy(ST->getElementType(I)));
877     return StructType::get(*Ctx, Elements);
878   }
879   return PrimitiveShadowTy;
880 }
881 
882 Type *DataFlowSanitizer::getShadowTy(Value *V) {
883   return getShadowTy(V->getType());
884 }
885 
886 bool DataFlowSanitizer::init(Module &M) {
887   Triple TargetTriple(M.getTargetTriple());
888   bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
889   bool IsMIPS64 = TargetTriple.isMIPS64();
890   bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||
891                    TargetTriple.getArch() == Triple::aarch64_be;
892 
893   const DataLayout &DL = M.getDataLayout();
894 
895   Mod = &M;
896   Ctx = &M.getContext();
897   Int8Ptr = Type::getInt8PtrTy(*Ctx);
898   OriginTy = IntegerType::get(*Ctx, OriginWidthBits);
899   OriginPtrTy = PointerType::getUnqual(OriginTy);
900   PrimitiveShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
901   PrimitiveShadowPtrTy = PointerType::getUnqual(PrimitiveShadowTy);
902   IntptrTy = DL.getIntPtrType(*Ctx);
903   ZeroPrimitiveShadow = ConstantInt::getSigned(PrimitiveShadowTy, 0);
904   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidthBytes);
905   OriginBase = ConstantInt::get(IntptrTy, 0x200000000000LL);
906   ZeroOrigin = ConstantInt::getSigned(OriginTy, 0);
907   if (IsX86_64)
908     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
909   else if (IsMIPS64)
910     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
911   // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
912   else if (IsAArch64)
913     DFSanRuntimeShadowMask = true;
914   else
915     report_fatal_error("unsupported triple");
916 
917   Type *DFSanUnionArgs[2] = {PrimitiveShadowTy, PrimitiveShadowTy};
918   DFSanUnionFnTy =
919       FunctionType::get(PrimitiveShadowTy, DFSanUnionArgs, /*isVarArg=*/false);
920   Type *DFSanUnionLoadArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
921   DFSanUnionLoadFnTy = FunctionType::get(PrimitiveShadowTy, DFSanUnionLoadArgs,
922                                          /*isVarArg=*/false);
923   Type *DFSanLoadLabelAndOriginArgs[2] = {Int8Ptr, IntptrTy};
924   DFSanLoadLabelAndOriginFnTy =
925       FunctionType::get(IntegerType::get(*Ctx, 64), DFSanLoadLabelAndOriginArgs,
926                         /*isVarArg=*/false);
927   DFSanUnimplementedFnTy = FunctionType::get(
928       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
929   Type *DFSanSetLabelArgs[4] = {PrimitiveShadowTy, OriginTy,
930                                 Type::getInt8PtrTy(*Ctx), IntptrTy};
931   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
932                                         DFSanSetLabelArgs, /*isVarArg=*/false);
933   DFSanNonzeroLabelFnTy =
934       FunctionType::get(Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
935   DFSanVarargWrapperFnTy = FunctionType::get(
936       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
937   DFSanCmpCallbackFnTy =
938       FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy,
939                         /*isVarArg=*/false);
940   DFSanChainOriginFnTy =
941       FunctionType::get(OriginTy, OriginTy, /*isVarArg=*/false);
942   Type *DFSanMaybeStoreOriginArgs[4] = {IntegerType::get(*Ctx, ShadowWidthBits),
943                                         Int8Ptr, IntptrTy, OriginTy};
944   DFSanMaybeStoreOriginFnTy = FunctionType::get(
945       Type::getVoidTy(*Ctx), DFSanMaybeStoreOriginArgs, /*isVarArg=*/false);
946   Type *DFSanMemOriginTransferArgs[3] = {Int8Ptr, Int8Ptr, IntptrTy};
947   DFSanMemOriginTransferFnTy = FunctionType::get(
948       Type::getVoidTy(*Ctx), DFSanMemOriginTransferArgs, /*isVarArg=*/false);
949   Type *DFSanLoadStoreCallbackArgs[2] = {PrimitiveShadowTy, Int8Ptr};
950   DFSanLoadStoreCallbackFnTy =
951       FunctionType::get(Type::getVoidTy(*Ctx), DFSanLoadStoreCallbackArgs,
952                         /*isVarArg=*/false);
953   Type *DFSanMemTransferCallbackArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
954   DFSanMemTransferCallbackFnTy =
955       FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs,
956                         /*isVarArg=*/false);
957 
958   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
959   return true;
960 }
961 
962 bool DataFlowSanitizer::isInstrumented(const Function *F) {
963   return !ABIList.isIn(*F, "uninstrumented");
964 }
965 
966 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
967   return !ABIList.isIn(*GA, "uninstrumented");
968 }
969 
970 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
971   return ClArgsABI ? IA_Args : IA_TLS;
972 }
973 
974 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
975   if (ABIList.isIn(*F, "functional"))
976     return WK_Functional;
977   if (ABIList.isIn(*F, "discard"))
978     return WK_Discard;
979   if (ABIList.isIn(*F, "custom"))
980     return WK_Custom;
981 
982   return WK_Warning;
983 }
984 
985 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
986   std::string GVName = std::string(GV->getName()), Prefix = "dfs$";
987   GV->setName(Prefix + GVName);
988 
989   // Try to change the name of the function in module inline asm.  We only do
990   // this for specific asm directives, currently only ".symver", to try to avoid
991   // corrupting asm which happens to contain the symbol name as a substring.
992   // Note that the substitution for .symver assumes that the versioned symbol
993   // also has an instrumented name.
994   std::string Asm = GV->getParent()->getModuleInlineAsm();
995   std::string SearchStr = ".symver " + GVName + ",";
996   size_t Pos = Asm.find(SearchStr);
997   if (Pos != std::string::npos) {
998     Asm.replace(Pos, SearchStr.size(),
999                 ".symver " + Prefix + GVName + "," + Prefix);
1000     GV->getParent()->setModuleInlineAsm(Asm);
1001   }
1002 }
1003 
1004 Function *
1005 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
1006                                         GlobalValue::LinkageTypes NewFLink,
1007                                         FunctionType *NewFT) {
1008   FunctionType *FT = F->getFunctionType();
1009   Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
1010                                     NewFName, F->getParent());
1011   NewF->copyAttributesFrom(F);
1012   NewF->removeAttributes(
1013       AttributeList::ReturnIndex,
1014       AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1015 
1016   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
1017   if (F->isVarArg()) {
1018     NewF->removeAttributes(AttributeList::FunctionIndex,
1019                            AttrBuilder().addAttribute("split-stack"));
1020     CallInst::Create(DFSanVarargWrapperFn,
1021                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
1022                      BB);
1023     new UnreachableInst(*Ctx, BB);
1024   } else {
1025     std::vector<Value *> Args;
1026     unsigned n = FT->getNumParams();
1027     for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
1028       Args.push_back(&*ai);
1029     CallInst *CI = CallInst::Create(F, Args, "", BB);
1030     if (FT->getReturnType()->isVoidTy())
1031       ReturnInst::Create(*Ctx, BB);
1032     else
1033       ReturnInst::Create(*Ctx, CI, BB);
1034   }
1035 
1036   return NewF;
1037 }
1038 
1039 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
1040                                                           StringRef FName) {
1041   FunctionType *FTT = getTrampolineFunctionType(FT);
1042   FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
1043   Function *F = dyn_cast<Function>(C.getCallee());
1044   if (F && F->isDeclaration()) {
1045     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
1046     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
1047     std::vector<Value *> Args;
1048     Function::arg_iterator AI = F->arg_begin(); ++AI;
1049     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
1050       Args.push_back(&*AI);
1051     CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
1052     ReturnInst *RI;
1053     if (FT->getReturnType()->isVoidTy())
1054       RI = ReturnInst::Create(*Ctx, BB);
1055     else
1056       RI = ReturnInst::Create(*Ctx, CI, BB);
1057 
1058     // F is called by a wrapped custom function with primitive shadows. So
1059     // its arguments and return value need conversion.
1060     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
1061     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
1062     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N) {
1063       Value *Shadow =
1064           DFSF.expandFromPrimitiveShadow(ValAI->getType(), &*ShadowAI, CI);
1065       DFSF.ValShadowMap[&*ValAI] = Shadow;
1066     }
1067     DFSanVisitor(DFSF).visitCallInst(*CI);
1068     if (!FT->getReturnType()->isVoidTy()) {
1069       Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(
1070           DFSF.getShadow(RI->getReturnValue()), RI);
1071       new StoreInst(PrimitiveShadow, &*std::prev(F->arg_end()), RI);
1072     }
1073   }
1074 
1075   return cast<Constant>(C.getCallee());
1076 }
1077 
1078 // Initialize DataFlowSanitizer runtime functions and declare them in the module
1079 void DataFlowSanitizer::initializeRuntimeFunctions(Module &M) {
1080   {
1081     AttributeList AL;
1082     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1083                          Attribute::NoUnwind);
1084     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1085                          Attribute::ReadNone);
1086     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1087                          Attribute::ZExt);
1088     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1089     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1090     DFSanUnionFn =
1091         Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL);
1092   }
1093   {
1094     AttributeList AL;
1095     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1096                          Attribute::NoUnwind);
1097     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1098                          Attribute::ReadNone);
1099     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1100                          Attribute::ZExt);
1101     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1102     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1103     DFSanCheckedUnionFn =
1104         Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL);
1105   }
1106   {
1107     AttributeList AL;
1108     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1109                          Attribute::NoUnwind);
1110     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1111                          Attribute::ReadOnly);
1112     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1113                          Attribute::ZExt);
1114     DFSanUnionLoadFn =
1115         Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
1116   }
1117   {
1118     AttributeList AL;
1119     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1120                          Attribute::NoUnwind);
1121     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1122                          Attribute::ReadOnly);
1123     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1124                          Attribute::ZExt);
1125     DFSanUnionLoadFast16LabelsFn = Mod->getOrInsertFunction(
1126         "__dfsan_union_load_fast16labels", DFSanUnionLoadFnTy, AL);
1127   }
1128   {
1129     AttributeList AL;
1130     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1131                          Attribute::NoUnwind);
1132     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1133                          Attribute::ReadOnly);
1134     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1135                          Attribute::ZExt);
1136     DFSanLoadLabelAndOriginFn = Mod->getOrInsertFunction(
1137         "__dfsan_load_label_and_origin", DFSanLoadLabelAndOriginFnTy, AL);
1138   }
1139   DFSanUnimplementedFn =
1140       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
1141   {
1142     AttributeList AL;
1143     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1144     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1145     DFSanSetLabelFn =
1146         Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
1147   }
1148   DFSanNonzeroLabelFn =
1149       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
1150   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
1151                                                   DFSanVarargWrapperFnTy);
1152   {
1153     AttributeList AL;
1154     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1155     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1156                          Attribute::ZExt);
1157     DFSanChainOriginFn = Mod->getOrInsertFunction("__dfsan_chain_origin",
1158                                                   DFSanChainOriginFnTy, AL);
1159   }
1160   DFSanMemOriginTransferFn = Mod->getOrInsertFunction(
1161       "__dfsan_mem_origin_transfer", DFSanMemOriginTransferFnTy);
1162 
1163   {
1164     AttributeList AL;
1165     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1166     AL = AL.addParamAttribute(M.getContext(), 3, Attribute::ZExt);
1167     DFSanMaybeStoreOriginFn = Mod->getOrInsertFunction(
1168         "__dfsan_maybe_store_origin", DFSanMaybeStoreOriginFnTy, AL);
1169   }
1170 
1171   DFSanRuntimeFunctions.insert(DFSanUnionFn.getCallee()->stripPointerCasts());
1172   DFSanRuntimeFunctions.insert(
1173       DFSanCheckedUnionFn.getCallee()->stripPointerCasts());
1174   DFSanRuntimeFunctions.insert(
1175       DFSanUnionLoadFn.getCallee()->stripPointerCasts());
1176   DFSanRuntimeFunctions.insert(
1177       DFSanUnionLoadFast16LabelsFn.getCallee()->stripPointerCasts());
1178   DFSanRuntimeFunctions.insert(
1179       DFSanLoadLabelAndOriginFn.getCallee()->stripPointerCasts());
1180   DFSanRuntimeFunctions.insert(
1181       DFSanUnimplementedFn.getCallee()->stripPointerCasts());
1182   DFSanRuntimeFunctions.insert(
1183       DFSanSetLabelFn.getCallee()->stripPointerCasts());
1184   DFSanRuntimeFunctions.insert(
1185       DFSanNonzeroLabelFn.getCallee()->stripPointerCasts());
1186   DFSanRuntimeFunctions.insert(
1187       DFSanVarargWrapperFn.getCallee()->stripPointerCasts());
1188   DFSanRuntimeFunctions.insert(
1189       DFSanLoadCallbackFn.getCallee()->stripPointerCasts());
1190   DFSanRuntimeFunctions.insert(
1191       DFSanStoreCallbackFn.getCallee()->stripPointerCasts());
1192   DFSanRuntimeFunctions.insert(
1193       DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts());
1194   DFSanRuntimeFunctions.insert(
1195       DFSanCmpCallbackFn.getCallee()->stripPointerCasts());
1196   DFSanRuntimeFunctions.insert(
1197       DFSanChainOriginFn.getCallee()->stripPointerCasts());
1198   DFSanRuntimeFunctions.insert(
1199       DFSanMemOriginTransferFn.getCallee()->stripPointerCasts());
1200   DFSanRuntimeFunctions.insert(
1201       DFSanMaybeStoreOriginFn.getCallee()->stripPointerCasts());
1202 }
1203 
1204 // Initializes event callback functions and declare them in the module
1205 void DataFlowSanitizer::initializeCallbackFunctions(Module &M) {
1206   DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback",
1207                                                  DFSanLoadStoreCallbackFnTy);
1208   DFSanStoreCallbackFn = Mod->getOrInsertFunction("__dfsan_store_callback",
1209                                                   DFSanLoadStoreCallbackFnTy);
1210   DFSanMemTransferCallbackFn = Mod->getOrInsertFunction(
1211       "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy);
1212   DFSanCmpCallbackFn =
1213       Mod->getOrInsertFunction("__dfsan_cmp_callback", DFSanCmpCallbackFnTy);
1214 }
1215 
1216 bool DataFlowSanitizer::runImpl(Module &M) {
1217   init(M);
1218 
1219   if (ABIList.isIn(M, "skip"))
1220     return false;
1221 
1222   const unsigned InitialGlobalSize = M.global_size();
1223   const unsigned InitialModuleSize = M.size();
1224 
1225   bool Changed = false;
1226 
1227   auto getOrInsertGlobal = [this, &Changed](StringRef Name,
1228                                             Type *Ty) -> Constant * {
1229     Constant *C = Mod->getOrInsertGlobal(Name, Ty);
1230     if (GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1231       Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel;
1232       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
1233     }
1234     return C;
1235   };
1236 
1237   // These globals must be kept in sync with the ones in dfsan.cpp.
1238   ArgTLS = getOrInsertGlobal(
1239       "__dfsan_arg_tls",
1240       ArrayType::get(Type::getInt64Ty(*Ctx), kArgTLSSize / 8));
1241   RetvalTLS = getOrInsertGlobal(
1242       "__dfsan_retval_tls",
1243       ArrayType::get(Type::getInt64Ty(*Ctx), kRetvalTLSSize / 8));
1244   ArgOriginTLSTy = ArrayType::get(OriginTy, kNumOfElementsInArgOrgTLS);
1245   ArgOriginTLS = getOrInsertGlobal("__dfsan_arg_origin_tls", ArgOriginTLSTy);
1246   RetvalOriginTLS = getOrInsertGlobal("__dfsan_retval_origin_tls", OriginTy);
1247 
1248   (void)Mod->getOrInsertGlobal("__dfsan_track_origins", OriginTy, [&] {
1249     Changed = true;
1250     return new GlobalVariable(
1251         M, OriginTy, true, GlobalValue::WeakODRLinkage,
1252         ConstantInt::getSigned(OriginTy, shouldTrackOrigins()),
1253         "__dfsan_track_origins");
1254   });
1255 
1256   ExternalShadowMask =
1257       Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
1258 
1259   initializeCallbackFunctions(M);
1260   initializeRuntimeFunctions(M);
1261 
1262   std::vector<Function *> FnsToInstrument;
1263   SmallPtrSet<Function *, 2> FnsWithNativeABI;
1264   for (Function &i : M)
1265     if (!i.isIntrinsic() && !DFSanRuntimeFunctions.contains(&i))
1266       FnsToInstrument.push_back(&i);
1267 
1268   // Give function aliases prefixes when necessary, and build wrappers where the
1269   // instrumentedness is inconsistent.
1270   for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
1271     GlobalAlias *GA = &*i;
1272     ++i;
1273     // Don't stop on weak.  We assume people aren't playing games with the
1274     // instrumentedness of overridden weak aliases.
1275     if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
1276       bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
1277       if (GAInst && FInst) {
1278         addGlobalNamePrefix(GA);
1279       } else if (GAInst != FInst) {
1280         // Non-instrumented alias of an instrumented function, or vice versa.
1281         // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
1282         // below will take care of instrumenting it.
1283         Function *NewF =
1284             buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
1285         GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
1286         NewF->takeName(GA);
1287         GA->eraseFromParent();
1288         FnsToInstrument.push_back(NewF);
1289       }
1290     }
1291   }
1292 
1293   ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
1294       .addAttribute(Attribute::ReadNone);
1295 
1296   // First, change the ABI of every function in the module.  ABI-listed
1297   // functions keep their original ABI and get a wrapper function.
1298   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
1299                                          e = FnsToInstrument.end();
1300        i != e; ++i) {
1301     Function &F = **i;
1302     FunctionType *FT = F.getFunctionType();
1303 
1304     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
1305                               FT->getReturnType()->isVoidTy());
1306 
1307     if (isInstrumented(&F)) {
1308       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
1309       // easily identify cases of mismatching ABIs.
1310       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
1311         FunctionType *NewFT = getArgsFunctionType(FT);
1312         Function *NewF = Function::Create(NewFT, F.getLinkage(),
1313                                           F.getAddressSpace(), "", &M);
1314         NewF->copyAttributesFrom(&F);
1315         NewF->removeAttributes(
1316             AttributeList::ReturnIndex,
1317             AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1318         for (Function::arg_iterator FArg = F.arg_begin(),
1319                                     NewFArg = NewF->arg_begin(),
1320                                     FArgEnd = F.arg_end();
1321              FArg != FArgEnd; ++FArg, ++NewFArg) {
1322           FArg->replaceAllUsesWith(&*NewFArg);
1323         }
1324         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
1325 
1326         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
1327              UI != UE;) {
1328           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
1329           ++UI;
1330           if (BA) {
1331             BA->replaceAllUsesWith(
1332                 BlockAddress::get(NewF, BA->getBasicBlock()));
1333             delete BA;
1334           }
1335         }
1336         F.replaceAllUsesWith(
1337             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
1338         NewF->takeName(&F);
1339         F.eraseFromParent();
1340         *i = NewF;
1341         addGlobalNamePrefix(NewF);
1342       } else {
1343         addGlobalNamePrefix(&F);
1344       }
1345     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
1346       // Build a wrapper function for F.  The wrapper simply calls F, and is
1347       // added to FnsToInstrument so that any instrumentation according to its
1348       // WrapperKind is done in the second pass below.
1349       FunctionType *NewFT = getInstrumentedABI() == IA_Args
1350                                 ? getArgsFunctionType(FT)
1351                                 : FT;
1352 
1353       // If the function being wrapped has local linkage, then preserve the
1354       // function's linkage in the wrapper function.
1355       GlobalValue::LinkageTypes wrapperLinkage =
1356           F.hasLocalLinkage()
1357               ? F.getLinkage()
1358               : GlobalValue::LinkOnceODRLinkage;
1359 
1360       Function *NewF = buildWrapperFunction(
1361           &F, std::string("dfsw$") + std::string(F.getName()),
1362           wrapperLinkage, NewFT);
1363       if (getInstrumentedABI() == IA_TLS)
1364         NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
1365 
1366       Value *WrappedFnCst =
1367           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
1368       F.replaceAllUsesWith(WrappedFnCst);
1369 
1370       UnwrappedFnMap[WrappedFnCst] = &F;
1371       *i = NewF;
1372 
1373       if (!F.isDeclaration()) {
1374         // This function is probably defining an interposition of an
1375         // uninstrumented function and hence needs to keep the original ABI.
1376         // But any functions it may call need to use the instrumented ABI, so
1377         // we instrument it in a mode which preserves the original ABI.
1378         FnsWithNativeABI.insert(&F);
1379 
1380         // This code needs to rebuild the iterators, as they may be invalidated
1381         // by the push_back, taking care that the new range does not include
1382         // any functions added by this code.
1383         size_t N = i - FnsToInstrument.begin(),
1384                Count = e - FnsToInstrument.begin();
1385         FnsToInstrument.push_back(&F);
1386         i = FnsToInstrument.begin() + N;
1387         e = FnsToInstrument.begin() + Count;
1388       }
1389                // Hopefully, nobody will try to indirectly call a vararg
1390                // function... yet.
1391     } else if (FT->isVarArg()) {
1392       UnwrappedFnMap[&F] = &F;
1393       *i = nullptr;
1394     }
1395   }
1396 
1397   for (Function *i : FnsToInstrument) {
1398     if (!i || i->isDeclaration())
1399       continue;
1400 
1401     removeUnreachableBlocks(*i);
1402 
1403     DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
1404 
1405     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
1406     // Build a copy of the list before iterating over it.
1407     SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
1408 
1409     for (BasicBlock *i : BBList) {
1410       Instruction *Inst = &i->front();
1411       while (true) {
1412         // DFSanVisitor may split the current basic block, changing the current
1413         // instruction's next pointer and moving the next instruction to the
1414         // tail block from which we should continue.
1415         Instruction *Next = Inst->getNextNode();
1416         // DFSanVisitor may delete Inst, so keep track of whether it was a
1417         // terminator.
1418         bool IsTerminator = Inst->isTerminator();
1419         if (!DFSF.SkipInsts.count(Inst))
1420           DFSanVisitor(DFSF).visit(Inst);
1421         if (IsTerminator)
1422           break;
1423         Inst = Next;
1424       }
1425     }
1426 
1427     // We will not necessarily be able to compute the shadow for every phi node
1428     // until we have visited every block.  Therefore, the code that handles phi
1429     // nodes adds them to the PHIFixups list so that they can be properly
1430     // handled here.
1431     for (std::vector<std::pair<PHINode *, PHINode *>>::iterator
1432              i = DFSF.PHIFixups.begin(),
1433              e = DFSF.PHIFixups.end();
1434          i != e; ++i) {
1435       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
1436            ++val) {
1437         i->second->setIncomingValue(
1438             val, DFSF.getShadow(i->first->getIncomingValue(val)));
1439       }
1440     }
1441 
1442     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
1443     // places (i.e. instructions in basic blocks we haven't even begun visiting
1444     // yet).  To make our life easier, do this work in a pass after the main
1445     // instrumentation.
1446     if (ClDebugNonzeroLabels) {
1447       for (Value *V : DFSF.NonZeroChecks) {
1448         Instruction *Pos;
1449         if (Instruction *I = dyn_cast<Instruction>(V))
1450           Pos = I->getNextNode();
1451         else
1452           Pos = &DFSF.F->getEntryBlock().front();
1453         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
1454           Pos = Pos->getNextNode();
1455         IRBuilder<> IRB(Pos);
1456         Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(V, Pos);
1457         Value *Ne =
1458             IRB.CreateICmpNE(PrimitiveShadow, DFSF.DFS.ZeroPrimitiveShadow);
1459         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1460             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
1461         IRBuilder<> ThenIRB(BI);
1462         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1463       }
1464     }
1465   }
1466 
1467   return Changed || !FnsToInstrument.empty() ||
1468          M.global_size() != InitialGlobalSize || M.size() != InitialModuleSize;
1469 }
1470 
1471 Value *DFSanFunction::getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB) {
1472   Value *Base = IRB.CreatePointerCast(DFS.ArgTLS, DFS.IntptrTy);
1473   if (ArgOffset)
1474     Base = IRB.CreateAdd(Base, ConstantInt::get(DFS.IntptrTy, ArgOffset));
1475   return IRB.CreateIntToPtr(Base, PointerType::get(DFS.getShadowTy(T), 0),
1476                             "_dfsarg");
1477 }
1478 
1479 Value *DFSanFunction::getRetvalTLS(Type *T, IRBuilder<> &IRB) {
1480   return IRB.CreatePointerCast(
1481       DFS.RetvalTLS, PointerType::get(DFS.getShadowTy(T), 0), "_dfsret");
1482 }
1483 
1484 Value *DFSanFunction::getRetvalOriginTLS() { return DFS.RetvalOriginTLS; }
1485 
1486 Value *DFSanFunction::getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB) {
1487   return IRB.CreateConstGEP2_64(DFS.ArgOriginTLSTy, DFS.ArgOriginTLS, 0, ArgNo,
1488                                 "_dfsarg_o");
1489 }
1490 
1491 Value *DFSanFunction::getOrigin(Value *V) {
1492   assert(DFS.shouldTrackOrigins());
1493   if (!isa<Argument>(V) && !isa<Instruction>(V))
1494     return DFS.ZeroOrigin;
1495   Value *&Origin = ValOriginMap[V];
1496   if (!Origin) {
1497     if (Argument *A = dyn_cast<Argument>(V)) {
1498       if (IsNativeABI)
1499         return DFS.ZeroOrigin;
1500       switch (IA) {
1501       case DataFlowSanitizer::IA_TLS: {
1502         if (A->getArgNo() < DFS.kNumOfElementsInArgOrgTLS) {
1503           Instruction *ArgOriginTLSPos = &*F->getEntryBlock().begin();
1504           IRBuilder<> IRB(ArgOriginTLSPos);
1505           Value *ArgOriginPtr = getArgOriginTLS(A->getArgNo(), IRB);
1506           Origin = IRB.CreateLoad(DFS.OriginTy, ArgOriginPtr);
1507         } else {
1508           // Overflow
1509           Origin = DFS.ZeroOrigin;
1510         }
1511         break;
1512       }
1513       case DataFlowSanitizer::IA_Args: {
1514         Origin = DFS.ZeroOrigin;
1515         break;
1516       }
1517       }
1518     } else {
1519       Origin = DFS.ZeroOrigin;
1520     }
1521   }
1522   return Origin;
1523 }
1524 
1525 void DFSanFunction::setOrigin(Instruction *I, Value *Origin) {
1526   if (!DFS.shouldTrackOrigins())
1527     return;
1528   assert(!ValOriginMap.count(I));
1529   assert(Origin->getType() == DFS.OriginTy);
1530   ValOriginMap[I] = Origin;
1531 }
1532 
1533 Value *DFSanFunction::getShadowForTLSArgument(Argument *A) {
1534   unsigned ArgOffset = 0;
1535   const DataLayout &DL = F->getParent()->getDataLayout();
1536   for (auto &FArg : F->args()) {
1537     if (!FArg.getType()->isSized()) {
1538       if (A == &FArg)
1539         break;
1540       continue;
1541     }
1542 
1543     unsigned Size = DL.getTypeAllocSize(DFS.getShadowTy(&FArg));
1544     if (A != &FArg) {
1545       ArgOffset += alignTo(Size, kShadowTLSAlignment);
1546       if (ArgOffset > kArgTLSSize)
1547         break; // ArgTLS overflows, uses a zero shadow.
1548       continue;
1549     }
1550 
1551     if (ArgOffset + Size > kArgTLSSize)
1552       break; // ArgTLS overflows, uses a zero shadow.
1553 
1554     Instruction *ArgTLSPos = &*F->getEntryBlock().begin();
1555     IRBuilder<> IRB(ArgTLSPos);
1556     Value *ArgShadowPtr = getArgTLS(FArg.getType(), ArgOffset, IRB);
1557     return IRB.CreateAlignedLoad(DFS.getShadowTy(&FArg), ArgShadowPtr,
1558                                  kShadowTLSAlignment);
1559   }
1560 
1561   return DFS.getZeroShadow(A);
1562 }
1563 
1564 Value *DFSanFunction::getShadow(Value *V) {
1565   if (!isa<Argument>(V) && !isa<Instruction>(V))
1566     return DFS.getZeroShadow(V);
1567   Value *&Shadow = ValShadowMap[V];
1568   if (!Shadow) {
1569     if (Argument *A = dyn_cast<Argument>(V)) {
1570       if (IsNativeABI)
1571         return DFS.getZeroShadow(V);
1572       switch (IA) {
1573       case DataFlowSanitizer::IA_TLS: {
1574         Shadow = getShadowForTLSArgument(A);
1575         break;
1576       }
1577       case DataFlowSanitizer::IA_Args: {
1578         unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
1579         Function::arg_iterator i = F->arg_begin();
1580         while (ArgIdx--)
1581           ++i;
1582         Shadow = &*i;
1583         assert(Shadow->getType() == DFS.PrimitiveShadowTy);
1584         break;
1585       }
1586       }
1587       NonZeroChecks.push_back(Shadow);
1588     } else {
1589       Shadow = DFS.getZeroShadow(V);
1590     }
1591   }
1592   return Shadow;
1593 }
1594 
1595 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1596   assert(!ValShadowMap.count(I));
1597   assert(DFS.shouldTrackFieldsAndIndices() ||
1598          Shadow->getType() == DFS.PrimitiveShadowTy);
1599   ValShadowMap[I] = Shadow;
1600 }
1601 
1602 Value *DataFlowSanitizer::getShadowOffset(Value *Addr, IRBuilder<> &IRB) {
1603   // Returns Addr & shadow_mask
1604   assert(Addr != RetvalTLS && "Reinstrumenting?");
1605   Value *ShadowPtrMaskValue;
1606   if (DFSanRuntimeShadowMask)
1607     ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
1608   else
1609     ShadowPtrMaskValue = ShadowPtrMask;
1610   return IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
1611                        IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy));
1612 }
1613 /*
1614 std::pair<Value *, Value *>
1615 DataFlowSanitizer::getShadowOriginAddress(Value *Addr, Align InstAlignment,
1616                                           Instruction *Pos) {
1617   // Returns ((Addr & shadow_mask) + origin_base) & ~4UL
1618   IRBuilder<> IRB(Pos);
1619   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1620   Value *ShadowPtr = IRB.CreateIntToPtr(
1621       IRB.CreateMul(ShadowOffset, ShadowPtrMul), PrimitiveShadowPtrTy);
1622   Value *OriginPtr = nullptr;
1623   if (shouldTrackOrigins()) {
1624     Value *OriginLong = IRB.CreateAdd(ShadowOffset, OriginBase);
1625     const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1626     // When alignment is >= 4, Addr must be aligned to 4, otherwise it is UB.
1627     // So Mask is unnecessary.
1628     if (Alignment < kMinOriginAlignment) {
1629       uint64_t Mask = kMinOriginAlignment.value() - 1;
1630       OriginLong = IRB.CreateAnd(OriginLong, ConstantInt::get(IntptrTy, ~Mask));
1631     }
1632     OriginPtr = IRB.CreateIntToPtr(OriginLong, OriginPtrTy);
1633   }
1634   return {ShadowPtr, OriginPtr};
1635 }
1636 */
1637 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1638   // Returns (Addr & shadow_mask) x 2
1639   IRBuilder<> IRB(Pos);
1640   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1641   return IRB.CreateIntToPtr(IRB.CreateMul(ShadowOffset, ShadowPtrMul),
1642                             PrimitiveShadowPtrTy);
1643 }
1644 
1645 Value *DFSanFunction::combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
1646                                                 Instruction *Pos) {
1647   Value *PrimitiveValue = combineShadows(V1, V2, Pos);
1648   return expandFromPrimitiveShadow(T, PrimitiveValue, Pos);
1649 }
1650 
1651 // Generates IR to compute the union of the two given shadows, inserting it
1652 // before Pos. The combined value is with primitive type.
1653 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1654   if (DFS.isZeroShadow(V1))
1655     return collapseToPrimitiveShadow(V2, Pos);
1656   if (DFS.isZeroShadow(V2))
1657     return collapseToPrimitiveShadow(V1, Pos);
1658   if (V1 == V2)
1659     return collapseToPrimitiveShadow(V1, Pos);
1660 
1661   auto V1Elems = ShadowElements.find(V1);
1662   auto V2Elems = ShadowElements.find(V2);
1663   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1664     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1665                       V2Elems->second.begin(), V2Elems->second.end())) {
1666       return collapseToPrimitiveShadow(V1, Pos);
1667     } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1668                              V1Elems->second.begin(), V1Elems->second.end())) {
1669       return collapseToPrimitiveShadow(V2, Pos);
1670     }
1671   } else if (V1Elems != ShadowElements.end()) {
1672     if (V1Elems->second.count(V2))
1673       return collapseToPrimitiveShadow(V1, Pos);
1674   } else if (V2Elems != ShadowElements.end()) {
1675     if (V2Elems->second.count(V1))
1676       return collapseToPrimitiveShadow(V2, Pos);
1677   }
1678 
1679   auto Key = std::make_pair(V1, V2);
1680   if (V1 > V2)
1681     std::swap(Key.first, Key.second);
1682   CachedShadow &CCS = CachedShadows[Key];
1683   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1684     return CCS.Shadow;
1685 
1686   // Converts inputs shadows to shadows with primitive types.
1687   Value *PV1 = collapseToPrimitiveShadow(V1, Pos);
1688   Value *PV2 = collapseToPrimitiveShadow(V2, Pos);
1689 
1690   IRBuilder<> IRB(Pos);
1691   if (ClFast16Labels) {
1692     CCS.Block = Pos->getParent();
1693     CCS.Shadow = IRB.CreateOr(PV1, PV2);
1694   } else if (AvoidNewBlocks) {
1695     CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {PV1, PV2});
1696     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1697     Call->addParamAttr(0, Attribute::ZExt);
1698     Call->addParamAttr(1, Attribute::ZExt);
1699 
1700     CCS.Block = Pos->getParent();
1701     CCS.Shadow = Call;
1702   } else {
1703     BasicBlock *Head = Pos->getParent();
1704     Value *Ne = IRB.CreateICmpNE(PV1, PV2);
1705     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1706         Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1707     IRBuilder<> ThenIRB(BI);
1708     CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {PV1, PV2});
1709     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1710     Call->addParamAttr(0, Attribute::ZExt);
1711     Call->addParamAttr(1, Attribute::ZExt);
1712 
1713     BasicBlock *Tail = BI->getSuccessor(0);
1714     PHINode *Phi =
1715         PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
1716     Phi->addIncoming(Call, Call->getParent());
1717     Phi->addIncoming(PV1, Head);
1718 
1719     CCS.Block = Tail;
1720     CCS.Shadow = Phi;
1721   }
1722 
1723   std::set<Value *> UnionElems;
1724   if (V1Elems != ShadowElements.end()) {
1725     UnionElems = V1Elems->second;
1726   } else {
1727     UnionElems.insert(V1);
1728   }
1729   if (V2Elems != ShadowElements.end()) {
1730     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1731   } else {
1732     UnionElems.insert(V2);
1733   }
1734   ShadowElements[CCS.Shadow] = std::move(UnionElems);
1735 
1736   return CCS.Shadow;
1737 }
1738 
1739 // A convenience function which folds the shadows of each of the operands
1740 // of the provided instruction Inst, inserting the IR before Inst.  Returns
1741 // the computed union Value.
1742 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1743   if (Inst->getNumOperands() == 0)
1744     return DFS.getZeroShadow(Inst);
1745 
1746   Value *Shadow = getShadow(Inst->getOperand(0));
1747   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
1748     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1749   }
1750   return expandFromPrimitiveShadow(Inst->getType(), Shadow, Inst);
1751 }
1752 
1753 void DFSanVisitor::visitInstOperands(Instruction &I) {
1754   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1755   DFSF.setShadow(&I, CombinedShadow);
1756   visitInstOperandOrigins(I);
1757 }
1758 
1759 Value *DFSanFunction::combineOrigins(const std::vector<Value *> &Shadows,
1760                                      const std::vector<Value *> &Origins,
1761                                      Instruction *Pos, ConstantInt *Zero) {
1762   assert(Shadows.size() == Origins.size());
1763   size_t Size = Origins.size();
1764   if (Size == 0)
1765     return DFS.ZeroOrigin;
1766   Value *Origin = nullptr;
1767   if (!Zero)
1768     Zero = DFS.ZeroPrimitiveShadow;
1769   for (size_t I = 0; I != Size; ++I) {
1770     Value *OpOrigin = Origins[I];
1771     Constant *ConstOpOrigin = dyn_cast<Constant>(OpOrigin);
1772     if (ConstOpOrigin && ConstOpOrigin->isNullValue())
1773       continue;
1774     if (!Origin) {
1775       Origin = OpOrigin;
1776       continue;
1777     }
1778     Value *OpShadow = Shadows[I];
1779     Value *PrimitiveShadow = collapseToPrimitiveShadow(OpShadow, Pos);
1780     IRBuilder<> IRB(Pos);
1781     Value *Cond = IRB.CreateICmpNE(PrimitiveShadow, Zero);
1782     Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1783   }
1784   return Origin ? Origin : DFS.ZeroOrigin;
1785 }
1786 
1787 Value *DFSanFunction::combineOperandOrigins(Instruction *Inst) {
1788   size_t Size = Inst->getNumOperands();
1789   std::vector<Value *> Shadows(Size);
1790   std::vector<Value *> Origins(Size);
1791   for (unsigned I = 0; I != Size; ++I) {
1792     Shadows[I] = getShadow(Inst->getOperand(I));
1793     Origins[I] = getOrigin(Inst->getOperand(I));
1794   }
1795   return combineOrigins(Shadows, Origins, Inst);
1796 }
1797 
1798 void DFSanVisitor::visitInstOperandOrigins(Instruction &I) {
1799   if (!DFSF.DFS.shouldTrackOrigins())
1800     return;
1801   Value *CombinedOrigin = DFSF.combineOperandOrigins(&I);
1802   DFSF.setOrigin(&I, CombinedOrigin);
1803 }
1804 
1805 Value *DFSanFunction::loadFast16ShadowFast(Value *ShadowAddr, uint64_t Size,
1806                                            Align ShadowAlign,
1807                                            Instruction *Pos) {
1808   // First OR all the WideShadows, then OR individual shadows within the
1809   // combined WideShadow. This is fewer instructions than ORing shadows
1810   // individually.
1811   IRBuilder<> IRB(Pos);
1812   Value *WideAddr =
1813       IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1814   Value *CombinedWideShadow =
1815       IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1816   for (uint64_t Ofs = 64 / DFS.ShadowWidthBits; Ofs != Size;
1817        Ofs += 64 / DFS.ShadowWidthBits) {
1818     WideAddr = IRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1819                              ConstantInt::get(DFS.IntptrTy, 1));
1820     Value *NextWideShadow =
1821         IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1822     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, NextWideShadow);
1823   }
1824   for (unsigned Width = 32; Width >= DFS.ShadowWidthBits; Width >>= 1) {
1825     Value *ShrShadow = IRB.CreateLShr(CombinedWideShadow, Width);
1826     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, ShrShadow);
1827   }
1828   return IRB.CreateTrunc(CombinedWideShadow, DFS.PrimitiveShadowTy);
1829 }
1830 
1831 Value *DFSanFunction::loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size,
1832                                            Align ShadowAlign,
1833                                            Instruction *Pos) {
1834   // Fast path for the common case where each byte has identical shadow: load
1835   // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1836   // shadow is non-equal.
1837   BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1838   IRBuilder<> FallbackIRB(FallbackBB);
1839   CallInst *FallbackCall = FallbackIRB.CreateCall(
1840       DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1841   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1842 
1843   // Compare each of the shadows stored in the loaded 64 bits to each other,
1844   // by computing (WideShadow rotl ShadowWidthBits) == WideShadow.
1845   IRBuilder<> IRB(Pos);
1846   Value *WideAddr =
1847       IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1848   Value *WideShadow =
1849       IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1850   Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.PrimitiveShadowTy);
1851   Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidthBits);
1852   Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidthBits);
1853   Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1854   Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1855 
1856   BasicBlock *Head = Pos->getParent();
1857   BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
1858 
1859   if (DomTreeNode *OldNode = DT.getNode(Head)) {
1860     std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1861 
1862     DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1863     for (auto *Child : Children)
1864       DT.changeImmediateDominator(Child, NewNode);
1865   }
1866 
1867   // In the following code LastBr will refer to the previous basic block's
1868   // conditional branch instruction, whose true successor is fixed up to point
1869   // to the next block during the loop below or to the tail after the final
1870   // iteration.
1871   BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1872   ReplaceInstWithInst(Head->getTerminator(), LastBr);
1873   DT.addNewBlock(FallbackBB, Head);
1874 
1875   for (uint64_t Ofs = 64 / DFS.ShadowWidthBits; Ofs != Size;
1876        Ofs += 64 / DFS.ShadowWidthBits) {
1877     BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1878     DT.addNewBlock(NextBB, LastBr->getParent());
1879     IRBuilder<> NextIRB(NextBB);
1880     WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1881                                  ConstantInt::get(DFS.IntptrTy, 1));
1882     Value *NextWideShadow =
1883         NextIRB.CreateAlignedLoad(NextIRB.getInt64Ty(), WideAddr, ShadowAlign);
1884     ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1885     LastBr->setSuccessor(0, NextBB);
1886     LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1887   }
1888 
1889   LastBr->setSuccessor(0, Tail);
1890   FallbackIRB.CreateBr(Tail);
1891   PHINode *Shadow =
1892       PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
1893   Shadow->addIncoming(FallbackCall, FallbackBB);
1894   Shadow->addIncoming(TruncShadow, LastBr->getParent());
1895   return Shadow;
1896 }
1897 
1898 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1899 // Addr has alignment Align, and take the union of each of those shadows. The
1900 // returned shadow always has primitive type.
1901 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1902                                  Instruction *Pos) {
1903   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1904     const auto i = AllocaShadowMap.find(AI);
1905     if (i != AllocaShadowMap.end()) {
1906       IRBuilder<> IRB(Pos);
1907       return IRB.CreateLoad(DFS.PrimitiveShadowTy, i->second);
1908     }
1909   }
1910 
1911   const llvm::Align ShadowAlign(Align * DFS.ShadowWidthBytes);
1912   SmallVector<const Value *, 2> Objs;
1913   getUnderlyingObjects(Addr, Objs);
1914   bool AllConstants = true;
1915   for (const Value *Obj : Objs) {
1916     if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
1917       continue;
1918     if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
1919       continue;
1920 
1921     AllConstants = false;
1922     break;
1923   }
1924   if (AllConstants)
1925     return DFS.ZeroPrimitiveShadow;
1926 
1927   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1928   switch (Size) {
1929   case 0:
1930     return DFS.ZeroPrimitiveShadow;
1931   case 1: {
1932     LoadInst *LI = new LoadInst(DFS.PrimitiveShadowTy, ShadowAddr, "", Pos);
1933     LI->setAlignment(ShadowAlign);
1934     return LI;
1935   }
1936   case 2: {
1937     IRBuilder<> IRB(Pos);
1938     Value *ShadowAddr1 = IRB.CreateGEP(DFS.PrimitiveShadowTy, ShadowAddr,
1939                                        ConstantInt::get(DFS.IntptrTy, 1));
1940     return combineShadows(
1941         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr, ShadowAlign),
1942         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr1, ShadowAlign),
1943         Pos);
1944   }
1945   }
1946 
1947   if (ClFast16Labels && Size % (64 / DFS.ShadowWidthBits) == 0)
1948     return loadFast16ShadowFast(ShadowAddr, Size, ShadowAlign, Pos);
1949 
1950   if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidthBits) == 0)
1951     return loadLegacyShadowFast(ShadowAddr, Size, ShadowAlign, Pos);
1952 
1953   IRBuilder<> IRB(Pos);
1954   FunctionCallee &UnionLoadFn =
1955       ClFast16Labels ? DFS.DFSanUnionLoadFast16LabelsFn : DFS.DFSanUnionLoadFn;
1956   CallInst *FallbackCall = IRB.CreateCall(
1957       UnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1958   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1959   return FallbackCall;
1960 }
1961 
1962 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1963   auto &DL = LI.getModule()->getDataLayout();
1964   uint64_t Size = DL.getTypeStoreSize(LI.getType());
1965   if (Size == 0) {
1966     DFSF.setShadow(&LI, DFSF.DFS.getZeroShadow(&LI));
1967     return;
1968   }
1969 
1970   Align Alignment = ClPreserveAlignment ? LI.getAlign() : Align(1);
1971   Value *PrimitiveShadow =
1972       DFSF.loadShadow(LI.getPointerOperand(), Size, Alignment.value(), &LI);
1973   if (ClCombinePointerLabelsOnLoad) {
1974     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1975     PrimitiveShadow = DFSF.combineShadows(PrimitiveShadow, PtrShadow, &LI);
1976   }
1977   if (!DFSF.DFS.isZeroShadow(PrimitiveShadow))
1978     DFSF.NonZeroChecks.push_back(PrimitiveShadow);
1979 
1980   Value *Shadow =
1981       DFSF.expandFromPrimitiveShadow(LI.getType(), PrimitiveShadow, &LI);
1982   DFSF.setShadow(&LI, Shadow);
1983   if (ClEventCallbacks) {
1984     IRBuilder<> IRB(&LI);
1985     Value *Addr8 = IRB.CreateBitCast(LI.getPointerOperand(), DFSF.DFS.Int8Ptr);
1986     IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, {PrimitiveShadow, Addr8});
1987   }
1988 }
1989 
1990 void DFSanFunction::storePrimitiveShadow(Value *Addr, uint64_t Size,
1991                                          Align Alignment,
1992                                          Value *PrimitiveShadow,
1993                                          Instruction *Pos) {
1994   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1995     const auto i = AllocaShadowMap.find(AI);
1996     if (i != AllocaShadowMap.end()) {
1997       IRBuilder<> IRB(Pos);
1998       IRB.CreateStore(PrimitiveShadow, i->second);
1999       return;
2000     }
2001   }
2002 
2003   const Align ShadowAlign(Alignment.value() * DFS.ShadowWidthBytes);
2004   IRBuilder<> IRB(Pos);
2005   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
2006   if (DFS.isZeroShadow(PrimitiveShadow)) {
2007     IntegerType *ShadowTy =
2008         IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits);
2009     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
2010     Value *ExtShadowAddr =
2011         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
2012     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
2013     return;
2014   }
2015 
2016   const unsigned ShadowVecSize = 128 / DFS.ShadowWidthBits;
2017   uint64_t Offset = 0;
2018   if (Size >= ShadowVecSize) {
2019     auto *ShadowVecTy =
2020         FixedVectorType::get(DFS.PrimitiveShadowTy, ShadowVecSize);
2021     Value *ShadowVec = UndefValue::get(ShadowVecTy);
2022     for (unsigned i = 0; i != ShadowVecSize; ++i) {
2023       ShadowVec = IRB.CreateInsertElement(
2024           ShadowVec, PrimitiveShadow,
2025           ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
2026     }
2027     Value *ShadowVecAddr =
2028         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
2029     do {
2030       Value *CurShadowVecAddr =
2031           IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
2032       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
2033       Size -= ShadowVecSize;
2034       ++Offset;
2035     } while (Size >= ShadowVecSize);
2036     Offset *= ShadowVecSize;
2037   }
2038   while (Size > 0) {
2039     Value *CurShadowAddr =
2040         IRB.CreateConstGEP1_32(DFS.PrimitiveShadowTy, ShadowAddr, Offset);
2041     IRB.CreateAlignedStore(PrimitiveShadow, CurShadowAddr, ShadowAlign);
2042     --Size;
2043     ++Offset;
2044   }
2045 }
2046 
2047 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
2048   auto &DL = SI.getModule()->getDataLayout();
2049   uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
2050   if (Size == 0)
2051     return;
2052 
2053   const Align Alignment = ClPreserveAlignment ? SI.getAlign() : Align(1);
2054 
2055   Value* Shadow = DFSF.getShadow(SI.getValueOperand());
2056   Value *PrimitiveShadow;
2057   if (ClCombinePointerLabelsOnStore) {
2058     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
2059     PrimitiveShadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
2060   } else {
2061     PrimitiveShadow = DFSF.collapseToPrimitiveShadow(Shadow, &SI);
2062   }
2063   DFSF.storePrimitiveShadow(SI.getPointerOperand(), Size, Alignment,
2064                             PrimitiveShadow, &SI);
2065   if (ClEventCallbacks) {
2066     IRBuilder<> IRB(&SI);
2067     Value *Addr8 = IRB.CreateBitCast(SI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2068     IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, {PrimitiveShadow, Addr8});
2069   }
2070 }
2071 
2072 void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
2073   visitInstOperands(UO);
2074 }
2075 
2076 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
2077   visitInstOperands(BO);
2078 }
2079 
2080 void DFSanVisitor::visitCastInst(CastInst &CI) { visitInstOperands(CI); }
2081 
2082 void DFSanVisitor::visitCmpInst(CmpInst &CI) {
2083   visitInstOperands(CI);
2084   if (ClEventCallbacks) {
2085     IRBuilder<> IRB(&CI);
2086     Value *CombinedShadow = DFSF.getShadow(&CI);
2087     IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow);
2088   }
2089 }
2090 
2091 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2092   visitInstOperands(GEPI);
2093 }
2094 
2095 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
2096   visitInstOperands(I);
2097 }
2098 
2099 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
2100   visitInstOperands(I);
2101 }
2102 
2103 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
2104   visitInstOperands(I);
2105 }
2106 
2107 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
2108   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2109     visitInstOperands(I);
2110     return;
2111   }
2112 
2113   IRBuilder<> IRB(&I);
2114   Value *Agg = I.getAggregateOperand();
2115   Value *AggShadow = DFSF.getShadow(Agg);
2116   Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2117   DFSF.setShadow(&I, ResShadow);
2118   visitInstOperandOrigins(I);
2119 }
2120 
2121 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
2122   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2123     visitInstOperands(I);
2124     return;
2125   }
2126 
2127   IRBuilder<> IRB(&I);
2128   Value *AggShadow = DFSF.getShadow(I.getAggregateOperand());
2129   Value *InsShadow = DFSF.getShadow(I.getInsertedValueOperand());
2130   Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2131   DFSF.setShadow(&I, Res);
2132   visitInstOperandOrigins(I);
2133 }
2134 
2135 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
2136   bool AllLoadsStores = true;
2137   for (User *U : I.users()) {
2138     if (isa<LoadInst>(U))
2139       continue;
2140 
2141     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2142       if (SI->getPointerOperand() == &I)
2143         continue;
2144     }
2145 
2146     AllLoadsStores = false;
2147     break;
2148   }
2149   if (AllLoadsStores) {
2150     IRBuilder<> IRB(&I);
2151     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.PrimitiveShadowTy);
2152   }
2153   DFSF.setShadow(&I, DFSF.DFS.ZeroPrimitiveShadow);
2154 }
2155 
2156 void DFSanVisitor::visitSelectInst(SelectInst &I) {
2157   Value *CondShadow = DFSF.getShadow(I.getCondition());
2158   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
2159   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
2160   Value *ShadowSel = nullptr;
2161   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2162   std::vector<Value *> Shadows;
2163   std::vector<Value *> Origins;
2164   Value *TrueOrigin =
2165       ShouldTrackOrigins ? DFSF.getOrigin(I.getTrueValue()) : nullptr;
2166   Value *FalseOrigin =
2167       ShouldTrackOrigins ? DFSF.getOrigin(I.getFalseValue()) : nullptr;
2168 
2169   if (isa<VectorType>(I.getCondition()->getType())) {
2170     ShadowSel = DFSF.combineShadowsThenConvert(I.getType(), TrueShadow,
2171                                                FalseShadow, &I);
2172     if (ShouldTrackOrigins) {
2173       Shadows.push_back(TrueShadow);
2174       Shadows.push_back(FalseShadow);
2175       Origins.push_back(TrueOrigin);
2176       Origins.push_back(FalseOrigin);
2177     }
2178   } else {
2179     if (TrueShadow == FalseShadow) {
2180       ShadowSel = TrueShadow;
2181       if (ShouldTrackOrigins) {
2182         Shadows.push_back(TrueShadow);
2183         Origins.push_back(TrueOrigin);
2184       }
2185     } else {
2186       ShadowSel =
2187           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
2188       if (ShouldTrackOrigins) {
2189         Shadows.push_back(ShadowSel);
2190         Origins.push_back(SelectInst::Create(I.getCondition(), TrueOrigin,
2191                                              FalseOrigin, "", &I));
2192       }
2193     }
2194   }
2195   DFSF.setShadow(&I, ClTrackSelectControlFlow
2196                          ? DFSF.combineShadowsThenConvert(
2197                                I.getType(), CondShadow, ShadowSel, &I)
2198                          : ShadowSel);
2199   if (ShouldTrackOrigins) {
2200     if (ClTrackSelectControlFlow) {
2201       Shadows.push_back(CondShadow);
2202       Origins.push_back(DFSF.getOrigin(I.getCondition()));
2203     }
2204     DFSF.setOrigin(&I, DFSF.combineOrigins(Shadows, Origins, &I));
2205   }
2206 }
2207 
2208 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
2209   IRBuilder<> IRB(&I);
2210   Value *ValShadow = DFSF.getShadow(I.getValue());
2211   Value *ValOrigin = DFSF.DFS.shouldTrackOrigins()
2212                          ? DFSF.getOrigin(I.getValue())
2213                          : DFSF.DFS.ZeroOrigin;
2214   IRB.CreateCall(
2215       DFSF.DFS.DFSanSetLabelFn,
2216       {ValShadow, ValOrigin,
2217        IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
2218        IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2219 }
2220 
2221 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
2222   IRBuilder<> IRB(&I);
2223   Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
2224   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
2225   Value *LenShadow =
2226       IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(),
2227                                                     DFSF.DFS.ShadowWidthBytes));
2228   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
2229   Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr);
2230   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
2231   auto *MTI = cast<MemTransferInst>(
2232       IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
2233                      {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
2234   if (ClPreserveAlignment) {
2235     MTI->setDestAlignment(I.getDestAlign() * DFSF.DFS.ShadowWidthBytes);
2236     MTI->setSourceAlignment(I.getSourceAlign() * DFSF.DFS.ShadowWidthBytes);
2237   } else {
2238     MTI->setDestAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2239     MTI->setSourceAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2240   }
2241   if (ClEventCallbacks) {
2242     IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn,
2243                    {RawDestShadow, I.getLength()});
2244   }
2245 }
2246 
2247 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
2248   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
2249     switch (DFSF.IA) {
2250     case DataFlowSanitizer::IA_TLS: {
2251       Value *S = DFSF.getShadow(RI.getReturnValue());
2252       IRBuilder<> IRB(&RI);
2253       Type *RT = DFSF.F->getFunctionType()->getReturnType();
2254       unsigned Size =
2255           getDataLayout().getTypeAllocSize(DFSF.DFS.getShadowTy(RT));
2256       if (Size <= kRetvalTLSSize) {
2257         // If the size overflows, stores nothing. At callsite, oversized return
2258         // shadows are set to zero.
2259         IRB.CreateAlignedStore(S, DFSF.getRetvalTLS(RT, IRB),
2260                                kShadowTLSAlignment);
2261       }
2262       if (DFSF.DFS.shouldTrackOrigins()) {
2263         Value *O = DFSF.getOrigin(RI.getReturnValue());
2264         IRB.CreateStore(O, DFSF.getRetvalOriginTLS());
2265       }
2266       break;
2267     }
2268     case DataFlowSanitizer::IA_Args: {
2269       IRBuilder<> IRB(&RI);
2270       Type *RT = DFSF.F->getFunctionType()->getReturnType();
2271       Value *InsVal =
2272           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
2273       Value *InsShadow =
2274           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
2275       RI.setOperand(0, InsShadow);
2276       break;
2277     }
2278     }
2279   }
2280 }
2281 
2282 bool DFSanVisitor::visitWrappedCallBase(Function &F, CallBase &CB) {
2283   IRBuilder<> IRB(&CB);
2284   switch (DFSF.DFS.getWrapperKind(&F)) {
2285   case DataFlowSanitizer::WK_Warning:
2286     CB.setCalledFunction(&F);
2287     IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
2288                    IRB.CreateGlobalStringPtr(F.getName()));
2289     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2290     return true;
2291   case DataFlowSanitizer::WK_Discard:
2292     CB.setCalledFunction(&F);
2293     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2294     return true;
2295   case DataFlowSanitizer::WK_Functional:
2296     CB.setCalledFunction(&F);
2297     visitInstOperands(CB);
2298     return true;
2299   case DataFlowSanitizer::WK_Custom:
2300     // Don't try to handle invokes of custom functions, it's too complicated.
2301     // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
2302     // wrapper.
2303     CallInst *CI = dyn_cast<CallInst>(&CB);
2304     if (!CI)
2305       return false;
2306 
2307     FunctionType *FT = F.getFunctionType();
2308     TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
2309     std::string CustomFName = "__dfsw_";
2310     CustomFName += F.getName();
2311     FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
2312         CustomFName, CustomFn.TransformedType);
2313     if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
2314       CustomFn->copyAttributesFrom(&F);
2315 
2316       // Custom functions returning non-void will write to the return label.
2317       if (!FT->getReturnType()->isVoidTy()) {
2318         CustomFn->removeAttributes(AttributeList::FunctionIndex,
2319                                    DFSF.DFS.ReadOnlyNoneAttrs);
2320       }
2321     }
2322 
2323     std::vector<Value *> Args;
2324 
2325     // Adds non-variable arguments.
2326     auto *I = CB.arg_begin();
2327     for (unsigned n = FT->getNumParams(); n != 0; ++I, --n) {
2328       Type *T = (*I)->getType();
2329       FunctionType *ParamFT;
2330       if (isa<PointerType>(T) &&
2331           (ParamFT = dyn_cast<FunctionType>(
2332                cast<PointerType>(T)->getElementType()))) {
2333         std::string TName = "dfst";
2334         TName += utostr(FT->getNumParams() - n);
2335         TName += "$";
2336         TName += F.getName();
2337         Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
2338         Args.push_back(T);
2339         Args.push_back(
2340             IRB.CreateBitCast(*I, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
2341       } else {
2342         Args.push_back(*I);
2343       }
2344     }
2345 
2346     // Adds non-variable argument shadows.
2347     I = CB.arg_begin();
2348     const unsigned ShadowArgStart = Args.size();
2349     for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2350       Args.push_back(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB));
2351 
2352     // Adds variable argument shadows.
2353     if (FT->isVarArg()) {
2354       auto *LabelVATy = ArrayType::get(DFSF.DFS.PrimitiveShadowTy,
2355                                        CB.arg_size() - FT->getNumParams());
2356       auto *LabelVAAlloca =
2357           new AllocaInst(LabelVATy, getDataLayout().getAllocaAddrSpace(),
2358                          "labelva", &DFSF.F->getEntryBlock().front());
2359 
2360       for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2361         auto *LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, N);
2362         IRB.CreateStore(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB),
2363                         LabelVAPtr);
2364       }
2365 
2366       Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
2367     }
2368 
2369     // Adds the return value shadow.
2370     if (!FT->getReturnType()->isVoidTy()) {
2371       if (!DFSF.LabelReturnAlloca) {
2372         DFSF.LabelReturnAlloca = new AllocaInst(
2373             DFSF.DFS.PrimitiveShadowTy, getDataLayout().getAllocaAddrSpace(),
2374             "labelreturn", &DFSF.F->getEntryBlock().front());
2375       }
2376       Args.push_back(DFSF.LabelReturnAlloca);
2377     }
2378 
2379     // Adds variable arguments.
2380     append_range(Args, drop_begin(CB.args(), FT->getNumParams()));
2381 
2382     CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
2383     CustomCI->setCallingConv(CI->getCallingConv());
2384     CustomCI->setAttributes(TransformFunctionAttributes(
2385         CustomFn, CI->getContext(), CI->getAttributes()));
2386 
2387     // Update the parameter attributes of the custom call instruction to
2388     // zero extend the shadow parameters. This is required for targets
2389     // which consider PrimitiveShadowTy an illegal type.
2390     for (unsigned N = 0; N < FT->getNumParams(); N++) {
2391       const unsigned ArgNo = ShadowArgStart + N;
2392       if (CustomCI->getArgOperand(ArgNo)->getType() ==
2393           DFSF.DFS.PrimitiveShadowTy)
2394         CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
2395     }
2396 
2397     // Loads the return value shadow.
2398     if (!FT->getReturnType()->isVoidTy()) {
2399       LoadInst *LabelLoad =
2400           IRB.CreateLoad(DFSF.DFS.PrimitiveShadowTy, DFSF.LabelReturnAlloca);
2401       DFSF.setShadow(CustomCI, DFSF.expandFromPrimitiveShadow(
2402                                    FT->getReturnType(), LabelLoad, &CB));
2403     }
2404 
2405     CI->replaceAllUsesWith(CustomCI);
2406     CI->eraseFromParent();
2407     return true;
2408   }
2409   return false;
2410 }
2411 
2412 void DFSanVisitor::visitCallBase(CallBase &CB) {
2413   Function *F = CB.getCalledFunction();
2414   if ((F && F->isIntrinsic()) || CB.isInlineAsm()) {
2415     visitInstOperands(CB);
2416     return;
2417   }
2418 
2419   // Calls to this function are synthesized in wrappers, and we shouldn't
2420   // instrument them.
2421   if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
2422     return;
2423 
2424   DenseMap<Value *, Function *>::iterator i =
2425       DFSF.DFS.UnwrappedFnMap.find(CB.getCalledOperand());
2426   if (i != DFSF.DFS.UnwrappedFnMap.end())
2427     if (visitWrappedCallBase(*i->second, CB))
2428       return;
2429 
2430   IRBuilder<> IRB(&CB);
2431 
2432   FunctionType *FT = CB.getFunctionType();
2433   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
2434     // Stores argument shadows.
2435     unsigned ArgOffset = 0;
2436     const DataLayout &DL = getDataLayout();
2437     for (unsigned I = 0, N = FT->getNumParams(); I != N; ++I) {
2438       unsigned Size =
2439           DL.getTypeAllocSize(DFSF.DFS.getShadowTy(FT->getParamType(I)));
2440       // Stop storing if arguments' size overflows. Inside a function, arguments
2441       // after overflow have zero shadow values.
2442       if (ArgOffset + Size > kArgTLSSize)
2443         break;
2444       IRB.CreateAlignedStore(
2445           DFSF.getShadow(CB.getArgOperand(I)),
2446           DFSF.getArgTLS(FT->getParamType(I), ArgOffset, IRB),
2447           kShadowTLSAlignment);
2448       ArgOffset += alignTo(Size, kShadowTLSAlignment);
2449     }
2450   }
2451 
2452   Instruction *Next = nullptr;
2453   if (!CB.getType()->isVoidTy()) {
2454     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2455       if (II->getNormalDest()->getSinglePredecessor()) {
2456         Next = &II->getNormalDest()->front();
2457       } else {
2458         BasicBlock *NewBB =
2459             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
2460         Next = &NewBB->front();
2461       }
2462     } else {
2463       assert(CB.getIterator() != CB.getParent()->end());
2464       Next = CB.getNextNode();
2465     }
2466 
2467     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
2468       // Loads the return value shadow.
2469       IRBuilder<> NextIRB(Next);
2470       const DataLayout &DL = getDataLayout();
2471       unsigned Size = DL.getTypeAllocSize(DFSF.DFS.getShadowTy(&CB));
2472       if (Size > kRetvalTLSSize) {
2473         // Set overflowed return shadow to be zero.
2474         DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2475       } else {
2476         LoadInst *LI = NextIRB.CreateAlignedLoad(
2477             DFSF.DFS.getShadowTy(&CB), DFSF.getRetvalTLS(CB.getType(), NextIRB),
2478             kShadowTLSAlignment, "_dfsret");
2479         DFSF.SkipInsts.insert(LI);
2480         DFSF.setShadow(&CB, LI);
2481         DFSF.NonZeroChecks.push_back(LI);
2482       }
2483     }
2484   }
2485 
2486   // Do all instrumentation for IA_Args down here to defer tampering with the
2487   // CFG in a way that SplitEdge may be able to detect.
2488   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
2489     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
2490     Value *Func =
2491         IRB.CreateBitCast(CB.getCalledOperand(), PointerType::getUnqual(NewFT));
2492     std::vector<Value *> Args;
2493 
2494     auto i = CB.arg_begin(), E = CB.arg_end();
2495     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
2496       Args.push_back(*i);
2497 
2498     i = CB.arg_begin();
2499     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
2500       Args.push_back(DFSF.getShadow(*i));
2501 
2502     if (FT->isVarArg()) {
2503       unsigned VarArgSize = CB.arg_size() - FT->getNumParams();
2504       ArrayType *VarArgArrayTy =
2505           ArrayType::get(DFSF.DFS.PrimitiveShadowTy, VarArgSize);
2506       AllocaInst *VarArgShadow =
2507         new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
2508                        "", &DFSF.F->getEntryBlock().front());
2509       Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
2510       for (unsigned n = 0; i != E; ++i, ++n) {
2511         IRB.CreateStore(
2512             DFSF.getShadow(*i),
2513             IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
2514         Args.push_back(*i);
2515       }
2516     }
2517 
2518     CallBase *NewCB;
2519     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2520       NewCB = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
2521                                II->getUnwindDest(), Args);
2522     } else {
2523       NewCB = IRB.CreateCall(NewFT, Func, Args);
2524     }
2525     NewCB->setCallingConv(CB.getCallingConv());
2526     NewCB->setAttributes(CB.getAttributes().removeAttributes(
2527         *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
2528         AttributeFuncs::typeIncompatible(NewCB->getType())));
2529 
2530     if (Next) {
2531       ExtractValueInst *ExVal = ExtractValueInst::Create(NewCB, 0, "", Next);
2532       DFSF.SkipInsts.insert(ExVal);
2533       ExtractValueInst *ExShadow = ExtractValueInst::Create(NewCB, 1, "", Next);
2534       DFSF.SkipInsts.insert(ExShadow);
2535       DFSF.setShadow(ExVal, ExShadow);
2536       DFSF.NonZeroChecks.push_back(ExShadow);
2537 
2538       CB.replaceAllUsesWith(ExVal);
2539     }
2540 
2541     CB.eraseFromParent();
2542   }
2543 }
2544 
2545 void DFSanVisitor::visitPHINode(PHINode &PN) {
2546   Type *ShadowTy = DFSF.DFS.getShadowTy(&PN);
2547   PHINode *ShadowPN =
2548       PHINode::Create(ShadowTy, PN.getNumIncomingValues(), "", &PN);
2549 
2550   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
2551   Value *UndefShadow = UndefValue::get(ShadowTy);
2552   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
2553        ++i) {
2554     ShadowPN->addIncoming(UndefShadow, *i);
2555   }
2556 
2557   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
2558   DFSF.setShadow(&PN, ShadowPN);
2559 }
2560 
2561 namespace {
2562 class DataFlowSanitizerLegacyPass : public ModulePass {
2563 private:
2564   std::vector<std::string> ABIListFiles;
2565 
2566 public:
2567   static char ID;
2568 
2569   DataFlowSanitizerLegacyPass(
2570       const std::vector<std::string> &ABIListFiles = std::vector<std::string>())
2571       : ModulePass(ID), ABIListFiles(ABIListFiles) {}
2572 
2573   bool runOnModule(Module &M) override {
2574     return DataFlowSanitizer(ABIListFiles).runImpl(M);
2575   }
2576 };
2577 } // namespace
2578 
2579 char DataFlowSanitizerLegacyPass::ID;
2580 
2581 INITIALIZE_PASS(DataFlowSanitizerLegacyPass, "dfsan",
2582                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
2583 
2584 ModulePass *llvm::createDataFlowSanitizerLegacyPassPass(
2585     const std::vector<std::string> &ABIListFiles) {
2586   return new DataFlowSanitizerLegacyPass(ABIListFiles);
2587 }
2588 
2589 PreservedAnalyses DataFlowSanitizerPass::run(Module &M,
2590                                              ModuleAnalysisManager &AM) {
2591   if (DataFlowSanitizer(ABIListFiles).runImpl(M)) {
2592     return PreservedAnalyses::none();
2593   }
2594   return PreservedAnalyses::all();
2595 }
2596