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 
393 public:
394   static char ID;
395 
396   DataFlowSanitizer(
397       const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
398       void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
399 
400   bool doInitialization(Module &M) override;
401   bool runOnModule(Module &M) override;
402 };
403 
404 struct DFSanFunction {
405   DataFlowSanitizer &DFS;
406   Function *F;
407   DominatorTree DT;
408   DataFlowSanitizer::InstrumentedABI IA;
409   bool IsNativeABI;
410   Value *ArgTLSPtr = nullptr;
411   Value *RetvalTLSPtr = nullptr;
412   AllocaInst *LabelReturnAlloca = nullptr;
413   DenseMap<Value *, Value *> ValShadowMap;
414   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
415   std::vector<std::pair<PHINode *, PHINode *>> PHIFixups;
416   DenseSet<Instruction *> SkipInsts;
417   std::vector<Value *> NonZeroChecks;
418   bool AvoidNewBlocks;
419 
420   struct CachedCombinedShadow {
421     BasicBlock *Block;
422     Value *Shadow;
423   };
424   DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
425       CachedCombinedShadows;
426   DenseMap<Value *, std::set<Value *>> ShadowElements;
427 
428   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
429       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
430     DT.recalculate(*F);
431     // FIXME: Need to track down the register allocator issue which causes poor
432     // performance in pathological cases with large numbers of basic blocks.
433     AvoidNewBlocks = F->size() > 1000;
434   }
435 
436   Value *getArgTLSPtr();
437   Value *getArgTLS(unsigned Index, Instruction *Pos);
438   Value *getRetvalTLS();
439   Value *getShadow(Value *V);
440   void setShadow(Instruction *I, Value *Shadow);
441   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
442   Value *combineOperandShadows(Instruction *Inst);
443   Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
444                     Instruction *Pos);
445   void storeShadow(Value *Addr, uint64_t Size, Align Alignment, Value *Shadow,
446                    Instruction *Pos);
447 };
448 
449 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
450 public:
451   DFSanFunction &DFSF;
452 
453   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
454 
455   const DataLayout &getDataLayout() const {
456     return DFSF.F->getParent()->getDataLayout();
457   }
458 
459   // Combines shadow values for all of I's operands. Returns the combined shadow
460   // value.
461   Value *visitOperandShadowInst(Instruction &I);
462 
463   void visitUnaryOperator(UnaryOperator &UO);
464   void visitBinaryOperator(BinaryOperator &BO);
465   void visitCastInst(CastInst &CI);
466   void visitCmpInst(CmpInst &CI);
467   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
468   void visitLoadInst(LoadInst &LI);
469   void visitStoreInst(StoreInst &SI);
470   void visitReturnInst(ReturnInst &RI);
471   void visitCallBase(CallBase &CB);
472   void visitPHINode(PHINode &PN);
473   void visitExtractElementInst(ExtractElementInst &I);
474   void visitInsertElementInst(InsertElementInst &I);
475   void visitShuffleVectorInst(ShuffleVectorInst &I);
476   void visitExtractValueInst(ExtractValueInst &I);
477   void visitInsertValueInst(InsertValueInst &I);
478   void visitAllocaInst(AllocaInst &I);
479   void visitSelectInst(SelectInst &I);
480   void visitMemSetInst(MemSetInst &I);
481   void visitMemTransferInst(MemTransferInst &I);
482 };
483 
484 } // end anonymous namespace
485 
486 char DataFlowSanitizer::ID;
487 
488 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
489                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
490 
491 ModulePass *
492 llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
493                                   void *(*getArgTLS)(),
494                                   void *(*getRetValTLS)()) {
495   return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
496 }
497 
498 DataFlowSanitizer::DataFlowSanitizer(
499     const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
500     void *(*getRetValTLS)())
501     : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
502   std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
503   AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
504                          ClABIListFiles.end());
505   // FIXME: should we propagate vfs::FileSystem to this constructor?
506   ABIList.set(
507       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
508 }
509 
510 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
511   SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
512   ArgTypes.append(T->getNumParams(), ShadowTy);
513   if (T->isVarArg())
514     ArgTypes.push_back(ShadowPtrTy);
515   Type *RetType = T->getReturnType();
516   if (!RetType->isVoidTy())
517     RetType = StructType::get(RetType, ShadowTy);
518   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
519 }
520 
521 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
522   assert(!T->isVarArg());
523   SmallVector<Type *, 4> ArgTypes;
524   ArgTypes.push_back(T->getPointerTo());
525   ArgTypes.append(T->param_begin(), T->param_end());
526   ArgTypes.append(T->getNumParams(), ShadowTy);
527   Type *RetType = T->getReturnType();
528   if (!RetType->isVoidTy())
529     ArgTypes.push_back(ShadowPtrTy);
530   return FunctionType::get(T->getReturnType(), ArgTypes, false);
531 }
532 
533 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
534   SmallVector<Type *, 4> ArgTypes;
535 
536   // Some parameters of the custom function being constructed are
537   // parameters of T.  Record the mapping from parameters of T to
538   // parameters of the custom function, so that parameter attributes
539   // at call sites can be updated.
540   std::vector<unsigned> ArgumentIndexMapping;
541   for (unsigned i = 0, ie = T->getNumParams(); i != ie; ++i) {
542     Type* param_type = T->getParamType(i);
543     FunctionType *FT;
544     if (isa<PointerType>(param_type) && (FT = dyn_cast<FunctionType>(
545             cast<PointerType>(param_type)->getElementType()))) {
546       ArgumentIndexMapping.push_back(ArgTypes.size());
547       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
548       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
549     } else {
550       ArgumentIndexMapping.push_back(ArgTypes.size());
551       ArgTypes.push_back(param_type);
552     }
553   }
554   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
555     ArgTypes.push_back(ShadowTy);
556   if (T->isVarArg())
557     ArgTypes.push_back(ShadowPtrTy);
558   Type *RetType = T->getReturnType();
559   if (!RetType->isVoidTy())
560     ArgTypes.push_back(ShadowPtrTy);
561   return TransformedFunction(
562       T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
563       ArgumentIndexMapping);
564 }
565 
566 bool DataFlowSanitizer::doInitialization(Module &M) {
567   Triple TargetTriple(M.getTargetTriple());
568   bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
569   bool IsMIPS64 = TargetTriple.isMIPS64();
570   bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||
571                    TargetTriple.getArch() == Triple::aarch64_be;
572 
573   const DataLayout &DL = M.getDataLayout();
574 
575   Mod = &M;
576   Ctx = &M.getContext();
577   ShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
578   ShadowPtrTy = PointerType::getUnqual(ShadowTy);
579   IntptrTy = DL.getIntPtrType(*Ctx);
580   ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
581   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidthBytes);
582   if (IsX86_64)
583     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
584   else if (IsMIPS64)
585     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
586   // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
587   else if (IsAArch64)
588     DFSanRuntimeShadowMask = true;
589   else
590     report_fatal_error("unsupported triple");
591 
592   Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
593   DFSanUnionFnTy =
594       FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
595   Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
596   DFSanUnionLoadFnTy =
597       FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
598   DFSanUnimplementedFnTy = FunctionType::get(
599       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
600   Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
601   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
602                                         DFSanSetLabelArgs, /*isVarArg=*/false);
603   DFSanNonzeroLabelFnTy = FunctionType::get(
604       Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
605   DFSanVarargWrapperFnTy = FunctionType::get(
606       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
607   DFSanLoadStoreCmpCallbackFnTy =
608       FunctionType::get(Type::getVoidTy(*Ctx), ShadowTy, /*isVarArg=*/false);
609   Type *DFSanMemTransferCallbackArgs[2] = {ShadowPtrTy, IntptrTy};
610   DFSanMemTransferCallbackFnTy =
611       FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs,
612                         /*isVarArg=*/false);
613 
614   if (GetArgTLSPtr) {
615     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
616     ArgTLS = nullptr;
617     GetArgTLSTy = FunctionType::get(PointerType::getUnqual(ArgTLSTy), false);
618     GetArgTLS = ConstantExpr::getIntToPtr(
619         ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
620         PointerType::getUnqual(GetArgTLSTy));
621   }
622   if (GetRetvalTLSPtr) {
623     RetvalTLS = nullptr;
624     GetRetvalTLSTy = FunctionType::get(PointerType::getUnqual(ShadowTy), false);
625     GetRetvalTLS = ConstantExpr::getIntToPtr(
626         ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
627         PointerType::getUnqual(GetRetvalTLSTy));
628   }
629 
630   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
631   return true;
632 }
633 
634 bool DataFlowSanitizer::isInstrumented(const Function *F) {
635   return !ABIList.isIn(*F, "uninstrumented");
636 }
637 
638 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
639   return !ABIList.isIn(*GA, "uninstrumented");
640 }
641 
642 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
643   return ClArgsABI ? IA_Args : IA_TLS;
644 }
645 
646 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
647   if (ABIList.isIn(*F, "functional"))
648     return WK_Functional;
649   if (ABIList.isIn(*F, "discard"))
650     return WK_Discard;
651   if (ABIList.isIn(*F, "custom"))
652     return WK_Custom;
653 
654   return WK_Warning;
655 }
656 
657 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
658   std::string GVName = std::string(GV->getName()), Prefix = "dfs$";
659   GV->setName(Prefix + GVName);
660 
661   // Try to change the name of the function in module inline asm.  We only do
662   // this for specific asm directives, currently only ".symver", to try to avoid
663   // corrupting asm which happens to contain the symbol name as a substring.
664   // Note that the substitution for .symver assumes that the versioned symbol
665   // also has an instrumented name.
666   std::string Asm = GV->getParent()->getModuleInlineAsm();
667   std::string SearchStr = ".symver " + GVName + ",";
668   size_t Pos = Asm.find(SearchStr);
669   if (Pos != std::string::npos) {
670     Asm.replace(Pos, SearchStr.size(),
671                 ".symver " + Prefix + GVName + "," + Prefix);
672     GV->getParent()->setModuleInlineAsm(Asm);
673   }
674 }
675 
676 Function *
677 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
678                                         GlobalValue::LinkageTypes NewFLink,
679                                         FunctionType *NewFT) {
680   FunctionType *FT = F->getFunctionType();
681   Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
682                                     NewFName, F->getParent());
683   NewF->copyAttributesFrom(F);
684   NewF->removeAttributes(
685       AttributeList::ReturnIndex,
686       AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
687 
688   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
689   if (F->isVarArg()) {
690     NewF->removeAttributes(AttributeList::FunctionIndex,
691                            AttrBuilder().addAttribute("split-stack"));
692     CallInst::Create(DFSanVarargWrapperFn,
693                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
694                      BB);
695     new UnreachableInst(*Ctx, BB);
696   } else {
697     std::vector<Value *> Args;
698     unsigned n = FT->getNumParams();
699     for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
700       Args.push_back(&*ai);
701     CallInst *CI = CallInst::Create(F, Args, "", BB);
702     if (FT->getReturnType()->isVoidTy())
703       ReturnInst::Create(*Ctx, BB);
704     else
705       ReturnInst::Create(*Ctx, CI, BB);
706   }
707 
708   return NewF;
709 }
710 
711 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
712                                                           StringRef FName) {
713   FunctionType *FTT = getTrampolineFunctionType(FT);
714   FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
715   Function *F = dyn_cast<Function>(C.getCallee());
716   if (F && F->isDeclaration()) {
717     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
718     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
719     std::vector<Value *> Args;
720     Function::arg_iterator AI = F->arg_begin(); ++AI;
721     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
722       Args.push_back(&*AI);
723     CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
724     ReturnInst *RI;
725     if (FT->getReturnType()->isVoidTy())
726       RI = ReturnInst::Create(*Ctx, BB);
727     else
728       RI = ReturnInst::Create(*Ctx, CI, BB);
729 
730     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
731     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
732     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
733       DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
734     DFSanVisitor(DFSF).visitCallInst(*CI);
735     if (!FT->getReturnType()->isVoidTy())
736       new StoreInst(DFSF.getShadow(RI->getReturnValue()),
737                     &*std::prev(F->arg_end()), RI);
738   }
739 
740   return cast<Constant>(C.getCallee());
741 }
742 
743 bool DataFlowSanitizer::runOnModule(Module &M) {
744   if (ABIList.isIn(M, "skip"))
745     return false;
746 
747   if (!GetArgTLSPtr) {
748     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
749     ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
750     if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
751       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
752   }
753   if (!GetRetvalTLSPtr) {
754     RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
755     if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
756       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
757   }
758 
759   ExternalShadowMask =
760       Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
761 
762   {
763     AttributeList AL;
764     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
765                          Attribute::NoUnwind);
766     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
767                          Attribute::ReadNone);
768     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
769                          Attribute::ZExt);
770     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
771     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
772     DFSanUnionFn =
773         Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL);
774   }
775 
776   {
777     AttributeList AL;
778     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
779                          Attribute::NoUnwind);
780     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
781                          Attribute::ReadNone);
782     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
783                          Attribute::ZExt);
784     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
785     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
786     DFSanCheckedUnionFn =
787         Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL);
788   }
789   {
790     AttributeList AL;
791     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
792                          Attribute::NoUnwind);
793     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
794                          Attribute::ReadOnly);
795     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
796                          Attribute::ZExt);
797     DFSanUnionLoadFn =
798         Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
799   }
800   DFSanUnimplementedFn =
801       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
802   {
803     AttributeList AL;
804     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
805     DFSanSetLabelFn =
806         Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
807   }
808   DFSanNonzeroLabelFn =
809       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
810   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
811                                                   DFSanVarargWrapperFnTy);
812 
813   DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback",
814                                                  DFSanLoadStoreCmpCallbackFnTy);
815   DFSanStoreCallbackFn = Mod->getOrInsertFunction(
816       "__dfsan_store_callback", DFSanLoadStoreCmpCallbackFnTy);
817   DFSanMemTransferCallbackFn = Mod->getOrInsertFunction(
818       "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy);
819   DFSanCmpCallbackFn = Mod->getOrInsertFunction("__dfsan_cmp_callback",
820                                                 DFSanLoadStoreCmpCallbackFnTy);
821 
822   std::vector<Function *> FnsToInstrument;
823   SmallPtrSet<Function *, 2> FnsWithNativeABI;
824   for (Function &i : M) {
825     if (!i.isIntrinsic() &&
826         &i != DFSanUnionFn.getCallee()->stripPointerCasts() &&
827         &i != DFSanCheckedUnionFn.getCallee()->stripPointerCasts() &&
828         &i != DFSanUnionLoadFn.getCallee()->stripPointerCasts() &&
829         &i != DFSanUnimplementedFn.getCallee()->stripPointerCasts() &&
830         &i != DFSanSetLabelFn.getCallee()->stripPointerCasts() &&
831         &i != DFSanNonzeroLabelFn.getCallee()->stripPointerCasts() &&
832         &i != DFSanVarargWrapperFn.getCallee()->stripPointerCasts() &&
833         &i != DFSanLoadCallbackFn.getCallee()->stripPointerCasts() &&
834         &i != DFSanStoreCallbackFn.getCallee()->stripPointerCasts() &&
835         &i != DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts() &&
836         &i != DFSanCmpCallbackFn.getCallee()->stripPointerCasts())
837       FnsToInstrument.push_back(&i);
838   }
839 
840   // Give function aliases prefixes when necessary, and build wrappers where the
841   // instrumentedness is inconsistent.
842   for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
843     GlobalAlias *GA = &*i;
844     ++i;
845     // Don't stop on weak.  We assume people aren't playing games with the
846     // instrumentedness of overridden weak aliases.
847     if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
848       bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
849       if (GAInst && FInst) {
850         addGlobalNamePrefix(GA);
851       } else if (GAInst != FInst) {
852         // Non-instrumented alias of an instrumented function, or vice versa.
853         // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
854         // below will take care of instrumenting it.
855         Function *NewF =
856             buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
857         GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
858         NewF->takeName(GA);
859         GA->eraseFromParent();
860         FnsToInstrument.push_back(NewF);
861       }
862     }
863   }
864 
865   ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
866       .addAttribute(Attribute::ReadNone);
867 
868   // First, change the ABI of every function in the module.  ABI-listed
869   // functions keep their original ABI and get a wrapper function.
870   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
871                                          e = FnsToInstrument.end();
872        i != e; ++i) {
873     Function &F = **i;
874     FunctionType *FT = F.getFunctionType();
875 
876     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
877                               FT->getReturnType()->isVoidTy());
878 
879     if (isInstrumented(&F)) {
880       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
881       // easily identify cases of mismatching ABIs.
882       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
883         FunctionType *NewFT = getArgsFunctionType(FT);
884         Function *NewF = Function::Create(NewFT, F.getLinkage(),
885                                           F.getAddressSpace(), "", &M);
886         NewF->copyAttributesFrom(&F);
887         NewF->removeAttributes(
888             AttributeList::ReturnIndex,
889             AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
890         for (Function::arg_iterator FArg = F.arg_begin(),
891                                     NewFArg = NewF->arg_begin(),
892                                     FArgEnd = F.arg_end();
893              FArg != FArgEnd; ++FArg, ++NewFArg) {
894           FArg->replaceAllUsesWith(&*NewFArg);
895         }
896         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
897 
898         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
899              UI != UE;) {
900           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
901           ++UI;
902           if (BA) {
903             BA->replaceAllUsesWith(
904                 BlockAddress::get(NewF, BA->getBasicBlock()));
905             delete BA;
906           }
907         }
908         F.replaceAllUsesWith(
909             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
910         NewF->takeName(&F);
911         F.eraseFromParent();
912         *i = NewF;
913         addGlobalNamePrefix(NewF);
914       } else {
915         addGlobalNamePrefix(&F);
916       }
917     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
918       // Build a wrapper function for F.  The wrapper simply calls F, and is
919       // added to FnsToInstrument so that any instrumentation according to its
920       // WrapperKind is done in the second pass below.
921       FunctionType *NewFT = getInstrumentedABI() == IA_Args
922                                 ? getArgsFunctionType(FT)
923                                 : FT;
924 
925       // If the function being wrapped has local linkage, then preserve the
926       // function's linkage in the wrapper function.
927       GlobalValue::LinkageTypes wrapperLinkage =
928           F.hasLocalLinkage()
929               ? F.getLinkage()
930               : GlobalValue::LinkOnceODRLinkage;
931 
932       Function *NewF = buildWrapperFunction(
933           &F, std::string("dfsw$") + std::string(F.getName()),
934           wrapperLinkage, NewFT);
935       if (getInstrumentedABI() == IA_TLS)
936         NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
937 
938       Value *WrappedFnCst =
939           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
940       F.replaceAllUsesWith(WrappedFnCst);
941 
942       UnwrappedFnMap[WrappedFnCst] = &F;
943       *i = NewF;
944 
945       if (!F.isDeclaration()) {
946         // This function is probably defining an interposition of an
947         // uninstrumented function and hence needs to keep the original ABI.
948         // But any functions it may call need to use the instrumented ABI, so
949         // we instrument it in a mode which preserves the original ABI.
950         FnsWithNativeABI.insert(&F);
951 
952         // This code needs to rebuild the iterators, as they may be invalidated
953         // by the push_back, taking care that the new range does not include
954         // any functions added by this code.
955         size_t N = i - FnsToInstrument.begin(),
956                Count = e - FnsToInstrument.begin();
957         FnsToInstrument.push_back(&F);
958         i = FnsToInstrument.begin() + N;
959         e = FnsToInstrument.begin() + Count;
960       }
961                // Hopefully, nobody will try to indirectly call a vararg
962                // function... yet.
963     } else if (FT->isVarArg()) {
964       UnwrappedFnMap[&F] = &F;
965       *i = nullptr;
966     }
967   }
968 
969   for (Function *i : FnsToInstrument) {
970     if (!i || i->isDeclaration())
971       continue;
972 
973     removeUnreachableBlocks(*i);
974 
975     DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
976 
977     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
978     // Build a copy of the list before iterating over it.
979     SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
980 
981     for (BasicBlock *i : BBList) {
982       Instruction *Inst = &i->front();
983       while (true) {
984         // DFSanVisitor may split the current basic block, changing the current
985         // instruction's next pointer and moving the next instruction to the
986         // tail block from which we should continue.
987         Instruction *Next = Inst->getNextNode();
988         // DFSanVisitor may delete Inst, so keep track of whether it was a
989         // terminator.
990         bool IsTerminator = Inst->isTerminator();
991         if (!DFSF.SkipInsts.count(Inst))
992           DFSanVisitor(DFSF).visit(Inst);
993         if (IsTerminator)
994           break;
995         Inst = Next;
996       }
997     }
998 
999     // We will not necessarily be able to compute the shadow for every phi node
1000     // until we have visited every block.  Therefore, the code that handles phi
1001     // nodes adds them to the PHIFixups list so that they can be properly
1002     // handled here.
1003     for (std::vector<std::pair<PHINode *, PHINode *>>::iterator
1004              i = DFSF.PHIFixups.begin(),
1005              e = DFSF.PHIFixups.end();
1006          i != e; ++i) {
1007       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
1008            ++val) {
1009         i->second->setIncomingValue(
1010             val, DFSF.getShadow(i->first->getIncomingValue(val)));
1011       }
1012     }
1013 
1014     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
1015     // places (i.e. instructions in basic blocks we haven't even begun visiting
1016     // yet).  To make our life easier, do this work in a pass after the main
1017     // instrumentation.
1018     if (ClDebugNonzeroLabels) {
1019       for (Value *V : DFSF.NonZeroChecks) {
1020         Instruction *Pos;
1021         if (Instruction *I = dyn_cast<Instruction>(V))
1022           Pos = I->getNextNode();
1023         else
1024           Pos = &DFSF.F->getEntryBlock().front();
1025         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
1026           Pos = Pos->getNextNode();
1027         IRBuilder<> IRB(Pos);
1028         Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
1029         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1030             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
1031         IRBuilder<> ThenIRB(BI);
1032         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1033       }
1034     }
1035   }
1036 
1037   return false;
1038 }
1039 
1040 Value *DFSanFunction::getArgTLSPtr() {
1041   if (ArgTLSPtr)
1042     return ArgTLSPtr;
1043   if (DFS.ArgTLS)
1044     return ArgTLSPtr = DFS.ArgTLS;
1045 
1046   IRBuilder<> IRB(&F->getEntryBlock().front());
1047   return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLSTy, DFS.GetArgTLS, {});
1048 }
1049 
1050 Value *DFSanFunction::getRetvalTLS() {
1051   if (RetvalTLSPtr)
1052     return RetvalTLSPtr;
1053   if (DFS.RetvalTLS)
1054     return RetvalTLSPtr = DFS.RetvalTLS;
1055 
1056   IRBuilder<> IRB(&F->getEntryBlock().front());
1057   return RetvalTLSPtr =
1058              IRB.CreateCall(DFS.GetRetvalTLSTy, DFS.GetRetvalTLS, {});
1059 }
1060 
1061 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
1062   IRBuilder<> IRB(Pos);
1063   return IRB.CreateConstGEP2_64(ArrayType::get(DFS.ShadowTy, 64),
1064                                 getArgTLSPtr(), 0, Idx);
1065 }
1066 
1067 Value *DFSanFunction::getShadow(Value *V) {
1068   if (!isa<Argument>(V) && !isa<Instruction>(V))
1069     return DFS.ZeroShadow;
1070   Value *&Shadow = ValShadowMap[V];
1071   if (!Shadow) {
1072     if (Argument *A = dyn_cast<Argument>(V)) {
1073       if (IsNativeABI)
1074         return DFS.ZeroShadow;
1075       switch (IA) {
1076       case DataFlowSanitizer::IA_TLS: {
1077         Value *ArgTLSPtr = getArgTLSPtr();
1078         Instruction *ArgTLSPos =
1079             DFS.ArgTLS ? &*F->getEntryBlock().begin()
1080                        : cast<Instruction>(ArgTLSPtr)->getNextNode();
1081         IRBuilder<> IRB(ArgTLSPos);
1082         Shadow =
1083             IRB.CreateLoad(DFS.ShadowTy, getArgTLS(A->getArgNo(), ArgTLSPos));
1084         break;
1085       }
1086       case DataFlowSanitizer::IA_Args: {
1087         unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
1088         Function::arg_iterator i = F->arg_begin();
1089         while (ArgIdx--)
1090           ++i;
1091         Shadow = &*i;
1092         assert(Shadow->getType() == DFS.ShadowTy);
1093         break;
1094       }
1095       }
1096       NonZeroChecks.push_back(Shadow);
1097     } else {
1098       Shadow = DFS.ZeroShadow;
1099     }
1100   }
1101   return Shadow;
1102 }
1103 
1104 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1105   assert(!ValShadowMap.count(I));
1106   assert(Shadow->getType() == DFS.ShadowTy);
1107   ValShadowMap[I] = Shadow;
1108 }
1109 
1110 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1111   assert(Addr != RetvalTLS && "Reinstrumenting?");
1112   IRBuilder<> IRB(Pos);
1113   Value *ShadowPtrMaskValue;
1114   if (DFSanRuntimeShadowMask)
1115     ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
1116   else
1117     ShadowPtrMaskValue = ShadowPtrMask;
1118   return IRB.CreateIntToPtr(
1119       IRB.CreateMul(
1120           IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
1121                         IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)),
1122           ShadowPtrMul),
1123       ShadowPtrTy);
1124 }
1125 
1126 // Generates IR to compute the union of the two given shadows, inserting it
1127 // before Pos.  Returns the computed union Value.
1128 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1129   if (V1 == DFS.ZeroShadow)
1130     return V2;
1131   if (V2 == DFS.ZeroShadow)
1132     return V1;
1133   if (V1 == V2)
1134     return V1;
1135 
1136   auto V1Elems = ShadowElements.find(V1);
1137   auto V2Elems = ShadowElements.find(V2);
1138   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1139     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1140                       V2Elems->second.begin(), V2Elems->second.end())) {
1141       return V1;
1142     } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1143                              V1Elems->second.begin(), V1Elems->second.end())) {
1144       return V2;
1145     }
1146   } else if (V1Elems != ShadowElements.end()) {
1147     if (V1Elems->second.count(V2))
1148       return V1;
1149   } else if (V2Elems != ShadowElements.end()) {
1150     if (V2Elems->second.count(V1))
1151       return V2;
1152   }
1153 
1154   auto Key = std::make_pair(V1, V2);
1155   if (V1 > V2)
1156     std::swap(Key.first, Key.second);
1157   CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
1158   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1159     return CCS.Shadow;
1160 
1161   IRBuilder<> IRB(Pos);
1162   if (AvoidNewBlocks) {
1163     CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
1164     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1165     Call->addParamAttr(0, Attribute::ZExt);
1166     Call->addParamAttr(1, Attribute::ZExt);
1167 
1168     CCS.Block = Pos->getParent();
1169     CCS.Shadow = Call;
1170   } else {
1171     BasicBlock *Head = Pos->getParent();
1172     Value *Ne = IRB.CreateICmpNE(V1, V2);
1173     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1174         Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1175     IRBuilder<> ThenIRB(BI);
1176     CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
1177     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1178     Call->addParamAttr(0, Attribute::ZExt);
1179     Call->addParamAttr(1, Attribute::ZExt);
1180 
1181     BasicBlock *Tail = BI->getSuccessor(0);
1182     PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1183     Phi->addIncoming(Call, Call->getParent());
1184     Phi->addIncoming(V1, Head);
1185 
1186     CCS.Block = Tail;
1187     CCS.Shadow = Phi;
1188   }
1189 
1190   std::set<Value *> UnionElems;
1191   if (V1Elems != ShadowElements.end()) {
1192     UnionElems = V1Elems->second;
1193   } else {
1194     UnionElems.insert(V1);
1195   }
1196   if (V2Elems != ShadowElements.end()) {
1197     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1198   } else {
1199     UnionElems.insert(V2);
1200   }
1201   ShadowElements[CCS.Shadow] = std::move(UnionElems);
1202 
1203   return CCS.Shadow;
1204 }
1205 
1206 // A convenience function which folds the shadows of each of the operands
1207 // of the provided instruction Inst, inserting the IR before Inst.  Returns
1208 // the computed union Value.
1209 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1210   if (Inst->getNumOperands() == 0)
1211     return DFS.ZeroShadow;
1212 
1213   Value *Shadow = getShadow(Inst->getOperand(0));
1214   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
1215     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1216   }
1217   return Shadow;
1218 }
1219 
1220 Value *DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1221   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1222   DFSF.setShadow(&I, CombinedShadow);
1223   return CombinedShadow;
1224 }
1225 
1226 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1227 // Addr has alignment Align, and take the union of each of those shadows.
1228 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1229                                  Instruction *Pos) {
1230   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1231     const auto i = AllocaShadowMap.find(AI);
1232     if (i != AllocaShadowMap.end()) {
1233       IRBuilder<> IRB(Pos);
1234       return IRB.CreateLoad(DFS.ShadowTy, i->second);
1235     }
1236   }
1237 
1238   const llvm::Align ShadowAlign(Align * DFS.ShadowWidthBytes);
1239   SmallVector<const Value *, 2> Objs;
1240   GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
1241   bool AllConstants = true;
1242   for (const Value *Obj : Objs) {
1243     if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
1244       continue;
1245     if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
1246       continue;
1247 
1248     AllConstants = false;
1249     break;
1250   }
1251   if (AllConstants)
1252     return DFS.ZeroShadow;
1253 
1254   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1255   switch (Size) {
1256   case 0:
1257     return DFS.ZeroShadow;
1258   case 1: {
1259     LoadInst *LI = new LoadInst(DFS.ShadowTy, ShadowAddr, "", Pos);
1260     LI->setAlignment(ShadowAlign);
1261     return LI;
1262   }
1263   case 2: {
1264     IRBuilder<> IRB(Pos);
1265     Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1266                                        ConstantInt::get(DFS.IntptrTy, 1));
1267     return combineShadows(
1268         IRB.CreateAlignedLoad(DFS.ShadowTy, ShadowAddr, ShadowAlign),
1269         IRB.CreateAlignedLoad(DFS.ShadowTy, ShadowAddr1, ShadowAlign), Pos);
1270   }
1271   }
1272   if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidthBits) == 0) {
1273     // Fast path for the common case where each byte has identical shadow: load
1274     // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1275     // shadow is non-equal.
1276     BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1277     IRBuilder<> FallbackIRB(FallbackBB);
1278     CallInst *FallbackCall = FallbackIRB.CreateCall(
1279         DFS.DFSanUnionLoadFn,
1280         {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1281     FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1282 
1283     // Compare each of the shadows stored in the loaded 64 bits to each other,
1284     // by computing (WideShadow rotl ShadowWidthBits) == WideShadow.
1285     IRBuilder<> IRB(Pos);
1286     Value *WideAddr =
1287         IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1288     Value *WideShadow =
1289         IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1290     Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1291     Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidthBits);
1292     Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidthBits);
1293     Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1294     Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1295 
1296     BasicBlock *Head = Pos->getParent();
1297     BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
1298 
1299     if (DomTreeNode *OldNode = DT.getNode(Head)) {
1300       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1301 
1302       DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1303       for (auto Child : Children)
1304         DT.changeImmediateDominator(Child, NewNode);
1305     }
1306 
1307     // In the following code LastBr will refer to the previous basic block's
1308     // conditional branch instruction, whose true successor is fixed up to point
1309     // to the next block during the loop below or to the tail after the final
1310     // iteration.
1311     BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1312     ReplaceInstWithInst(Head->getTerminator(), LastBr);
1313     DT.addNewBlock(FallbackBB, Head);
1314 
1315     for (uint64_t Ofs = 64 / DFS.ShadowWidthBits; Ofs != Size;
1316          Ofs += 64 / DFS.ShadowWidthBits) {
1317       BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1318       DT.addNewBlock(NextBB, LastBr->getParent());
1319       IRBuilder<> NextIRB(NextBB);
1320       WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1321                                    ConstantInt::get(DFS.IntptrTy, 1));
1322       Value *NextWideShadow = NextIRB.CreateAlignedLoad(NextIRB.getInt64Ty(),
1323                                                         WideAddr, ShadowAlign);
1324       ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1325       LastBr->setSuccessor(0, NextBB);
1326       LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1327     }
1328 
1329     LastBr->setSuccessor(0, Tail);
1330     FallbackIRB.CreateBr(Tail);
1331     PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1332     Shadow->addIncoming(FallbackCall, FallbackBB);
1333     Shadow->addIncoming(TruncShadow, LastBr->getParent());
1334     return Shadow;
1335   }
1336 
1337   IRBuilder<> IRB(Pos);
1338   CallInst *FallbackCall = IRB.CreateCall(
1339       DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1340   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1341   return FallbackCall;
1342 }
1343 
1344 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1345   auto &DL = LI.getModule()->getDataLayout();
1346   uint64_t Size = DL.getTypeStoreSize(LI.getType());
1347   if (Size == 0) {
1348     DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1349     return;
1350   }
1351 
1352   uint64_t Align;
1353   if (ClPreserveAlignment) {
1354     Align = LI.getAlignment();
1355     if (Align == 0)
1356       Align = DL.getABITypeAlignment(LI.getType());
1357   } else {
1358     Align = 1;
1359   }
1360   Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1361   if (ClCombinePointerLabelsOnLoad) {
1362     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1363     Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
1364   }
1365   if (Shadow != DFSF.DFS.ZeroShadow)
1366     DFSF.NonZeroChecks.push_back(Shadow);
1367 
1368   DFSF.setShadow(&LI, Shadow);
1369   if (ClEventCallbacks) {
1370     IRBuilder<> IRB(&LI);
1371     IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, Shadow);
1372   }
1373 }
1374 
1375 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, Align Alignment,
1376                                 Value *Shadow, Instruction *Pos) {
1377   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1378     const auto i = AllocaShadowMap.find(AI);
1379     if (i != AllocaShadowMap.end()) {
1380       IRBuilder<> IRB(Pos);
1381       IRB.CreateStore(Shadow, i->second);
1382       return;
1383     }
1384   }
1385 
1386   const Align ShadowAlign(Alignment.value() * DFS.ShadowWidthBytes);
1387   IRBuilder<> IRB(Pos);
1388   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1389   if (Shadow == DFS.ZeroShadow) {
1390     IntegerType *ShadowTy =
1391         IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits);
1392     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1393     Value *ExtShadowAddr =
1394         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1395     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1396     return;
1397   }
1398 
1399   const unsigned ShadowVecSize = 128 / DFS.ShadowWidthBits;
1400   uint64_t Offset = 0;
1401   if (Size >= ShadowVecSize) {
1402     VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1403     Value *ShadowVec = UndefValue::get(ShadowVecTy);
1404     for (unsigned i = 0; i != ShadowVecSize; ++i) {
1405       ShadowVec = IRB.CreateInsertElement(
1406           ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1407     }
1408     Value *ShadowVecAddr =
1409         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1410     do {
1411       Value *CurShadowVecAddr =
1412           IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
1413       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1414       Size -= ShadowVecSize;
1415       ++Offset;
1416     } while (Size >= ShadowVecSize);
1417     Offset *= ShadowVecSize;
1418   }
1419   while (Size > 0) {
1420     Value *CurShadowAddr =
1421         IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
1422     IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1423     --Size;
1424     ++Offset;
1425   }
1426 }
1427 
1428 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1429   auto &DL = SI.getModule()->getDataLayout();
1430   uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
1431   if (Size == 0)
1432     return;
1433 
1434   const Align Alignement =
1435       ClPreserveAlignment ? DL.getValueOrABITypeAlignment(
1436                                 SI.getAlign(), SI.getValueOperand()->getType())
1437                           : Align(1);
1438 
1439   Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1440   if (ClCombinePointerLabelsOnStore) {
1441     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1442     Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1443   }
1444   DFSF.storeShadow(SI.getPointerOperand(), Size, Alignement, Shadow, &SI);
1445   if (ClEventCallbacks) {
1446     IRBuilder<> IRB(&SI);
1447     IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, Shadow);
1448   }
1449 }
1450 
1451 void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
1452   visitOperandShadowInst(UO);
1453 }
1454 
1455 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1456   visitOperandShadowInst(BO);
1457 }
1458 
1459 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1460 
1461 void DFSanVisitor::visitCmpInst(CmpInst &CI) {
1462   Value *CombinedShadow = visitOperandShadowInst(CI);
1463   if (ClEventCallbacks) {
1464     IRBuilder<> IRB(&CI);
1465     IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow);
1466   }
1467 }
1468 
1469 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1470   visitOperandShadowInst(GEPI);
1471 }
1472 
1473 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1474   visitOperandShadowInst(I);
1475 }
1476 
1477 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1478   visitOperandShadowInst(I);
1479 }
1480 
1481 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1482   visitOperandShadowInst(I);
1483 }
1484 
1485 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1486   visitOperandShadowInst(I);
1487 }
1488 
1489 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1490   visitOperandShadowInst(I);
1491 }
1492 
1493 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1494   bool AllLoadsStores = true;
1495   for (User *U : I.users()) {
1496     if (isa<LoadInst>(U))
1497       continue;
1498 
1499     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1500       if (SI->getPointerOperand() == &I)
1501         continue;
1502     }
1503 
1504     AllLoadsStores = false;
1505     break;
1506   }
1507   if (AllLoadsStores) {
1508     IRBuilder<> IRB(&I);
1509     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1510   }
1511   DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1512 }
1513 
1514 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1515   Value *CondShadow = DFSF.getShadow(I.getCondition());
1516   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1517   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1518 
1519   if (isa<VectorType>(I.getCondition()->getType())) {
1520     DFSF.setShadow(
1521         &I,
1522         DFSF.combineShadows(
1523             CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
1524   } else {
1525     Value *ShadowSel;
1526     if (TrueShadow == FalseShadow) {
1527       ShadowSel = TrueShadow;
1528     } else {
1529       ShadowSel =
1530           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1531     }
1532     DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
1533   }
1534 }
1535 
1536 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1537   IRBuilder<> IRB(&I);
1538   Value *ValShadow = DFSF.getShadow(I.getValue());
1539   IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1540                  {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1541                                                                 *DFSF.DFS.Ctx)),
1542                   IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
1543 }
1544 
1545 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1546   IRBuilder<> IRB(&I);
1547   Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1548   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1549   Value *LenShadow =
1550       IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(),
1551                                                     DFSF.DFS.ShadowWidthBytes));
1552   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1553   Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr);
1554   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1555   auto *MTI = cast<MemTransferInst>(
1556       IRB.CreateCall(I.getFunctionType(), I.getCalledValue(),
1557                      {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
1558   if (ClPreserveAlignment) {
1559     MTI->setDestAlignment(I.getDestAlign() * DFSF.DFS.ShadowWidthBytes);
1560     MTI->setSourceAlignment(I.getSourceAlign() * DFSF.DFS.ShadowWidthBytes);
1561   } else {
1562     MTI->setDestAlignment(Align(DFSF.DFS.ShadowWidthBytes));
1563     MTI->setSourceAlignment(Align(DFSF.DFS.ShadowWidthBytes));
1564   }
1565   if (ClEventCallbacks) {
1566     IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn,
1567                    {RawDestShadow, I.getLength()});
1568   }
1569 }
1570 
1571 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1572   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1573     switch (DFSF.IA) {
1574     case DataFlowSanitizer::IA_TLS: {
1575       Value *S = DFSF.getShadow(RI.getReturnValue());
1576       IRBuilder<> IRB(&RI);
1577       IRB.CreateStore(S, DFSF.getRetvalTLS());
1578       break;
1579     }
1580     case DataFlowSanitizer::IA_Args: {
1581       IRBuilder<> IRB(&RI);
1582       Type *RT = DFSF.F->getFunctionType()->getReturnType();
1583       Value *InsVal =
1584           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1585       Value *InsShadow =
1586           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1587       RI.setOperand(0, InsShadow);
1588       break;
1589     }
1590     }
1591   }
1592 }
1593 
1594 void DFSanVisitor::visitCallBase(CallBase &CB) {
1595   Function *F = CB.getCalledFunction();
1596   if ((F && F->isIntrinsic()) || isa<InlineAsm>(CB.getCalledValue())) {
1597     visitOperandShadowInst(CB);
1598     return;
1599   }
1600 
1601   // Calls to this function are synthesized in wrappers, and we shouldn't
1602   // instrument them.
1603   if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
1604     return;
1605 
1606   IRBuilder<> IRB(&CB);
1607 
1608   DenseMap<Value *, Function *>::iterator i =
1609       DFSF.DFS.UnwrappedFnMap.find(CB.getCalledValue());
1610   if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1611     Function *F = i->second;
1612     switch (DFSF.DFS.getWrapperKind(F)) {
1613     case DataFlowSanitizer::WK_Warning:
1614       CB.setCalledFunction(F);
1615       IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1616                      IRB.CreateGlobalStringPtr(F->getName()));
1617       DFSF.setShadow(&CB, DFSF.DFS.ZeroShadow);
1618       return;
1619     case DataFlowSanitizer::WK_Discard:
1620       CB.setCalledFunction(F);
1621       DFSF.setShadow(&CB, DFSF.DFS.ZeroShadow);
1622       return;
1623     case DataFlowSanitizer::WK_Functional:
1624       CB.setCalledFunction(F);
1625       visitOperandShadowInst(CB);
1626       return;
1627     case DataFlowSanitizer::WK_Custom:
1628       // Don't try to handle invokes of custom functions, it's too complicated.
1629       // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1630       // wrapper.
1631       if (CallInst *CI = dyn_cast<CallInst>(&CB)) {
1632         FunctionType *FT = F->getFunctionType();
1633         TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
1634         std::string CustomFName = "__dfsw_";
1635         CustomFName += F->getName();
1636         FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
1637             CustomFName, CustomFn.TransformedType);
1638         if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
1639           CustomFn->copyAttributesFrom(F);
1640 
1641           // Custom functions returning non-void will write to the return label.
1642           if (!FT->getReturnType()->isVoidTy()) {
1643             CustomFn->removeAttributes(AttributeList::FunctionIndex,
1644                                        DFSF.DFS.ReadOnlyNoneAttrs);
1645           }
1646         }
1647 
1648         std::vector<Value *> Args;
1649 
1650         auto i = CB.arg_begin();
1651         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1652           Type *T = (*i)->getType();
1653           FunctionType *ParamFT;
1654           if (isa<PointerType>(T) &&
1655               (ParamFT = dyn_cast<FunctionType>(
1656                    cast<PointerType>(T)->getElementType()))) {
1657             std::string TName = "dfst";
1658             TName += utostr(FT->getNumParams() - n);
1659             TName += "$";
1660             TName += F->getName();
1661             Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1662             Args.push_back(T);
1663             Args.push_back(
1664                 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1665           } else {
1666             Args.push_back(*i);
1667           }
1668         }
1669 
1670         i = CB.arg_begin();
1671         const unsigned ShadowArgStart = Args.size();
1672         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1673           Args.push_back(DFSF.getShadow(*i));
1674 
1675         if (FT->isVarArg()) {
1676           auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1677                                            CB.arg_size() - FT->getNumParams());
1678           auto *LabelVAAlloca = new AllocaInst(
1679               LabelVATy, getDataLayout().getAllocaAddrSpace(),
1680               "labelva", &DFSF.F->getEntryBlock().front());
1681 
1682           for (unsigned n = 0; i != CB.arg_end(); ++i, ++n) {
1683             auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
1684             IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1685           }
1686 
1687           Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
1688         }
1689 
1690         if (!FT->getReturnType()->isVoidTy()) {
1691           if (!DFSF.LabelReturnAlloca) {
1692             DFSF.LabelReturnAlloca =
1693               new AllocaInst(DFSF.DFS.ShadowTy,
1694                              getDataLayout().getAllocaAddrSpace(),
1695                              "labelreturn", &DFSF.F->getEntryBlock().front());
1696           }
1697           Args.push_back(DFSF.LabelReturnAlloca);
1698         }
1699 
1700         for (i = CB.arg_begin() + FT->getNumParams(); i != CB.arg_end(); ++i)
1701           Args.push_back(*i);
1702 
1703         CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1704         CustomCI->setCallingConv(CI->getCallingConv());
1705         CustomCI->setAttributes(TransformFunctionAttributes(CustomFn,
1706             CI->getContext(), CI->getAttributes()));
1707 
1708         // Update the parameter attributes of the custom call instruction to
1709         // zero extend the shadow parameters. This is required for targets
1710         // which consider ShadowTy an illegal type.
1711         for (unsigned n = 0; n < FT->getNumParams(); n++) {
1712           const unsigned ArgNo = ShadowArgStart + n;
1713           if (CustomCI->getArgOperand(ArgNo)->getType() == DFSF.DFS.ShadowTy)
1714             CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
1715         }
1716 
1717         if (!FT->getReturnType()->isVoidTy()) {
1718           LoadInst *LabelLoad =
1719               IRB.CreateLoad(DFSF.DFS.ShadowTy, DFSF.LabelReturnAlloca);
1720           DFSF.setShadow(CustomCI, LabelLoad);
1721         }
1722 
1723         CI->replaceAllUsesWith(CustomCI);
1724         CI->eraseFromParent();
1725         return;
1726       }
1727       break;
1728     }
1729   }
1730 
1731   FunctionType *FT = cast<FunctionType>(
1732       CB.getCalledValue()->getType()->getPointerElementType());
1733   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1734     for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1735       IRB.CreateStore(DFSF.getShadow(CB.getArgOperand(i)),
1736                       DFSF.getArgTLS(i, &CB));
1737     }
1738   }
1739 
1740   Instruction *Next = nullptr;
1741   if (!CB.getType()->isVoidTy()) {
1742     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
1743       if (II->getNormalDest()->getSinglePredecessor()) {
1744         Next = &II->getNormalDest()->front();
1745       } else {
1746         BasicBlock *NewBB =
1747             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
1748         Next = &NewBB->front();
1749       }
1750     } else {
1751       assert(CB.getIterator() != CB.getParent()->end());
1752       Next = CB.getNextNode();
1753     }
1754 
1755     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1756       IRBuilder<> NextIRB(Next);
1757       LoadInst *LI = NextIRB.CreateLoad(DFSF.DFS.ShadowTy, DFSF.getRetvalTLS());
1758       DFSF.SkipInsts.insert(LI);
1759       DFSF.setShadow(&CB, LI);
1760       DFSF.NonZeroChecks.push_back(LI);
1761     }
1762   }
1763 
1764   // Do all instrumentation for IA_Args down here to defer tampering with the
1765   // CFG in a way that SplitEdge may be able to detect.
1766   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1767     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1768     Value *Func =
1769         IRB.CreateBitCast(CB.getCalledValue(), PointerType::getUnqual(NewFT));
1770     std::vector<Value *> Args;
1771 
1772     auto i = CB.arg_begin(), E = CB.arg_end();
1773     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1774       Args.push_back(*i);
1775 
1776     i = CB.arg_begin();
1777     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1778       Args.push_back(DFSF.getShadow(*i));
1779 
1780     if (FT->isVarArg()) {
1781       unsigned VarArgSize = CB.arg_size() - FT->getNumParams();
1782       ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1783       AllocaInst *VarArgShadow =
1784         new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
1785                        "", &DFSF.F->getEntryBlock().front());
1786       Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
1787       for (unsigned n = 0; i != E; ++i, ++n) {
1788         IRB.CreateStore(
1789             DFSF.getShadow(*i),
1790             IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
1791         Args.push_back(*i);
1792       }
1793     }
1794 
1795     CallBase *NewCB;
1796     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
1797       NewCB = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
1798                                II->getUnwindDest(), Args);
1799     } else {
1800       NewCB = IRB.CreateCall(NewFT, Func, Args);
1801     }
1802     NewCB->setCallingConv(CB.getCallingConv());
1803     NewCB->setAttributes(CB.getAttributes().removeAttributes(
1804         *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
1805         AttributeFuncs::typeIncompatible(NewCB->getType())));
1806 
1807     if (Next) {
1808       ExtractValueInst *ExVal = ExtractValueInst::Create(NewCB, 0, "", Next);
1809       DFSF.SkipInsts.insert(ExVal);
1810       ExtractValueInst *ExShadow = ExtractValueInst::Create(NewCB, 1, "", Next);
1811       DFSF.SkipInsts.insert(ExShadow);
1812       DFSF.setShadow(ExVal, ExShadow);
1813       DFSF.NonZeroChecks.push_back(ExShadow);
1814 
1815       CB.replaceAllUsesWith(ExVal);
1816     }
1817 
1818     CB.eraseFromParent();
1819   }
1820 }
1821 
1822 void DFSanVisitor::visitPHINode(PHINode &PN) {
1823   PHINode *ShadowPN =
1824       PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1825 
1826   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1827   Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1828   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1829        ++i) {
1830     ShadowPN->addIncoming(UndefShadow, *i);
1831   }
1832 
1833   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1834   DFSF.setShadow(&PN, ShadowPN);
1835 }
1836