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