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