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