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