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