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