blob: 1171d902d32291366560cedd11b5a4463e6b13aa [file] [log] [blame]
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001//===-- 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"
Peter Collingbourne28a10af2013-08-27 22:09:06 +000051#include "llvm/ADT/StringExtras.h"
Peter Collingbourne0826e602014-12-05 21:22:32 +000052#include "llvm/ADT/Triple.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000053#include "llvm/Analysis/ValueTracking.h"
Peter Collingbourne705a1ae2014-07-15 04:41:17 +000054#include "llvm/IR/Dominators.h"
David Blaikiec6c6c7b2014-10-07 22:59:46 +000055#include "llvm/IR/DebugInfo.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000056#include "llvm/IR/IRBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000057#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000058#include "llvm/IR/InstVisitor.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000059#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/MDBuilder.h"
61#include "llvm/IR/Type.h"
62#include "llvm/IR/Value.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000063#include "llvm/Pass.h"
64#include "llvm/Support/CommandLine.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000065#include "llvm/Support/SpecialCaseList.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000066#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourneae66d572013-08-09 21:42:53 +000067#include "llvm/Transforms/Utils/Local.h"
Peter Collingbourne9947c492014-07-15 22:13:19 +000068#include <algorithm>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000069#include <iterator>
Peter Collingbourne9947c492014-07-15 22:13:19 +000070#include <set>
71#include <utility>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000072
73using namespace llvm;
74
75// The -dfsan-preserve-alignment flag controls whether this pass assumes that
76// alignment requirements provided by the input IR are correct. For example,
77// if the input IR contains a load with alignment 8, this flag will cause
78// the shadow load to have alignment 16. This flag is disabled by default as
79// we have unfortunately encountered too much code (including Clang itself;
80// see PR14291) which performs misaligned access.
81static cl::opt<bool> ClPreserveAlignment(
82 "dfsan-preserve-alignment",
83 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
84 cl::init(false));
85
Alexey Samsonovb9b80272015-02-04 17:39:48 +000086// The ABI list files control how shadow parameters are passed. The pass treats
Peter Collingbourne68162e72013-08-14 18:54:12 +000087// every function labelled "uninstrumented" in the ABI list file as conforming
88// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
89// additional annotations for those functions, a call to one of those functions
90// will produce a warning message, as the labelling behaviour of the function is
91// unknown. The other supported annotations are "functional" and "discard",
92// which are described below under DataFlowSanitizer::WrapperKind.
Alexey Samsonovb9b80272015-02-04 17:39:48 +000093static cl::list<std::string> ClABIListFiles(
Peter Collingbourne68162e72013-08-14 18:54:12 +000094 "dfsan-abilist",
95 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000096 cl::Hidden);
97
Peter Collingbourne68162e72013-08-14 18:54:12 +000098// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
99// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000100static cl::opt<bool> ClArgsABI(
101 "dfsan-args-abi",
102 cl::desc("Use the argument ABI rather than the TLS ABI"),
103 cl::Hidden);
104
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000105// Controls whether the pass includes or ignores the labels of pointers in load
106// instructions.
107static cl::opt<bool> ClCombinePointerLabelsOnLoad(
108 "dfsan-combine-pointer-labels-on-load",
109 cl::desc("Combine the label of the pointer with the label of the data when "
110 "loading from memory."),
111 cl::Hidden, cl::init(true));
112
113// Controls whether the pass includes or ignores the labels of pointers in
114// stores instructions.
115static cl::opt<bool> ClCombinePointerLabelsOnStore(
116 "dfsan-combine-pointer-labels-on-store",
117 cl::desc("Combine the label of the pointer with the label of the data when "
118 "storing in memory."),
119 cl::Hidden, cl::init(false));
120
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000121static cl::opt<bool> ClDebugNonzeroLabels(
122 "dfsan-debug-nonzero-labels",
123 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
124 "load or return with a nonzero label"),
125 cl::Hidden);
126
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000127namespace {
128
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000129StringRef GetGlobalTypeString(const GlobalValue &G) {
130 // Types of GlobalVariables are always pointer types.
131 Type *GType = G.getType()->getElementType();
132 // For now we support blacklisting struct types only.
133 if (StructType *SGType = dyn_cast<StructType>(GType)) {
134 if (!SGType->isLiteral())
135 return SGType->getName();
136 }
137 return "<unknown type>";
138}
139
140class DFSanABIList {
141 std::unique_ptr<SpecialCaseList> SCL;
142
143 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000144 DFSanABIList() {}
145
146 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000147
148 /// Returns whether either this function or its source file are listed in the
149 /// given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000150 bool isIn(const Function &F, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000151 return isIn(*F.getParent(), Category) ||
152 SCL->inSection("fun", F.getName(), Category);
153 }
154
155 /// Returns whether this global alias is listed in the given category.
156 ///
157 /// If GA aliases a function, the alias's name is matched as a function name
158 /// would be. Similarly, aliases of globals are matched like globals.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000159 bool isIn(const GlobalAlias &GA, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000160 if (isIn(*GA.getParent(), Category))
161 return true;
162
163 if (isa<FunctionType>(GA.getType()->getElementType()))
164 return SCL->inSection("fun", GA.getName(), Category);
165
166 return SCL->inSection("global", GA.getName(), Category) ||
167 SCL->inSection("type", GetGlobalTypeString(GA), Category);
168 }
169
170 /// Returns whether this module is listed in the given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000171 bool isIn(const Module &M, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000172 return SCL->inSection("src", M.getModuleIdentifier(), Category);
173 }
174};
175
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000176class DataFlowSanitizer : public ModulePass {
177 friend struct DFSanFunction;
178 friend class DFSanVisitor;
179
180 enum {
181 ShadowWidth = 16
182 };
183
Peter Collingbourne68162e72013-08-14 18:54:12 +0000184 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000185 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000186 /// Argument and return value labels are passed through additional
187 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000188 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000189
190 /// Argument and return value labels are passed through TLS variables
191 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000192 IA_TLS
193 };
194
Peter Collingbourne68162e72013-08-14 18:54:12 +0000195 /// How should calls to uninstrumented functions be handled?
196 enum WrapperKind {
197 /// This function is present in an uninstrumented form but we don't know
198 /// how it should be handled. Print a warning and call the function anyway.
199 /// Don't label the return value.
200 WK_Warning,
201
202 /// This function does not write to (user-accessible) memory, and its return
203 /// value is unlabelled.
204 WK_Discard,
205
206 /// This function does not write to (user-accessible) memory, and the label
207 /// of its return value is the union of the label of its arguments.
208 WK_Functional,
209
210 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
211 /// where F is the name of the function. This function may wrap the
212 /// original function or provide its own implementation. This is similar to
213 /// the IA_Args ABI, except that IA_Args uses a struct return type to
214 /// pass the return value shadow in a register, while WK_Custom uses an
215 /// extra pointer argument to return the shadow. This allows the wrapped
216 /// form of the function type to be expressed in C.
217 WK_Custom
218 };
219
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000220 const DataLayout *DL;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000221 Module *Mod;
222 LLVMContext *Ctx;
223 IntegerType *ShadowTy;
224 PointerType *ShadowPtrTy;
225 IntegerType *IntptrTy;
226 ConstantInt *ZeroShadow;
227 ConstantInt *ShadowPtrMask;
228 ConstantInt *ShadowPtrMul;
229 Constant *ArgTLS;
230 Constant *RetvalTLS;
231 void *(*GetArgTLSPtr)();
232 void *(*GetRetvalTLSPtr)();
233 Constant *GetArgTLS;
234 Constant *GetRetvalTLS;
235 FunctionType *DFSanUnionFnTy;
236 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000237 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000238 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000239 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournea1099842014-11-05 17:21:00 +0000240 FunctionType *DFSanVarargWrapperFnTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000241 Constant *DFSanUnionFn;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000242 Constant *DFSanCheckedUnionFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000243 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000244 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000245 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000246 Constant *DFSanNonzeroLabelFn;
Peter Collingbournea1099842014-11-05 17:21:00 +0000247 Constant *DFSanVarargWrapperFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000248 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000249 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000250 DenseMap<Value *, Function *> UnwrappedFnMap;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000251 AttributeSet ReadOnlyNoneAttrs;
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000252 DenseMap<const Function *, DISubprogram> FunctionDIs;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000253
254 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000255 bool isInstrumented(const Function *F);
256 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000257 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000258 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000259 FunctionType *getCustomFunctionType(FunctionType *T);
260 InstrumentedABI getInstrumentedABI();
261 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000262 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000263 Function *buildWrapperFunction(Function *F, StringRef NewFName,
264 GlobalValue::LinkageTypes NewFLink,
265 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000266 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000267
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000268 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000269 DataFlowSanitizer(
270 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
271 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000272 static char ID;
Craig Topper3e4c6972014-03-05 09:10:37 +0000273 bool doInitialization(Module &M) override;
274 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000275};
276
277struct DFSanFunction {
278 DataFlowSanitizer &DFS;
279 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000280 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000281 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000282 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000283 Value *ArgTLSPtr;
284 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000285 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000286 DenseMap<Value *, Value *> ValShadowMap;
287 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
288 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
289 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000290 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000291 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000292
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000293 struct CachedCombinedShadow {
294 BasicBlock *Block;
295 Value *Shadow;
296 };
297 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
298 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000299 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000300
Peter Collingbourne68162e72013-08-14 18:54:12 +0000301 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
302 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000303 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000304 LabelReturnAlloca(nullptr) {
305 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000306 // FIXME: Need to track down the register allocator issue which causes poor
307 // performance in pathological cases with large numbers of basic blocks.
308 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000309 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000310 Value *getArgTLSPtr();
311 Value *getArgTLS(unsigned Index, Instruction *Pos);
312 Value *getRetvalTLS();
313 Value *getShadow(Value *V);
314 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000315 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000316 Value *combineOperandShadows(Instruction *Inst);
317 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
318 Instruction *Pos);
319 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
320 Instruction *Pos);
321};
322
323class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000324 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000325 DFSanFunction &DFSF;
326 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
327
328 void visitOperandShadowInst(Instruction &I);
329
330 void visitBinaryOperator(BinaryOperator &BO);
331 void visitCastInst(CastInst &CI);
332 void visitCmpInst(CmpInst &CI);
333 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
334 void visitLoadInst(LoadInst &LI);
335 void visitStoreInst(StoreInst &SI);
336 void visitReturnInst(ReturnInst &RI);
337 void visitCallSite(CallSite CS);
338 void visitPHINode(PHINode &PN);
339 void visitExtractElementInst(ExtractElementInst &I);
340 void visitInsertElementInst(InsertElementInst &I);
341 void visitShuffleVectorInst(ShuffleVectorInst &I);
342 void visitExtractValueInst(ExtractValueInst &I);
343 void visitInsertValueInst(InsertValueInst &I);
344 void visitAllocaInst(AllocaInst &I);
345 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000346 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000347 void visitMemTransferInst(MemTransferInst &I);
348};
349
350}
351
352char DataFlowSanitizer::ID;
353INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
354 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
355
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000356ModulePass *
357llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
358 void *(*getArgTLS)(),
359 void *(*getRetValTLS)()) {
360 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000361}
362
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000363DataFlowSanitizer::DataFlowSanitizer(
364 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
365 void *(*getRetValTLS)())
366 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
367 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
368 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
369 ClABIListFiles.end());
370 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
Peter Collingbourne68162e72013-08-14 18:54:12 +0000371}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000372
Peter Collingbourne68162e72013-08-14 18:54:12 +0000373FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000374 llvm::SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
375 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000376 if (T->isVarArg())
377 ArgTypes.push_back(ShadowPtrTy);
378 Type *RetType = T->getReturnType();
379 if (!RetType->isVoidTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000380 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000381 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
382}
383
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000384FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
385 assert(!T->isVarArg());
386 llvm::SmallVector<Type *, 4> ArgTypes;
387 ArgTypes.push_back(T->getPointerTo());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000388 ArgTypes.append(T->param_begin(), T->param_end());
389 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000390 Type *RetType = T->getReturnType();
391 if (!RetType->isVoidTy())
392 ArgTypes.push_back(ShadowPtrTy);
393 return FunctionType::get(T->getReturnType(), ArgTypes, false);
394}
395
Peter Collingbourne68162e72013-08-14 18:54:12 +0000396FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000397 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000398 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
399 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000400 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000401 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
402 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000403 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
404 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
405 } else {
406 ArgTypes.push_back(*i);
407 }
408 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000409 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
410 ArgTypes.push_back(ShadowTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000411 if (T->isVarArg())
412 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000413 Type *RetType = T->getReturnType();
414 if (!RetType->isVoidTy())
415 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000416 return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000417}
418
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000419bool DataFlowSanitizer::doInitialization(Module &M) {
Peter Collingbourne0826e602014-12-05 21:22:32 +0000420 llvm::Triple TargetTriple(M.getTargetTriple());
421 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
422 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
423 TargetTriple.getArch() == llvm::Triple::mips64el;
424
Mehdi Amini46a43552015-03-04 18:43:29 +0000425 DL = &M.getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000426
427 Mod = &M;
428 Ctx = &M.getContext();
429 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
430 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
431 IntptrTy = DL->getIntPtrType(*Ctx);
432 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000433 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000434 if (IsX86_64)
435 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
436 else if (IsMIPS64)
437 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
438 else
439 report_fatal_error("unsupported triple");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000440
441 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
442 DFSanUnionFnTy =
443 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
444 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
445 DFSanUnionLoadFnTy =
446 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000447 DFSanUnimplementedFnTy = FunctionType::get(
448 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000449 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
450 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
451 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000452 DFSanNonzeroLabelFnTy = FunctionType::get(
Craig Toppere1d12942014-08-27 05:25:25 +0000453 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
Peter Collingbournea1099842014-11-05 17:21:00 +0000454 DFSanVarargWrapperFnTy = FunctionType::get(
455 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000456
457 if (GetArgTLSPtr) {
458 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000459 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000460 GetArgTLS = ConstantExpr::getIntToPtr(
461 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
462 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000463 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
464 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000465 }
466 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000467 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000468 GetRetvalTLS = ConstantExpr::getIntToPtr(
469 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
470 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000471 FunctionType::get(PointerType::getUnqual(ShadowTy),
472 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000473 }
474
475 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
476 return true;
477}
478
Peter Collingbourne59b12622013-08-22 20:08:08 +0000479bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000480 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000481}
482
Peter Collingbourne59b12622013-08-22 20:08:08 +0000483bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000484 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000485}
486
Peter Collingbourne68162e72013-08-14 18:54:12 +0000487DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000488 return ClArgsABI ? IA_Args : IA_TLS;
489}
490
Peter Collingbourne68162e72013-08-14 18:54:12 +0000491DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000492 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000493 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000494 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000495 return WK_Discard;
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000496 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000497 return WK_Custom;
498
499 return WK_Warning;
500}
501
Peter Collingbourne59b12622013-08-22 20:08:08 +0000502void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
503 std::string GVName = GV->getName(), Prefix = "dfs$";
504 GV->setName(Prefix + GVName);
505
506 // Try to change the name of the function in module inline asm. We only do
507 // this for specific asm directives, currently only ".symver", to try to avoid
508 // corrupting asm which happens to contain the symbol name as a substring.
509 // Note that the substitution for .symver assumes that the versioned symbol
510 // also has an instrumented name.
511 std::string Asm = GV->getParent()->getModuleInlineAsm();
512 std::string SearchStr = ".symver " + GVName + ",";
513 size_t Pos = Asm.find(SearchStr);
514 if (Pos != std::string::npos) {
515 Asm.replace(Pos, SearchStr.size(),
516 ".symver " + Prefix + GVName + "," + Prefix);
517 GV->getParent()->setModuleInlineAsm(Asm);
518 }
519}
520
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000521Function *
522DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
523 GlobalValue::LinkageTypes NewFLink,
524 FunctionType *NewFT) {
525 FunctionType *FT = F->getFunctionType();
526 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
527 F->getParent());
528 NewF->copyAttributesFrom(F);
529 NewF->removeAttributes(
530 AttributeSet::ReturnIndex,
531 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
532 AttributeSet::ReturnIndex));
533
534 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
Peter Collingbournea1099842014-11-05 17:21:00 +0000535 if (F->isVarArg()) {
536 NewF->removeAttributes(
537 AttributeSet::FunctionIndex,
538 AttributeSet().addAttribute(*Ctx, AttributeSet::FunctionIndex,
539 "split-stack"));
540 CallInst::Create(DFSanVarargWrapperFn,
541 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
542 BB);
543 new UnreachableInst(*Ctx, BB);
544 } else {
545 std::vector<Value *> Args;
546 unsigned n = FT->getNumParams();
547 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
548 Args.push_back(&*ai);
549 CallInst *CI = CallInst::Create(F, Args, "", BB);
550 if (FT->getReturnType()->isVoidTy())
551 ReturnInst::Create(*Ctx, BB);
552 else
553 ReturnInst::Create(*Ctx, CI, BB);
554 }
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000555
556 return NewF;
557}
558
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000559Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
560 StringRef FName) {
561 FunctionType *FTT = getTrampolineFunctionType(FT);
562 Constant *C = Mod->getOrInsertFunction(FName, FTT);
563 Function *F = dyn_cast<Function>(C);
564 if (F && F->isDeclaration()) {
565 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
566 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
567 std::vector<Value *> Args;
568 Function::arg_iterator AI = F->arg_begin(); ++AI;
569 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
570 Args.push_back(&*AI);
571 CallInst *CI =
572 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
573 ReturnInst *RI;
574 if (FT->getReturnType()->isVoidTy())
575 RI = ReturnInst::Create(*Ctx, BB);
576 else
577 RI = ReturnInst::Create(*Ctx, CI, BB);
578
579 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
580 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
581 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
582 DFSF.ValShadowMap[ValAI] = ShadowAI;
583 DFSanVisitor(DFSF).visitCallInst(*CI);
584 if (!FT->getReturnType()->isVoidTy())
585 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
586 &F->getArgumentList().back(), RI);
587 }
588
589 return C;
590}
591
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000592bool DataFlowSanitizer::runOnModule(Module &M) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000593
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000594 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000595 return false;
596
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000597 FunctionDIs = makeSubprogramMap(M);
598
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000599 if (!GetArgTLSPtr) {
600 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
601 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
602 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
603 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
604 }
605 if (!GetRetvalTLSPtr) {
606 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
607 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
608 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
609 }
610
611 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
612 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000613 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
614 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
615 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
616 F->addAttribute(1, Attribute::ZExt);
617 F->addAttribute(2, Attribute::ZExt);
618 }
619 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
620 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
621 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000622 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
623 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
624 F->addAttribute(1, Attribute::ZExt);
625 F->addAttribute(2, Attribute::ZExt);
626 }
627 DFSanUnionLoadFn =
628 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
629 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000630 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000631 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000632 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
633 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000634 DFSanUnimplementedFn =
635 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000636 DFSanSetLabelFn =
637 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
638 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
639 F->addAttribute(1, Attribute::ZExt);
640 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000641 DFSanNonzeroLabelFn =
642 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournea1099842014-11-05 17:21:00 +0000643 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
644 DFSanVarargWrapperFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000645
646 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000647 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000648 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000649 if (!i->isIntrinsic() &&
650 i != DFSanUnionFn &&
Peter Collingbournedf240b22014-08-06 00:33:40 +0000651 i != DFSanCheckedUnionFn &&
Peter Collingbourne68162e72013-08-14 18:54:12 +0000652 i != DFSanUnionLoadFn &&
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000653 i != DFSanUnimplementedFn &&
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000654 i != DFSanSetLabelFn &&
Peter Collingbournea1099842014-11-05 17:21:00 +0000655 i != DFSanNonzeroLabelFn &&
656 i != DFSanVarargWrapperFn)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000657 FnsToInstrument.push_back(&*i);
658 }
659
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000660 // Give function aliases prefixes when necessary, and build wrappers where the
661 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000662 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
663 GlobalAlias *GA = &*i;
664 ++i;
665 // Don't stop on weak. We assume people aren't playing games with the
666 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000667 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000668 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
669 if (GAInst && FInst) {
670 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000671 } else if (GAInst != FInst) {
672 // Non-instrumented alias of an instrumented function, or vice versa.
673 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
674 // below will take care of instrumenting it.
675 Function *NewF =
676 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000677 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000678 NewF->takeName(GA);
679 GA->eraseFromParent();
680 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000681 }
682 }
683 }
684
Peter Collingbourne68162e72013-08-14 18:54:12 +0000685 AttrBuilder B;
686 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
687 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
688
689 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000690 // functions keep their original ABI and get a wrapper function.
691 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
692 e = FnsToInstrument.end();
693 i != e; ++i) {
694 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000695 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000696
Peter Collingbourne59b12622013-08-22 20:08:08 +0000697 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
698 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000699
700 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000701 // Instrumented functions get a 'dfs$' prefix. This allows us to more
702 // easily identify cases of mismatching ABIs.
703 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000704 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000705 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000706 NewF->copyAttributesFrom(&F);
707 NewF->removeAttributes(
708 AttributeSet::ReturnIndex,
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000709 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000710 AttributeSet::ReturnIndex));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000711 for (Function::arg_iterator FArg = F.arg_begin(),
712 NewFArg = NewF->arg_begin(),
713 FArgEnd = F.arg_end();
714 FArg != FArgEnd; ++FArg, ++NewFArg) {
715 FArg->replaceAllUsesWith(NewFArg);
716 }
717 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
718
Chandler Carruthcdf47882014-03-09 03:16:01 +0000719 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
720 UI != UE;) {
721 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
722 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000723 if (BA) {
724 BA->replaceAllUsesWith(
725 BlockAddress::get(NewF, BA->getBasicBlock()));
726 delete BA;
727 }
728 }
729 F.replaceAllUsesWith(
730 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
731 NewF->takeName(&F);
732 F.eraseFromParent();
733 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000734 addGlobalNamePrefix(NewF);
735 } else {
736 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000737 }
Peter Collingbourne59b12622013-08-22 20:08:08 +0000738 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000739 // Build a wrapper function for F. The wrapper simply calls F, and is
740 // added to FnsToInstrument so that any instrumentation according to its
741 // WrapperKind is done in the second pass below.
742 FunctionType *NewFT = getInstrumentedABI() == IA_Args
743 ? getArgsFunctionType(FT)
744 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000745 Function *NewF = buildWrapperFunction(
746 &F, std::string("dfsw$") + std::string(F.getName()),
747 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000748 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000749 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000750
Peter Collingbourne68162e72013-08-14 18:54:12 +0000751 Value *WrappedFnCst =
752 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
753 F.replaceAllUsesWith(WrappedFnCst);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000754
755 // Patch the pointer to LLVM function in debug info descriptor.
756 auto DI = FunctionDIs.find(&F);
757 if (DI != FunctionDIs.end())
758 DI->second.replaceFunction(&F);
759
Peter Collingbourne68162e72013-08-14 18:54:12 +0000760 UnwrappedFnMap[WrappedFnCst] = &F;
761 *i = NewF;
762
763 if (!F.isDeclaration()) {
764 // This function is probably defining an interposition of an
765 // uninstrumented function and hence needs to keep the original ABI.
766 // But any functions it may call need to use the instrumented ABI, so
767 // we instrument it in a mode which preserves the original ABI.
768 FnsWithNativeABI.insert(&F);
769
770 // This code needs to rebuild the iterators, as they may be invalidated
771 // by the push_back, taking care that the new range does not include
772 // any functions added by this code.
773 size_t N = i - FnsToInstrument.begin(),
774 Count = e - FnsToInstrument.begin();
775 FnsToInstrument.push_back(&F);
776 i = FnsToInstrument.begin() + N;
777 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000778 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000779 // Hopefully, nobody will try to indirectly call a vararg
780 // function... yet.
781 } else if (FT->isVarArg()) {
782 UnwrappedFnMap[&F] = &F;
783 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000784 }
785 }
786
787 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
788 e = FnsToInstrument.end();
789 i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000790 if (!*i || (*i)->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000791 continue;
792
Peter Collingbourneae66d572013-08-09 21:42:53 +0000793 removeUnreachableBlocks(**i);
794
Peter Collingbourne68162e72013-08-14 18:54:12 +0000795 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000796
797 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
798 // Build a copy of the list before iterating over it.
David Blaikieceec2bd2014-04-11 01:50:01 +0000799 llvm::SmallVector<BasicBlock *, 4> BBList(
800 depth_first(&(*i)->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000801
802 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
803 e = BBList.end();
804 i != e; ++i) {
805 Instruction *Inst = &(*i)->front();
806 while (1) {
807 // DFSanVisitor may split the current basic block, changing the current
808 // instruction's next pointer and moving the next instruction to the
809 // tail block from which we should continue.
810 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000811 // DFSanVisitor may delete Inst, so keep track of whether it was a
812 // terminator.
813 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000814 if (!DFSF.SkipInsts.count(Inst))
815 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000816 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000817 break;
818 Inst = Next;
819 }
820 }
821
Peter Collingbourne68162e72013-08-14 18:54:12 +0000822 // We will not necessarily be able to compute the shadow for every phi node
823 // until we have visited every block. Therefore, the code that handles phi
824 // nodes adds them to the PHIFixups list so that they can be properly
825 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000826 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
827 i = DFSF.PHIFixups.begin(),
828 e = DFSF.PHIFixups.end();
829 i != e; ++i) {
830 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
831 ++val) {
832 i->second->setIncomingValue(
833 val, DFSF.getShadow(i->first->getIncomingValue(val)));
834 }
835 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000836
837 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
838 // places (i.e. instructions in basic blocks we haven't even begun visiting
839 // yet). To make our life easier, do this work in a pass after the main
840 // instrumentation.
841 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000842 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000843 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000844 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000845 Pos = I->getNextNode();
846 else
847 Pos = DFSF.F->getEntryBlock().begin();
848 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
849 Pos = Pos->getNextNode();
850 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000851 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000852 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000853 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000854 IRBuilder<> ThenIRB(BI);
855 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
856 }
857 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000858 }
859
860 return false;
861}
862
863Value *DFSanFunction::getArgTLSPtr() {
864 if (ArgTLSPtr)
865 return ArgTLSPtr;
866 if (DFS.ArgTLS)
867 return ArgTLSPtr = DFS.ArgTLS;
868
869 IRBuilder<> IRB(F->getEntryBlock().begin());
870 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
871}
872
873Value *DFSanFunction::getRetvalTLS() {
874 if (RetvalTLSPtr)
875 return RetvalTLSPtr;
876 if (DFS.RetvalTLS)
877 return RetvalTLSPtr = DFS.RetvalTLS;
878
879 IRBuilder<> IRB(F->getEntryBlock().begin());
880 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
881}
882
883Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
884 IRBuilder<> IRB(Pos);
885 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
886}
887
888Value *DFSanFunction::getShadow(Value *V) {
889 if (!isa<Argument>(V) && !isa<Instruction>(V))
890 return DFS.ZeroShadow;
891 Value *&Shadow = ValShadowMap[V];
892 if (!Shadow) {
893 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000894 if (IsNativeABI)
895 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000896 switch (IA) {
897 case DataFlowSanitizer::IA_TLS: {
898 Value *ArgTLSPtr = getArgTLSPtr();
899 Instruction *ArgTLSPos =
900 DFS.ArgTLS ? &*F->getEntryBlock().begin()
901 : cast<Instruction>(ArgTLSPtr)->getNextNode();
902 IRBuilder<> IRB(ArgTLSPos);
903 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
904 break;
905 }
906 case DataFlowSanitizer::IA_Args: {
907 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
908 Function::arg_iterator i = F->arg_begin();
909 while (ArgIdx--)
910 ++i;
911 Shadow = i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000912 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000913 break;
914 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000915 }
Peter Collingbournefab565a2014-08-22 01:18:18 +0000916 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000917 } else {
918 Shadow = DFS.ZeroShadow;
919 }
920 }
921 return Shadow;
922}
923
924void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
925 assert(!ValShadowMap.count(I));
926 assert(Shadow->getType() == DFS.ShadowTy);
927 ValShadowMap[I] = Shadow;
928}
929
930Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
931 assert(Addr != RetvalTLS && "Reinstrumenting?");
932 IRBuilder<> IRB(Pos);
933 return IRB.CreateIntToPtr(
934 IRB.CreateMul(
935 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
936 ShadowPtrMul),
937 ShadowPtrTy);
938}
939
940// Generates IR to compute the union of the two given shadows, inserting it
941// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000942Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
943 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000944 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000945 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000946 return V1;
947 if (V1 == V2)
948 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000949
Peter Collingbourne9947c492014-07-15 22:13:19 +0000950 auto V1Elems = ShadowElements.find(V1);
951 auto V2Elems = ShadowElements.find(V2);
952 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
953 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
954 V2Elems->second.begin(), V2Elems->second.end())) {
955 return V1;
956 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
957 V1Elems->second.begin(), V1Elems->second.end())) {
958 return V2;
959 }
960 } else if (V1Elems != ShadowElements.end()) {
961 if (V1Elems->second.count(V2))
962 return V1;
963 } else if (V2Elems != ShadowElements.end()) {
964 if (V2Elems->second.count(V1))
965 return V2;
966 }
967
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000968 auto Key = std::make_pair(V1, V2);
969 if (V1 > V2)
970 std::swap(Key.first, Key.second);
971 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
972 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
973 return CCS.Shadow;
974
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000975 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000976 if (AvoidNewBlocks) {
977 CallInst *Call = IRB.CreateCall2(DFS.DFSanCheckedUnionFn, V1, V2);
978 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
979 Call->addAttribute(1, Attribute::ZExt);
980 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000981
Peter Collingbournedf240b22014-08-06 00:33:40 +0000982 CCS.Block = Pos->getParent();
983 CCS.Shadow = Call;
984 } else {
985 BasicBlock *Head = Pos->getParent();
986 Value *Ne = IRB.CreateICmpNE(V1, V2);
987 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
988 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
989 IRBuilder<> ThenIRB(BI);
990 CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
991 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
992 Call->addAttribute(1, Attribute::ZExt);
993 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000994
Peter Collingbournedf240b22014-08-06 00:33:40 +0000995 BasicBlock *Tail = BI->getSuccessor(0);
996 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
997 Phi->addIncoming(Call, Call->getParent());
998 Phi->addIncoming(V1, Head);
999
1000 CCS.Block = Tail;
1001 CCS.Shadow = Phi;
1002 }
Peter Collingbourne9947c492014-07-15 22:13:19 +00001003
1004 std::set<Value *> UnionElems;
1005 if (V1Elems != ShadowElements.end()) {
1006 UnionElems = V1Elems->second;
1007 } else {
1008 UnionElems.insert(V1);
1009 }
1010 if (V2Elems != ShadowElements.end()) {
1011 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1012 } else {
1013 UnionElems.insert(V2);
1014 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001015 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +00001016
Peter Collingbournedf240b22014-08-06 00:33:40 +00001017 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001018}
1019
1020// A convenience function which folds the shadows of each of the operands
1021// of the provided instruction Inst, inserting the IR before Inst. Returns
1022// the computed union Value.
1023Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1024 if (Inst->getNumOperands() == 0)
1025 return DFS.ZeroShadow;
1026
1027 Value *Shadow = getShadow(Inst->getOperand(0));
1028 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001029 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001030 }
1031 return Shadow;
1032}
1033
1034void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1035 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1036 DFSF.setShadow(&I, CombinedShadow);
1037}
1038
1039// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1040// Addr has alignment Align, and take the union of each of those shadows.
1041Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1042 Instruction *Pos) {
1043 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1044 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1045 AllocaShadowMap.find(AI);
1046 if (i != AllocaShadowMap.end()) {
1047 IRBuilder<> IRB(Pos);
1048 return IRB.CreateLoad(i->second);
1049 }
1050 }
1051
1052 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1053 SmallVector<Value *, 2> Objs;
1054 GetUnderlyingObjects(Addr, Objs, DFS.DL);
1055 bool AllConstants = true;
1056 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1057 i != e; ++i) {
1058 if (isa<Function>(*i) || isa<BlockAddress>(*i))
1059 continue;
1060 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1061 continue;
1062
1063 AllConstants = false;
1064 break;
1065 }
1066 if (AllConstants)
1067 return DFS.ZeroShadow;
1068
1069 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1070 switch (Size) {
1071 case 0:
1072 return DFS.ZeroShadow;
1073 case 1: {
1074 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1075 LI->setAlignment(ShadowAlign);
1076 return LI;
1077 }
1078 case 2: {
1079 IRBuilder<> IRB(Pos);
1080 Value *ShadowAddr1 =
1081 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001082 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1083 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001084 }
1085 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001086 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001087 // Fast path for the common case where each byte has identical shadow: load
1088 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1089 // shadow is non-equal.
1090 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1091 IRBuilder<> FallbackIRB(FallbackBB);
1092 CallInst *FallbackCall = FallbackIRB.CreateCall2(
1093 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1094 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1095
1096 // Compare each of the shadows stored in the loaded 64 bits to each other,
1097 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1098 IRBuilder<> IRB(Pos);
1099 Value *WideAddr =
1100 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1101 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1102 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1103 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1104 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1105 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1106 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1107
1108 BasicBlock *Head = Pos->getParent();
1109 BasicBlock *Tail = Head->splitBasicBlock(Pos);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001110
1111 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1112 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1113
1114 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1115 for (auto Child : Children)
1116 DT.changeImmediateDominator(Child, NewNode);
1117 }
1118
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001119 // In the following code LastBr will refer to the previous basic block's
1120 // conditional branch instruction, whose true successor is fixed up to point
1121 // to the next block during the loop below or to the tail after the final
1122 // iteration.
1123 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1124 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001125 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001126
1127 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1128 Ofs += 64 / DFS.ShadowWidth) {
1129 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001130 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001131 IRBuilder<> NextIRB(NextBB);
1132 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1133 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1134 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1135 LastBr->setSuccessor(0, NextBB);
1136 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1137 }
1138
1139 LastBr->setSuccessor(0, Tail);
1140 FallbackIRB.CreateBr(Tail);
1141 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1142 Shadow->addIncoming(FallbackCall, FallbackBB);
1143 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1144 return Shadow;
1145 }
1146
1147 IRBuilder<> IRB(Pos);
1148 CallInst *FallbackCall = IRB.CreateCall2(
1149 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1150 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1151 return FallbackCall;
1152}
1153
1154void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1155 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001156 if (Size == 0) {
1157 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1158 return;
1159 }
1160
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001161 uint64_t Align;
1162 if (ClPreserveAlignment) {
1163 Align = LI.getAlignment();
1164 if (Align == 0)
1165 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1166 } else {
1167 Align = 1;
1168 }
1169 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001170 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1171 if (ClCombinePointerLabelsOnLoad) {
1172 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001173 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001174 }
1175 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001176 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001177
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001178 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001179}
1180
1181void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1182 Value *Shadow, Instruction *Pos) {
1183 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1184 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1185 AllocaShadowMap.find(AI);
1186 if (i != AllocaShadowMap.end()) {
1187 IRBuilder<> IRB(Pos);
1188 IRB.CreateStore(Shadow, i->second);
1189 return;
1190 }
1191 }
1192
1193 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1194 IRBuilder<> IRB(Pos);
1195 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1196 if (Shadow == DFS.ZeroShadow) {
1197 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1198 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1199 Value *ExtShadowAddr =
1200 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1201 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1202 return;
1203 }
1204
1205 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1206 uint64_t Offset = 0;
1207 if (Size >= ShadowVecSize) {
1208 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1209 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1210 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1211 ShadowVec = IRB.CreateInsertElement(
1212 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1213 }
1214 Value *ShadowVecAddr =
1215 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1216 do {
1217 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1218 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1219 Size -= ShadowVecSize;
1220 ++Offset;
1221 } while (Size >= ShadowVecSize);
1222 Offset *= ShadowVecSize;
1223 }
1224 while (Size > 0) {
1225 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1226 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1227 --Size;
1228 ++Offset;
1229 }
1230}
1231
1232void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1233 uint64_t Size =
1234 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001235 if (Size == 0)
1236 return;
1237
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001238 uint64_t Align;
1239 if (ClPreserveAlignment) {
1240 Align = SI.getAlignment();
1241 if (Align == 0)
1242 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1243 } else {
1244 Align = 1;
1245 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001246
1247 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1248 if (ClCombinePointerLabelsOnStore) {
1249 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001250 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001251 }
1252 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001253}
1254
1255void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1256 visitOperandShadowInst(BO);
1257}
1258
1259void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1260
1261void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1262
1263void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1264 visitOperandShadowInst(GEPI);
1265}
1266
1267void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1268 visitOperandShadowInst(I);
1269}
1270
1271void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1272 visitOperandShadowInst(I);
1273}
1274
1275void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1276 visitOperandShadowInst(I);
1277}
1278
1279void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1280 visitOperandShadowInst(I);
1281}
1282
1283void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1284 visitOperandShadowInst(I);
1285}
1286
1287void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1288 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001289 for (User *U : I.users()) {
1290 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001291 continue;
1292
Chandler Carruthcdf47882014-03-09 03:16:01 +00001293 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001294 if (SI->getPointerOperand() == &I)
1295 continue;
1296 }
1297
1298 AllLoadsStores = false;
1299 break;
1300 }
1301 if (AllLoadsStores) {
1302 IRBuilder<> IRB(&I);
1303 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1304 }
1305 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1306}
1307
1308void DFSanVisitor::visitSelectInst(SelectInst &I) {
1309 Value *CondShadow = DFSF.getShadow(I.getCondition());
1310 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1311 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1312
1313 if (isa<VectorType>(I.getCondition()->getType())) {
1314 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001315 &I,
1316 DFSF.combineShadows(
1317 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001318 } else {
1319 Value *ShadowSel;
1320 if (TrueShadow == FalseShadow) {
1321 ShadowSel = TrueShadow;
1322 } else {
1323 ShadowSel =
1324 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1325 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001326 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001327 }
1328}
1329
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001330void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1331 IRBuilder<> IRB(&I);
1332 Value *ValShadow = DFSF.getShadow(I.getValue());
1333 IRB.CreateCall3(
1334 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1335 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1336 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1337}
1338
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001339void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1340 IRBuilder<> IRB(&I);
1341 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1342 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1343 Value *LenShadow = IRB.CreateMul(
1344 I.getLength(),
1345 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1346 Value *AlignShadow;
1347 if (ClPreserveAlignment) {
1348 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1349 ConstantInt::get(I.getAlignmentCst()->getType(),
1350 DFSF.DFS.ShadowWidth / 8));
1351 } else {
1352 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1353 DFSF.DFS.ShadowWidth / 8);
1354 }
1355 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1356 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1357 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1358 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1359 AlignShadow, I.getVolatileCst());
1360}
1361
1362void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001363 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001364 switch (DFSF.IA) {
1365 case DataFlowSanitizer::IA_TLS: {
1366 Value *S = DFSF.getShadow(RI.getReturnValue());
1367 IRBuilder<> IRB(&RI);
1368 IRB.CreateStore(S, DFSF.getRetvalTLS());
1369 break;
1370 }
1371 case DataFlowSanitizer::IA_Args: {
1372 IRBuilder<> IRB(&RI);
1373 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1374 Value *InsVal =
1375 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1376 Value *InsShadow =
1377 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1378 RI.setOperand(0, InsShadow);
1379 break;
1380 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001381 }
1382 }
1383}
1384
1385void DFSanVisitor::visitCallSite(CallSite CS) {
1386 Function *F = CS.getCalledFunction();
1387 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1388 visitOperandShadowInst(*CS.getInstruction());
1389 return;
1390 }
1391
Peter Collingbournea1099842014-11-05 17:21:00 +00001392 // Calls to this function are synthesized in wrappers, and we shouldn't
1393 // instrument them.
1394 if (F == DFSF.DFS.DFSanVarargWrapperFn)
1395 return;
1396
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +00001397 assert(!(cast<FunctionType>(
1398 CS.getCalledValue()->getType()->getPointerElementType())->isVarArg() &&
1399 dyn_cast<InvokeInst>(CS.getInstruction())));
1400
Peter Collingbourne68162e72013-08-14 18:54:12 +00001401 IRBuilder<> IRB(CS.getInstruction());
1402
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001403 DenseMap<Value *, Function *>::iterator i =
1404 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1405 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001406 Function *F = i->second;
1407 switch (DFSF.DFS.getWrapperKind(F)) {
1408 case DataFlowSanitizer::WK_Warning: {
1409 CS.setCalledFunction(F);
1410 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1411 IRB.CreateGlobalStringPtr(F->getName()));
1412 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1413 return;
1414 }
1415 case DataFlowSanitizer::WK_Discard: {
1416 CS.setCalledFunction(F);
1417 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1418 return;
1419 }
1420 case DataFlowSanitizer::WK_Functional: {
1421 CS.setCalledFunction(F);
1422 visitOperandShadowInst(*CS.getInstruction());
1423 return;
1424 }
1425 case DataFlowSanitizer::WK_Custom: {
1426 // Don't try to handle invokes of custom functions, it's too complicated.
1427 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1428 // wrapper.
1429 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1430 FunctionType *FT = F->getFunctionType();
1431 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1432 std::string CustomFName = "__dfsw_";
1433 CustomFName += F->getName();
1434 Constant *CustomF =
1435 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1436 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1437 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001438
Peter Collingbourne68162e72013-08-14 18:54:12 +00001439 // Custom functions returning non-void will write to the return label.
1440 if (!FT->getReturnType()->isVoidTy()) {
1441 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1442 DFSF.DFS.ReadOnlyNoneAttrs);
1443 }
1444 }
1445
1446 std::vector<Value *> Args;
1447
1448 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001449 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001450 Type *T = (*i)->getType();
1451 FunctionType *ParamFT;
1452 if (isa<PointerType>(T) &&
1453 (ParamFT = dyn_cast<FunctionType>(
1454 cast<PointerType>(T)->getElementType()))) {
1455 std::string TName = "dfst";
1456 TName += utostr(FT->getNumParams() - n);
1457 TName += "$";
1458 TName += F->getName();
1459 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1460 Args.push_back(T);
1461 Args.push_back(
1462 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1463 } else {
1464 Args.push_back(*i);
1465 }
1466 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001467
1468 i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001469 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Peter Collingbourne68162e72013-08-14 18:54:12 +00001470 Args.push_back(DFSF.getShadow(*i));
1471
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001472 if (FT->isVarArg()) {
1473 auto LabelVAAlloca =
1474 new AllocaInst(ArrayType::get(DFSF.DFS.ShadowTy,
1475 CS.arg_size() - FT->getNumParams()),
1476 "labelva", DFSF.F->getEntryBlock().begin());
1477
1478 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
1479 auto LabelVAPtr = IRB.CreateStructGEP(LabelVAAlloca, n);
1480 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1481 }
1482
1483 Args.push_back(IRB.CreateStructGEP(LabelVAAlloca, 0));
1484 }
1485
Peter Collingbourne68162e72013-08-14 18:54:12 +00001486 if (!FT->getReturnType()->isVoidTy()) {
1487 if (!DFSF.LabelReturnAlloca) {
1488 DFSF.LabelReturnAlloca =
1489 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1490 DFSF.F->getEntryBlock().begin());
1491 }
1492 Args.push_back(DFSF.LabelReturnAlloca);
1493 }
1494
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001495 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1496 Args.push_back(*i);
1497
Peter Collingbourne68162e72013-08-14 18:54:12 +00001498 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1499 CustomCI->setCallingConv(CI->getCallingConv());
1500 CustomCI->setAttributes(CI->getAttributes());
1501
1502 if (!FT->getReturnType()->isVoidTy()) {
1503 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1504 DFSF.setShadow(CustomCI, LabelLoad);
1505 }
1506
1507 CI->replaceAllUsesWith(CustomCI);
1508 CI->eraseFromParent();
1509 return;
1510 }
1511 break;
1512 }
1513 }
1514 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001515
1516 FunctionType *FT = cast<FunctionType>(
1517 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001518 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001519 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1520 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1521 DFSF.getArgTLS(i, CS.getInstruction()));
1522 }
1523 }
1524
Craig Topperf40110f2014-04-25 05:29:35 +00001525 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001526 if (!CS.getType()->isVoidTy()) {
1527 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1528 if (II->getNormalDest()->getSinglePredecessor()) {
1529 Next = II->getNormalDest()->begin();
1530 } else {
1531 BasicBlock *NewBB =
Chandler Carruthd4500562015-01-19 12:36:53 +00001532 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001533 Next = NewBB->begin();
1534 }
1535 } else {
1536 Next = CS->getNextNode();
1537 }
1538
Peter Collingbourne68162e72013-08-14 18:54:12 +00001539 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001540 IRBuilder<> NextIRB(Next);
1541 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1542 DFSF.SkipInsts.insert(LI);
1543 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001544 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001545 }
1546 }
1547
1548 // Do all instrumentation for IA_Args down here to defer tampering with the
1549 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001550 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1551 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001552 Value *Func =
1553 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1554 std::vector<Value *> Args;
1555
1556 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1557 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1558 Args.push_back(*i);
1559
1560 i = CS.arg_begin();
1561 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1562 Args.push_back(DFSF.getShadow(*i));
1563
1564 if (FT->isVarArg()) {
1565 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1566 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1567 AllocaInst *VarArgShadow =
1568 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1569 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1570 for (unsigned n = 0; i != e; ++i, ++n) {
1571 IRB.CreateStore(DFSF.getShadow(*i),
1572 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1573 Args.push_back(*i);
1574 }
1575 }
1576
1577 CallSite NewCS;
1578 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1579 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1580 Args);
1581 } else {
1582 NewCS = IRB.CreateCall(Func, Args);
1583 }
1584 NewCS.setCallingConv(CS.getCallingConv());
1585 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1586 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1587 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1588 AttributeSet::ReturnIndex)));
1589
1590 if (Next) {
1591 ExtractValueInst *ExVal =
1592 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1593 DFSF.SkipInsts.insert(ExVal);
1594 ExtractValueInst *ExShadow =
1595 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1596 DFSF.SkipInsts.insert(ExShadow);
1597 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001598 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001599
1600 CS.getInstruction()->replaceAllUsesWith(ExVal);
1601 }
1602
1603 CS.getInstruction()->eraseFromParent();
1604 }
1605}
1606
1607void DFSanVisitor::visitPHINode(PHINode &PN) {
1608 PHINode *ShadowPN =
1609 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1610
1611 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1612 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1613 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1614 ++i) {
1615 ShadowPN->addIncoming(UndefShadow, *i);
1616 }
1617
1618 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1619 DFSF.setShadow(&PN, ShadowPN);
1620}