1 //===-- DataFlowSanitizer.cpp - dynamic data flow analysis ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
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.
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:
23 /// +--------------------+ 0x800000000000 (top of memory)
24 /// | application memory |
25 /// +--------------------+ 0x700000008000 (kAppAddr)
29 /// +--------------------+ 0x200200000000 (kUnusedAddr)
31 /// +--------------------+ 0x200000000000 (kUnionTableAddr)
33 /// +--------------------+ 0x000000010000 (kShadowAddr)
34 /// | reserved by kernel |
35 /// +--------------------+ 0x000000000000
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.
44 /// For more information, please refer to the design document:
45 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
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/Analysis/ValueTracking.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/IRBuilder.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/MDBuilder.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/InstVisitor.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
62 #include "llvm/Transforms/Utils/Local.h"
63 #include "llvm/Transforms/Utils/SpecialCaseList.h"
68 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
69 // alignment requirements provided by the input IR are correct. For example,
70 // if the input IR contains a load with alignment 8, this flag will cause
71 // the shadow load to have alignment 16. This flag is disabled by default as
72 // we have unfortunately encountered too much code (including Clang itself;
73 // see PR14291) which performs misaligned access.
74 static cl::opt<bool> ClPreserveAlignment(
75 "dfsan-preserve-alignment",
76 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
79 // The ABI list file controls how shadow parameters are passed. The pass treats
80 // every function labelled "uninstrumented" in the ABI list file as conforming
81 // to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
82 // additional annotations for those functions, a call to one of those functions
83 // will produce a warning message, as the labelling behaviour of the function is
84 // unknown. The other supported annotations are "functional" and "discard",
85 // which are described below under DataFlowSanitizer::WrapperKind.
86 static cl::opt<std::string> ClABIListFile(
88 cl::desc("File listing native ABI functions and how the pass treats them"),
91 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
92 // functions (see DataFlowSanitizer::InstrumentedABI below).
93 static cl::opt<bool> ClArgsABI(
95 cl::desc("Use the argument ABI rather than the TLS ABI"),
98 static cl::opt<bool> ClDebugNonzeroLabels(
99 "dfsan-debug-nonzero-labels",
100 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
101 "load or return with a nonzero label"),
106 class DataFlowSanitizer : public ModulePass {
107 friend struct DFSanFunction;
108 friend class DFSanVisitor;
114 /// Which ABI should be used for instrumented functions?
115 enum InstrumentedABI {
116 /// Argument and return value labels are passed through additional
117 /// arguments and by modifying the return type.
120 /// Argument and return value labels are passed through TLS variables
121 /// __dfsan_arg_tls and __dfsan_retval_tls.
125 /// How should calls to uninstrumented functions be handled?
127 /// This function is present in an uninstrumented form but we don't know
128 /// how it should be handled. Print a warning and call the function anyway.
129 /// Don't label the return value.
132 /// This function does not write to (user-accessible) memory, and its return
133 /// value is unlabelled.
136 /// This function does not write to (user-accessible) memory, and the label
137 /// of its return value is the union of the label of its arguments.
140 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
141 /// where F is the name of the function. This function may wrap the
142 /// original function or provide its own implementation. This is similar to
143 /// the IA_Args ABI, except that IA_Args uses a struct return type to
144 /// pass the return value shadow in a register, while WK_Custom uses an
145 /// extra pointer argument to return the shadow. This allows the wrapped
146 /// form of the function type to be expressed in C.
153 IntegerType *ShadowTy;
154 PointerType *ShadowPtrTy;
155 IntegerType *IntptrTy;
156 ConstantInt *ZeroShadow;
157 ConstantInt *ShadowPtrMask;
158 ConstantInt *ShadowPtrMul;
161 void *(*GetArgTLSPtr)();
162 void *(*GetRetvalTLSPtr)();
164 Constant *GetRetvalTLS;
165 FunctionType *DFSanUnionFnTy;
166 FunctionType *DFSanUnionLoadFnTy;
167 FunctionType *DFSanUnimplementedFnTy;
168 FunctionType *DFSanSetLabelFnTy;
169 FunctionType *DFSanNonzeroLabelFnTy;
170 Constant *DFSanUnionFn;
171 Constant *DFSanUnionLoadFn;
172 Constant *DFSanUnimplementedFn;
173 Constant *DFSanSetLabelFn;
174 Constant *DFSanNonzeroLabelFn;
175 MDNode *ColdCallWeights;
176 OwningPtr<SpecialCaseList> ABIList;
177 DenseMap<Value *, Function *> UnwrappedFnMap;
178 AttributeSet ReadOnlyNoneAttrs;
180 Value *getShadowAddress(Value *Addr, Instruction *Pos);
181 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
182 bool isInstrumented(const Function *F);
183 bool isInstrumented(const GlobalAlias *GA);
184 FunctionType *getArgsFunctionType(FunctionType *T);
185 FunctionType *getCustomFunctionType(FunctionType *T);
186 InstrumentedABI getInstrumentedABI();
187 WrapperKind getWrapperKind(Function *F);
188 void addGlobalNamePrefix(GlobalValue *GV);
189 Function *buildWrapperFunction(Function *F, StringRef NewFName,
190 GlobalValue::LinkageTypes NewFLink,
191 FunctionType *NewFT);
194 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
195 void *(*getArgTLS)() = 0, void *(*getRetValTLS)() = 0);
197 bool doInitialization(Module &M);
198 bool runOnModule(Module &M);
201 struct DFSanFunction {
202 DataFlowSanitizer &DFS;
204 DataFlowSanitizer::InstrumentedABI IA;
208 AllocaInst *LabelReturnAlloca;
209 DenseMap<Value *, Value *> ValShadowMap;
210 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
211 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
212 DenseSet<Instruction *> SkipInsts;
213 DenseSet<Value *> NonZeroChecks;
215 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
216 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
217 IsNativeABI(IsNativeABI), ArgTLSPtr(0), RetvalTLSPtr(0),
218 LabelReturnAlloca(0) {}
219 Value *getArgTLSPtr();
220 Value *getArgTLS(unsigned Index, Instruction *Pos);
221 Value *getRetvalTLS();
222 Value *getShadow(Value *V);
223 void setShadow(Instruction *I, Value *Shadow);
224 Value *combineOperandShadows(Instruction *Inst);
225 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
227 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
231 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
234 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
236 void visitOperandShadowInst(Instruction &I);
238 void visitBinaryOperator(BinaryOperator &BO);
239 void visitCastInst(CastInst &CI);
240 void visitCmpInst(CmpInst &CI);
241 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
242 void visitLoadInst(LoadInst &LI);
243 void visitStoreInst(StoreInst &SI);
244 void visitReturnInst(ReturnInst &RI);
245 void visitCallSite(CallSite CS);
246 void visitPHINode(PHINode &PN);
247 void visitExtractElementInst(ExtractElementInst &I);
248 void visitInsertElementInst(InsertElementInst &I);
249 void visitShuffleVectorInst(ShuffleVectorInst &I);
250 void visitExtractValueInst(ExtractValueInst &I);
251 void visitInsertValueInst(InsertValueInst &I);
252 void visitAllocaInst(AllocaInst &I);
253 void visitSelectInst(SelectInst &I);
254 void visitMemSetInst(MemSetInst &I);
255 void visitMemTransferInst(MemTransferInst &I);
260 char DataFlowSanitizer::ID;
261 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
262 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
264 ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
265 void *(*getArgTLS)(),
266 void *(*getRetValTLS)()) {
267 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
270 DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
271 void *(*getArgTLS)(),
272 void *(*getRetValTLS)())
273 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
274 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
278 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
279 llvm::SmallVector<Type *, 4> ArgTypes;
280 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
281 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
282 ArgTypes.push_back(ShadowTy);
284 ArgTypes.push_back(ShadowPtrTy);
285 Type *RetType = T->getReturnType();
286 if (!RetType->isVoidTy())
287 RetType = StructType::get(RetType, ShadowTy, (Type *)0);
288 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
291 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
292 assert(!T->isVarArg());
293 llvm::SmallVector<Type *, 4> ArgTypes;
294 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
295 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
296 ArgTypes.push_back(ShadowTy);
297 Type *RetType = T->getReturnType();
298 if (!RetType->isVoidTy())
299 ArgTypes.push_back(ShadowPtrTy);
300 return FunctionType::get(T->getReturnType(), ArgTypes, false);
303 bool DataFlowSanitizer::doInitialization(Module &M) {
304 DL = getAnalysisIfAvailable<DataLayout>();
309 Ctx = &M.getContext();
310 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
311 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
312 IntptrTy = DL->getIntPtrType(*Ctx);
313 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
314 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
315 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
317 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
319 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
320 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
322 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
323 DFSanUnimplementedFnTy = FunctionType::get(
324 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
325 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
326 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
327 DFSanSetLabelArgs, /*isVarArg=*/false);
328 DFSanNonzeroLabelFnTy = FunctionType::get(
329 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
332 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
334 GetArgTLS = ConstantExpr::getIntToPtr(
335 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
336 PointerType::getUnqual(
337 FunctionType::get(PointerType::getUnqual(ArgTLSTy), (Type *)0)));
339 if (GetRetvalTLSPtr) {
341 GetRetvalTLS = ConstantExpr::getIntToPtr(
342 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
343 PointerType::getUnqual(
344 FunctionType::get(PointerType::getUnqual(ShadowTy), (Type *)0)));
347 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
351 bool DataFlowSanitizer::isInstrumented(const Function *F) {
352 return !ABIList->isIn(*F, "uninstrumented");
355 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
356 return !ABIList->isIn(*GA, "uninstrumented");
359 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
360 return ClArgsABI ? IA_Args : IA_TLS;
363 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
364 if (ABIList->isIn(*F, "functional"))
365 return WK_Functional;
366 if (ABIList->isIn(*F, "discard"))
368 if (ABIList->isIn(*F, "custom"))
374 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
375 std::string GVName = GV->getName(), Prefix = "dfs$";
376 GV->setName(Prefix + GVName);
378 // Try to change the name of the function in module inline asm. We only do
379 // this for specific asm directives, currently only ".symver", to try to avoid
380 // corrupting asm which happens to contain the symbol name as a substring.
381 // Note that the substitution for .symver assumes that the versioned symbol
382 // also has an instrumented name.
383 std::string Asm = GV->getParent()->getModuleInlineAsm();
384 std::string SearchStr = ".symver " + GVName + ",";
385 size_t Pos = Asm.find(SearchStr);
386 if (Pos != std::string::npos) {
387 Asm.replace(Pos, SearchStr.size(),
388 ".symver " + Prefix + GVName + "," + Prefix);
389 GV->getParent()->setModuleInlineAsm(Asm);
394 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
395 GlobalValue::LinkageTypes NewFLink,
396 FunctionType *NewFT) {
397 FunctionType *FT = F->getFunctionType();
398 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
400 NewF->copyAttributesFrom(F);
401 NewF->removeAttributes(
402 AttributeSet::ReturnIndex,
403 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
404 AttributeSet::ReturnIndex));
406 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
407 std::vector<Value *> Args;
408 unsigned n = FT->getNumParams();
409 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
410 Args.push_back(&*ai);
411 CallInst *CI = CallInst::Create(F, Args, "", BB);
412 if (FT->getReturnType()->isVoidTy())
413 ReturnInst::Create(*Ctx, BB);
415 ReturnInst::Create(*Ctx, CI, BB);
420 bool DataFlowSanitizer::runOnModule(Module &M) {
424 if (ABIList->isIn(M, "skip"))
428 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
429 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
430 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
431 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
433 if (!GetRetvalTLSPtr) {
434 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
435 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
436 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
439 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
440 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
441 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
442 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
443 F->addAttribute(1, Attribute::ZExt);
444 F->addAttribute(2, Attribute::ZExt);
447 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
448 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
449 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
451 DFSanUnimplementedFn =
452 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
454 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
455 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
456 F->addAttribute(1, Attribute::ZExt);
458 DFSanNonzeroLabelFn =
459 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
461 std::vector<Function *> FnsToInstrument;
462 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
463 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
464 if (!i->isIntrinsic() &&
466 i != DFSanUnionLoadFn &&
467 i != DFSanUnimplementedFn &&
468 i != DFSanSetLabelFn &&
469 i != DFSanNonzeroLabelFn)
470 FnsToInstrument.push_back(&*i);
473 // Give function aliases prefixes when necessary.
474 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
475 GlobalAlias *GA = &*i;
477 // Don't stop on weak. We assume people aren't playing games with the
478 // instrumentedness of overridden weak aliases.
479 if (Function *F = dyn_cast<Function>(
480 GA->resolveAliasedGlobal(/*stopOnWeak=*/false))) {
481 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
482 if (GAInst && FInst) {
483 addGlobalNamePrefix(GA);
489 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
490 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
492 // First, change the ABI of every function in the module. ABI-listed
493 // functions keep their original ABI and get a wrapper function.
494 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
495 e = FnsToInstrument.end();
498 FunctionType *FT = F.getFunctionType();
500 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
501 FT->getReturnType()->isVoidTy());
503 if (isInstrumented(&F)) {
504 // Instrumented functions get a 'dfs$' prefix. This allows us to more
505 // easily identify cases of mismatching ABIs.
506 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
507 FunctionType *NewFT = getArgsFunctionType(FT);
508 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
509 NewF->copyAttributesFrom(&F);
510 NewF->removeAttributes(
511 AttributeSet::ReturnIndex,
512 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
513 AttributeSet::ReturnIndex));
514 for (Function::arg_iterator FArg = F.arg_begin(),
515 NewFArg = NewF->arg_begin(),
516 FArgEnd = F.arg_end();
517 FArg != FArgEnd; ++FArg, ++NewFArg) {
518 FArg->replaceAllUsesWith(NewFArg);
520 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
522 for (Function::use_iterator ui = F.use_begin(), ue = F.use_end();
524 BlockAddress *BA = dyn_cast<BlockAddress>(ui.getUse().getUser());
527 BA->replaceAllUsesWith(
528 BlockAddress::get(NewF, BA->getBasicBlock()));
532 F.replaceAllUsesWith(
533 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
537 addGlobalNamePrefix(NewF);
539 addGlobalNamePrefix(&F);
541 // Hopefully, nobody will try to indirectly call a vararg
543 } else if (FT->isVarArg()) {
544 UnwrappedFnMap[&F] = &F;
546 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
547 // Build a wrapper function for F. The wrapper simply calls F, and is
548 // added to FnsToInstrument so that any instrumentation according to its
549 // WrapperKind is done in the second pass below.
550 FunctionType *NewFT = getInstrumentedABI() == IA_Args
551 ? getArgsFunctionType(FT)
554 buildWrapperFunction(&F, std::string("dfsw$") + std::string(F.getName()),
555 GlobalValue::LinkOnceODRLinkage, NewFT);
556 if (getInstrumentedABI() == IA_TLS)
557 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
559 Value *WrappedFnCst =
560 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
561 F.replaceAllUsesWith(WrappedFnCst);
562 UnwrappedFnMap[WrappedFnCst] = &F;
565 if (!F.isDeclaration()) {
566 // This function is probably defining an interposition of an
567 // uninstrumented function and hence needs to keep the original ABI.
568 // But any functions it may call need to use the instrumented ABI, so
569 // we instrument it in a mode which preserves the original ABI.
570 FnsWithNativeABI.insert(&F);
572 // This code needs to rebuild the iterators, as they may be invalidated
573 // by the push_back, taking care that the new range does not include
574 // any functions added by this code.
575 size_t N = i - FnsToInstrument.begin(),
576 Count = e - FnsToInstrument.begin();
577 FnsToInstrument.push_back(&F);
578 i = FnsToInstrument.begin() + N;
579 e = FnsToInstrument.begin() + Count;
584 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
585 e = FnsToInstrument.end();
587 if (!*i || (*i)->isDeclaration())
590 removeUnreachableBlocks(**i);
592 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
594 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
595 // Build a copy of the list before iterating over it.
596 llvm::SmallVector<BasicBlock *, 4> BBList;
597 std::copy(df_begin(&(*i)->getEntryBlock()), df_end(&(*i)->getEntryBlock()),
598 std::back_inserter(BBList));
600 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
603 Instruction *Inst = &(*i)->front();
605 // DFSanVisitor may split the current basic block, changing the current
606 // instruction's next pointer and moving the next instruction to the
607 // tail block from which we should continue.
608 Instruction *Next = Inst->getNextNode();
609 // DFSanVisitor may delete Inst, so keep track of whether it was a
611 bool IsTerminator = isa<TerminatorInst>(Inst);
612 if (!DFSF.SkipInsts.count(Inst))
613 DFSanVisitor(DFSF).visit(Inst);
620 // We will not necessarily be able to compute the shadow for every phi node
621 // until we have visited every block. Therefore, the code that handles phi
622 // nodes adds them to the PHIFixups list so that they can be properly
624 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
625 i = DFSF.PHIFixups.begin(),
626 e = DFSF.PHIFixups.end();
628 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
630 i->second->setIncomingValue(
631 val, DFSF.getShadow(i->first->getIncomingValue(val)));
635 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
636 // places (i.e. instructions in basic blocks we haven't even begun visiting
637 // yet). To make our life easier, do this work in a pass after the main
639 if (ClDebugNonzeroLabels) {
640 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
641 e = DFSF.NonZeroChecks.end();
644 if (Instruction *I = dyn_cast<Instruction>(*i))
645 Pos = I->getNextNode();
647 Pos = DFSF.F->getEntryBlock().begin();
648 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
649 Pos = Pos->getNextNode();
650 IRBuilder<> IRB(Pos);
651 Instruction *NeInst = cast<Instruction>(
652 IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow));
653 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
654 NeInst, /*Unreachable=*/ false, ColdCallWeights));
655 IRBuilder<> ThenIRB(BI);
656 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
664 Value *DFSanFunction::getArgTLSPtr() {
668 return ArgTLSPtr = DFS.ArgTLS;
670 IRBuilder<> IRB(F->getEntryBlock().begin());
671 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
674 Value *DFSanFunction::getRetvalTLS() {
678 return RetvalTLSPtr = DFS.RetvalTLS;
680 IRBuilder<> IRB(F->getEntryBlock().begin());
681 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
684 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
685 IRBuilder<> IRB(Pos);
686 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
689 Value *DFSanFunction::getShadow(Value *V) {
690 if (!isa<Argument>(V) && !isa<Instruction>(V))
691 return DFS.ZeroShadow;
692 Value *&Shadow = ValShadowMap[V];
694 if (Argument *A = dyn_cast<Argument>(V)) {
696 return DFS.ZeroShadow;
698 case DataFlowSanitizer::IA_TLS: {
699 Value *ArgTLSPtr = getArgTLSPtr();
700 Instruction *ArgTLSPos =
701 DFS.ArgTLS ? &*F->getEntryBlock().begin()
702 : cast<Instruction>(ArgTLSPtr)->getNextNode();
703 IRBuilder<> IRB(ArgTLSPos);
704 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
707 case DataFlowSanitizer::IA_Args: {
708 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
709 Function::arg_iterator i = F->arg_begin();
713 assert(Shadow->getType() == DFS.ShadowTy);
717 NonZeroChecks.insert(Shadow);
719 Shadow = DFS.ZeroShadow;
725 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
726 assert(!ValShadowMap.count(I));
727 assert(Shadow->getType() == DFS.ShadowTy);
728 ValShadowMap[I] = Shadow;
731 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
732 assert(Addr != RetvalTLS && "Reinstrumenting?");
733 IRBuilder<> IRB(Pos);
734 return IRB.CreateIntToPtr(
736 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
741 // Generates IR to compute the union of the two given shadows, inserting it
742 // before Pos. Returns the computed union Value.
743 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
745 if (V1 == ZeroShadow)
747 if (V2 == ZeroShadow)
751 IRBuilder<> IRB(Pos);
752 BasicBlock *Head = Pos->getParent();
753 Value *Ne = IRB.CreateICmpNE(V1, V2);
754 Instruction *NeInst = dyn_cast<Instruction>(Ne);
756 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
757 NeInst, /*Unreachable=*/ false, ColdCallWeights));
758 IRBuilder<> ThenIRB(BI);
759 CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
760 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
761 Call->addAttribute(1, Attribute::ZExt);
762 Call->addAttribute(2, Attribute::ZExt);
764 BasicBlock *Tail = BI->getSuccessor(0);
765 PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
766 Phi->addIncoming(Call, Call->getParent());
767 Phi->addIncoming(ZeroShadow, Head);
776 // A convenience function which folds the shadows of each of the operands
777 // of the provided instruction Inst, inserting the IR before Inst. Returns
778 // the computed union Value.
779 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
780 if (Inst->getNumOperands() == 0)
781 return DFS.ZeroShadow;
783 Value *Shadow = getShadow(Inst->getOperand(0));
784 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
785 Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
790 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
791 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
792 DFSF.setShadow(&I, CombinedShadow);
795 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
796 // Addr has alignment Align, and take the union of each of those shadows.
797 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
799 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
800 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
801 AllocaShadowMap.find(AI);
802 if (i != AllocaShadowMap.end()) {
803 IRBuilder<> IRB(Pos);
804 return IRB.CreateLoad(i->second);
808 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
809 SmallVector<Value *, 2> Objs;
810 GetUnderlyingObjects(Addr, Objs, DFS.DL);
811 bool AllConstants = true;
812 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
814 if (isa<Function>(*i) || isa<BlockAddress>(*i))
816 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
819 AllConstants = false;
823 return DFS.ZeroShadow;
825 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
828 return DFS.ZeroShadow;
830 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
831 LI->setAlignment(ShadowAlign);
835 IRBuilder<> IRB(Pos);
837 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
838 return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
839 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
843 if (Size % (64 / DFS.ShadowWidth) == 0) {
844 // Fast path for the common case where each byte has identical shadow: load
845 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
846 // shadow is non-equal.
847 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
848 IRBuilder<> FallbackIRB(FallbackBB);
849 CallInst *FallbackCall = FallbackIRB.CreateCall2(
850 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
851 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
853 // Compare each of the shadows stored in the loaded 64 bits to each other,
854 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
855 IRBuilder<> IRB(Pos);
857 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
858 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
859 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
860 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
861 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
862 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
863 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
865 BasicBlock *Head = Pos->getParent();
866 BasicBlock *Tail = Head->splitBasicBlock(Pos);
867 // In the following code LastBr will refer to the previous basic block's
868 // conditional branch instruction, whose true successor is fixed up to point
869 // to the next block during the loop below or to the tail after the final
871 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
872 ReplaceInstWithInst(Head->getTerminator(), LastBr);
874 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
875 Ofs += 64 / DFS.ShadowWidth) {
876 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
877 IRBuilder<> NextIRB(NextBB);
878 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
879 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
880 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
881 LastBr->setSuccessor(0, NextBB);
882 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
885 LastBr->setSuccessor(0, Tail);
886 FallbackIRB.CreateBr(Tail);
887 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
888 Shadow->addIncoming(FallbackCall, FallbackBB);
889 Shadow->addIncoming(TruncShadow, LastBr->getParent());
893 IRBuilder<> IRB(Pos);
894 CallInst *FallbackCall = IRB.CreateCall2(
895 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
896 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
900 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
901 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
903 if (ClPreserveAlignment) {
904 Align = LI.getAlignment();
906 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
910 IRBuilder<> IRB(&LI);
911 Value *LoadedShadow =
912 DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
913 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
914 Value *CombinedShadow = DFSF.DFS.combineShadows(LoadedShadow, PtrShadow, &LI);
915 if (CombinedShadow != DFSF.DFS.ZeroShadow)
916 DFSF.NonZeroChecks.insert(CombinedShadow);
918 DFSF.setShadow(&LI, CombinedShadow);
921 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
922 Value *Shadow, Instruction *Pos) {
923 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
924 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
925 AllocaShadowMap.find(AI);
926 if (i != AllocaShadowMap.end()) {
927 IRBuilder<> IRB(Pos);
928 IRB.CreateStore(Shadow, i->second);
933 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
934 IRBuilder<> IRB(Pos);
935 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
936 if (Shadow == DFS.ZeroShadow) {
937 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
938 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
939 Value *ExtShadowAddr =
940 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
941 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
945 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
947 if (Size >= ShadowVecSize) {
948 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
949 Value *ShadowVec = UndefValue::get(ShadowVecTy);
950 for (unsigned i = 0; i != ShadowVecSize; ++i) {
951 ShadowVec = IRB.CreateInsertElement(
952 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
954 Value *ShadowVecAddr =
955 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
957 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
958 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
959 Size -= ShadowVecSize;
961 } while (Size >= ShadowVecSize);
962 Offset *= ShadowVecSize;
965 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
966 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
972 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
974 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
976 if (ClPreserveAlignment) {
977 Align = SI.getAlignment();
979 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
983 DFSF.storeShadow(SI.getPointerOperand(), Size, Align,
984 DFSF.getShadow(SI.getValueOperand()), &SI);
987 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
988 visitOperandShadowInst(BO);
991 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
993 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
995 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
996 visitOperandShadowInst(GEPI);
999 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1000 visitOperandShadowInst(I);
1003 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1004 visitOperandShadowInst(I);
1007 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1008 visitOperandShadowInst(I);
1011 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1012 visitOperandShadowInst(I);
1015 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1016 visitOperandShadowInst(I);
1019 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1020 bool AllLoadsStores = true;
1021 for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e;
1023 if (isa<LoadInst>(*i))
1026 if (StoreInst *SI = dyn_cast<StoreInst>(*i)) {
1027 if (SI->getPointerOperand() == &I)
1031 AllLoadsStores = false;
1034 if (AllLoadsStores) {
1035 IRBuilder<> IRB(&I);
1036 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1038 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1041 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1042 Value *CondShadow = DFSF.getShadow(I.getCondition());
1043 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1044 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1046 if (isa<VectorType>(I.getCondition()->getType())) {
1048 &I, DFSF.DFS.combineShadows(
1050 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
1053 if (TrueShadow == FalseShadow) {
1054 ShadowSel = TrueShadow;
1057 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1059 DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
1063 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1064 IRBuilder<> IRB(&I);
1065 Value *ValShadow = DFSF.getShadow(I.getValue());
1067 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1068 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1069 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1072 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1073 IRBuilder<> IRB(&I);
1074 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1075 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1076 Value *LenShadow = IRB.CreateMul(
1078 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1080 if (ClPreserveAlignment) {
1081 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1082 ConstantInt::get(I.getAlignmentCst()->getType(),
1083 DFSF.DFS.ShadowWidth / 8));
1085 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1086 DFSF.DFS.ShadowWidth / 8);
1088 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1089 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1090 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1091 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1092 AlignShadow, I.getVolatileCst());
1095 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1096 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1098 case DataFlowSanitizer::IA_TLS: {
1099 Value *S = DFSF.getShadow(RI.getReturnValue());
1100 IRBuilder<> IRB(&RI);
1101 IRB.CreateStore(S, DFSF.getRetvalTLS());
1104 case DataFlowSanitizer::IA_Args: {
1105 IRBuilder<> IRB(&RI);
1106 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1108 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1110 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1111 RI.setOperand(0, InsShadow);
1118 void DFSanVisitor::visitCallSite(CallSite CS) {
1119 Function *F = CS.getCalledFunction();
1120 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1121 visitOperandShadowInst(*CS.getInstruction());
1125 IRBuilder<> IRB(CS.getInstruction());
1127 DenseMap<Value *, Function *>::iterator i =
1128 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1129 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1130 Function *F = i->second;
1131 switch (DFSF.DFS.getWrapperKind(F)) {
1132 case DataFlowSanitizer::WK_Warning: {
1133 CS.setCalledFunction(F);
1134 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1135 IRB.CreateGlobalStringPtr(F->getName()));
1136 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1139 case DataFlowSanitizer::WK_Discard: {
1140 CS.setCalledFunction(F);
1141 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1144 case DataFlowSanitizer::WK_Functional: {
1145 CS.setCalledFunction(F);
1146 visitOperandShadowInst(*CS.getInstruction());
1149 case DataFlowSanitizer::WK_Custom: {
1150 // Don't try to handle invokes of custom functions, it's too complicated.
1151 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1153 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1154 FunctionType *FT = F->getFunctionType();
1155 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1156 std::string CustomFName = "__dfsw_";
1157 CustomFName += F->getName();
1159 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1160 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1161 CustomFn->copyAttributesFrom(F);
1163 // Custom functions returning non-void will write to the return label.
1164 if (!FT->getReturnType()->isVoidTy()) {
1165 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1166 DFSF.DFS.ReadOnlyNoneAttrs);
1170 std::vector<Value *> Args;
1172 CallSite::arg_iterator i = CS.arg_begin();
1173 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1177 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1178 Args.push_back(DFSF.getShadow(*i));
1180 if (!FT->getReturnType()->isVoidTy()) {
1181 if (!DFSF.LabelReturnAlloca) {
1182 DFSF.LabelReturnAlloca =
1183 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1184 DFSF.F->getEntryBlock().begin());
1186 Args.push_back(DFSF.LabelReturnAlloca);
1189 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1190 CustomCI->setCallingConv(CI->getCallingConv());
1191 CustomCI->setAttributes(CI->getAttributes());
1193 if (!FT->getReturnType()->isVoidTy()) {
1194 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1195 DFSF.setShadow(CustomCI, LabelLoad);
1198 CI->replaceAllUsesWith(CustomCI);
1199 CI->eraseFromParent();
1207 FunctionType *FT = cast<FunctionType>(
1208 CS.getCalledValue()->getType()->getPointerElementType());
1209 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1210 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1211 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1212 DFSF.getArgTLS(i, CS.getInstruction()));
1216 Instruction *Next = 0;
1217 if (!CS.getType()->isVoidTy()) {
1218 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1219 if (II->getNormalDest()->getSinglePredecessor()) {
1220 Next = II->getNormalDest()->begin();
1223 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1224 Next = NewBB->begin();
1227 Next = CS->getNextNode();
1230 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1231 IRBuilder<> NextIRB(Next);
1232 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1233 DFSF.SkipInsts.insert(LI);
1234 DFSF.setShadow(CS.getInstruction(), LI);
1235 DFSF.NonZeroChecks.insert(LI);
1239 // Do all instrumentation for IA_Args down here to defer tampering with the
1240 // CFG in a way that SplitEdge may be able to detect.
1241 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1242 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1244 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1245 std::vector<Value *> Args;
1247 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1248 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1252 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1253 Args.push_back(DFSF.getShadow(*i));
1255 if (FT->isVarArg()) {
1256 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1257 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1258 AllocaInst *VarArgShadow =
1259 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1260 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1261 for (unsigned n = 0; i != e; ++i, ++n) {
1262 IRB.CreateStore(DFSF.getShadow(*i),
1263 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1269 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1270 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1273 NewCS = IRB.CreateCall(Func, Args);
1275 NewCS.setCallingConv(CS.getCallingConv());
1276 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1277 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1278 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1279 AttributeSet::ReturnIndex)));
1282 ExtractValueInst *ExVal =
1283 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1284 DFSF.SkipInsts.insert(ExVal);
1285 ExtractValueInst *ExShadow =
1286 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1287 DFSF.SkipInsts.insert(ExShadow);
1288 DFSF.setShadow(ExVal, ExShadow);
1289 DFSF.NonZeroChecks.insert(ExShadow);
1291 CS.getInstruction()->replaceAllUsesWith(ExVal);
1294 CS.getInstruction()->eraseFromParent();
1298 void DFSanVisitor::visitPHINode(PHINode &PN) {
1300 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1302 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1303 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1304 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1306 ShadowPN->addIncoming(UndefShadow, *i);
1309 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1310 DFSF.setShadow(&PN, ShadowPN);