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