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