5e6313a5a5aa41e0439ef0de5206e80920432a5f
[oota-llvm.git] / lib / Transforms / Instrumentation / DataFlowSanitizer.cpp
1 //===-- DataFlowSanitizer.cpp - dynamic data flow analysis ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
11 /// analysis.
12 ///
13 /// Unlike other Sanitizer tools, this tool is not designed to detect a specific
14 /// class of bugs on its own.  Instead, it provides a generic dynamic data flow
15 /// analysis framework to be used by clients to help detect application-specific
16 /// issues within their own code.
17 ///
18 /// The analysis is based on automatic propagation of data flow labels (also
19 /// known as taint labels) through a program as it performs computation.  Each
20 /// byte of application memory is backed by two bytes of shadow memory which
21 /// hold the label.  On Linux/x86_64, memory is laid out as follows:
22 ///
23 /// +--------------------+ 0x800000000000 (top of memory)
24 /// | application memory |
25 /// +--------------------+ 0x700000008000 (kAppAddr)
26 /// |                    |
27 /// |       unused       |
28 /// |                    |
29 /// +--------------------+ 0x200200000000 (kUnusedAddr)
30 /// |    union table     |
31 /// +--------------------+ 0x200000000000 (kUnionTableAddr)
32 /// |   shadow memory    |
33 /// +--------------------+ 0x000000010000 (kShadowAddr)
34 /// | reserved by kernel |
35 /// +--------------------+ 0x000000000000
36 ///
37 /// To derive a shadow memory address from an application memory address,
38 /// bits 44-46 are cleared to bring the address into the range
39 /// [0x000000008000,0x100000000000).  Then the address is shifted left by 1 to
40 /// account for the double byte representation of shadow labels and move the
41 /// address into the shadow memory range.  See the function
42 /// DataFlowSanitizer::getShadowAddress below.
43 ///
44 /// For more information, please refer to the design document:
45 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
46
47 #include "llvm/Transforms/Instrumentation.h"
48 #include "llvm/ADT/DenseMap.h"
49 #include "llvm/ADT/DenseSet.h"
50 #include "llvm/ADT/DepthFirstIterator.h"
51 #include "llvm/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/SpecialCaseList.h"
63 #include <iterator>
64
65 using namespace llvm;
66
67 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
68 // alignment requirements provided by the input IR are correct.  For example,
69 // if the input IR contains a load with alignment 8, this flag will cause
70 // the shadow load to have alignment 16.  This flag is disabled by default as
71 // we have unfortunately encountered too much code (including Clang itself;
72 // see PR14291) which performs misaligned access.
73 static cl::opt<bool> ClPreserveAlignment(
74     "dfsan-preserve-alignment",
75     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
76     cl::init(false));
77
78 // The greylist file controls how shadow parameters are passed.
79 // The program acts as though every function in the greylist is passed
80 // parameters with zero shadow and that its return value also has zero shadow.
81 // This avoids the use of TLS or extra function parameters to pass shadow state
82 // and essentially makes the function conform to the "native" (i.e. unsanitized)
83 // ABI.
84 static cl::opt<std::string> ClGreylistFile(
85     "dfsan-greylist",
86     cl::desc("File containing the list of functions with a native ABI"),
87     cl::Hidden);
88
89 static cl::opt<bool> ClArgsABI(
90     "dfsan-args-abi",
91     cl::desc("Use the argument ABI rather than the TLS ABI"),
92     cl::Hidden);
93
94 namespace {
95
96 class DataFlowSanitizer : public ModulePass {
97   friend struct DFSanFunction;
98   friend class DFSanVisitor;
99
100   enum {
101     ShadowWidth = 16
102   };
103
104   enum InstrumentedABI {
105     IA_None,
106     IA_MemOnly,
107     IA_Args,
108     IA_TLS
109   };
110
111   DataLayout *DL;
112   Module *Mod;
113   LLVMContext *Ctx;
114   IntegerType *ShadowTy;
115   PointerType *ShadowPtrTy;
116   IntegerType *IntptrTy;
117   ConstantInt *ZeroShadow;
118   ConstantInt *ShadowPtrMask;
119   ConstantInt *ShadowPtrMul;
120   Constant *ArgTLS;
121   Constant *RetvalTLS;
122   void *(*GetArgTLSPtr)();
123   void *(*GetRetvalTLSPtr)();
124   Constant *GetArgTLS;
125   Constant *GetRetvalTLS;
126   FunctionType *DFSanUnionFnTy;
127   FunctionType *DFSanUnionLoadFnTy;
128   Constant *DFSanUnionFn;
129   Constant *DFSanUnionLoadFn;
130   MDNode *ColdCallWeights;
131   SpecialCaseList Greylist;
132   DenseMap<Value *, Function *> UnwrappedFnMap;
133
134   Value *getShadowAddress(Value *Addr, Instruction *Pos);
135   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
136   FunctionType *getInstrumentedFunctionType(FunctionType *T);
137   InstrumentedABI getInstrumentedABI(Function *F);
138   InstrumentedABI getDefaultInstrumentedABI();
139
140 public:
141   DataFlowSanitizer(void *(*getArgTLS)() = 0, void *(*getRetValTLS)() = 0);
142   static char ID;
143   bool doInitialization(Module &M);
144   bool runOnModule(Module &M);
145 };
146
147 struct DFSanFunction {
148   DataFlowSanitizer &DFS;
149   Function *F;
150   DataFlowSanitizer::InstrumentedABI IA;
151   Value *ArgTLSPtr;
152   Value *RetvalTLSPtr;
153   DenseMap<Value *, Value *> ValShadowMap;
154   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
155   std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
156   DenseSet<Instruction *> SkipInsts;
157
158   DFSanFunction(DataFlowSanitizer &DFS, Function *F)
159       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI(F)), ArgTLSPtr(0),
160         RetvalTLSPtr(0) {}
161   Value *getArgTLSPtr();
162   Value *getArgTLS(unsigned Index, Instruction *Pos);
163   Value *getRetvalTLS();
164   Value *getShadow(Value *V);
165   void setShadow(Instruction *I, Value *Shadow);
166   Value *combineOperandShadows(Instruction *Inst);
167   Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
168                     Instruction *Pos);
169   void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
170                    Instruction *Pos);
171 };
172
173 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
174 public:
175   DFSanFunction &DFSF;
176   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
177
178   void visitOperandShadowInst(Instruction &I);
179
180   void visitBinaryOperator(BinaryOperator &BO);
181   void visitCastInst(CastInst &CI);
182   void visitCmpInst(CmpInst &CI);
183   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
184   void visitLoadInst(LoadInst &LI);
185   void visitStoreInst(StoreInst &SI);
186   void visitReturnInst(ReturnInst &RI);
187   void visitCallSite(CallSite CS);
188   void visitPHINode(PHINode &PN);
189   void visitExtractElementInst(ExtractElementInst &I);
190   void visitInsertElementInst(InsertElementInst &I);
191   void visitShuffleVectorInst(ShuffleVectorInst &I);
192   void visitExtractValueInst(ExtractValueInst &I);
193   void visitInsertValueInst(InsertValueInst &I);
194   void visitAllocaInst(AllocaInst &I);
195   void visitSelectInst(SelectInst &I);
196   void visitMemTransferInst(MemTransferInst &I);
197 };
198
199 }
200
201 char DataFlowSanitizer::ID;
202 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
203                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
204
205 ModulePass *llvm::createDataFlowSanitizerPass(void *(*getArgTLS)(),
206                                               void *(*getRetValTLS)()) {
207   return new DataFlowSanitizer(getArgTLS, getRetValTLS);
208 }
209
210 DataFlowSanitizer::DataFlowSanitizer(void *(*getArgTLS)(),
211                                      void *(*getRetValTLS)())
212     : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
213       Greylist(ClGreylistFile) {}
214
215 FunctionType *DataFlowSanitizer::getInstrumentedFunctionType(FunctionType *T) {
216   llvm::SmallVector<Type *, 4> ArgTypes;
217   std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
218   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
219     ArgTypes.push_back(ShadowTy);
220   if (T->isVarArg())
221     ArgTypes.push_back(ShadowPtrTy);
222   Type *RetType = T->getReturnType();
223   if (!RetType->isVoidTy())
224     RetType = StructType::get(RetType, ShadowTy, (Type *)0);
225   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
226 }
227
228 bool DataFlowSanitizer::doInitialization(Module &M) {
229   DL = getAnalysisIfAvailable<DataLayout>();
230   if (!DL)
231     return false;
232
233   Mod = &M;
234   Ctx = &M.getContext();
235   ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
236   ShadowPtrTy = PointerType::getUnqual(ShadowTy);
237   IntptrTy = DL->getIntPtrType(*Ctx);
238   ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
239   ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
240   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
241
242   Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
243   DFSanUnionFnTy =
244       FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
245   Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
246   DFSanUnionLoadFnTy =
247       FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
248
249   if (GetArgTLSPtr) {
250     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
251     ArgTLS = 0;
252     GetArgTLS = ConstantExpr::getIntToPtr(
253         ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
254         PointerType::getUnqual(
255             FunctionType::get(PointerType::getUnqual(ArgTLSTy), (Type *)0)));
256   }
257   if (GetRetvalTLSPtr) {
258     RetvalTLS = 0;
259     GetRetvalTLS = ConstantExpr::getIntToPtr(
260         ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
261         PointerType::getUnqual(
262             FunctionType::get(PointerType::getUnqual(ShadowTy), (Type *)0)));
263   }
264
265   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
266   return true;
267 }
268
269 DataFlowSanitizer::InstrumentedABI
270 DataFlowSanitizer::getInstrumentedABI(Function *F) {
271   if (Greylist.isIn(*F))
272     return IA_MemOnly;
273   else
274     return getDefaultInstrumentedABI();
275 }
276
277 DataFlowSanitizer::InstrumentedABI
278 DataFlowSanitizer::getDefaultInstrumentedABI() {
279   return ClArgsABI ? IA_Args : IA_TLS;
280 }
281
282 bool DataFlowSanitizer::runOnModule(Module &M) {
283   if (!DL)
284     return false;
285
286   if (!GetArgTLSPtr) {
287     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
288     ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
289     if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
290       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
291   }
292   if (!GetRetvalTLSPtr) {
293     RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
294     if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
295       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
296   }
297
298   DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
299   if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
300     F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
301     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
302     F->addAttribute(1, Attribute::ZExt);
303     F->addAttribute(2, Attribute::ZExt);
304   }
305   DFSanUnionLoadFn =
306       Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
307   if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
308     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
309   }
310
311   std::vector<Function *> FnsToInstrument;
312   for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
313     if (!i->isIntrinsic() && i != DFSanUnionFn && i != DFSanUnionLoadFn)
314       FnsToInstrument.push_back(&*i);
315   }
316
317   // First, change the ABI of every function in the module.  Greylisted
318   // functions keep their original ABI and get a wrapper function.
319   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
320                                          e = FnsToInstrument.end();
321        i != e; ++i) {
322     Function &F = **i;
323
324     FunctionType *FT = F.getFunctionType();
325     FunctionType *NewFT = getInstrumentedFunctionType(FT);
326     // If the function types are the same (i.e. void()), we don't need to do
327     // anything here.
328     if (FT != NewFT) {
329       switch (getInstrumentedABI(&F)) {
330       case IA_Args: {
331         Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
332         NewF->setCallingConv(F.getCallingConv());
333         NewF->setAttributes(F.getAttributes().removeAttributes(
334             *Ctx, AttributeSet::ReturnIndex,
335             AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
336                                              AttributeSet::ReturnIndex)));
337         for (Function::arg_iterator FArg = F.arg_begin(),
338                                     NewFArg = NewF->arg_begin(),
339                                     FArgEnd = F.arg_end();
340              FArg != FArgEnd; ++FArg, ++NewFArg) {
341           FArg->replaceAllUsesWith(NewFArg);
342         }
343         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
344
345         for (Function::use_iterator ui = F.use_begin(), ue = F.use_end();
346              ui != ue;) {
347           BlockAddress *BA = dyn_cast<BlockAddress>(ui.getUse().getUser());
348           ++ui;
349           if (BA) {
350             BA->replaceAllUsesWith(
351                 BlockAddress::get(NewF, BA->getBasicBlock()));
352             delete BA;
353           }
354         }
355         F.replaceAllUsesWith(
356             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
357         NewF->takeName(&F);
358         F.eraseFromParent();
359         *i = NewF;
360         break;
361       }
362       case IA_MemOnly: {
363         assert(!FT->isVarArg() && "varargs not handled here yet");
364         assert(getDefaultInstrumentedABI() == IA_Args);
365         Function *NewF =
366             Function::Create(NewFT, GlobalValue::LinkOnceODRLinkage,
367                              std::string("dfsw$") + F.getName(), &M);
368         NewF->setCallingConv(F.getCallingConv());
369         NewF->setAttributes(F.getAttributes());
370
371         BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
372         std::vector<Value *> Args;
373         unsigned n = FT->getNumParams();
374         for (Function::arg_iterator i = NewF->arg_begin(); n != 0; ++i, --n)
375           Args.push_back(&*i);
376         CallInst *CI = CallInst::Create(&F, Args, "", BB);
377         if (FT->getReturnType()->isVoidTy())
378           ReturnInst::Create(*Ctx, BB);
379         else {
380           Value *InsVal = InsertValueInst::Create(
381               UndefValue::get(NewFT->getReturnType()), CI, 0, "", BB);
382           Value *InsShadow =
383               InsertValueInst::Create(InsVal, ZeroShadow, 1, "", BB);
384           ReturnInst::Create(*Ctx, InsShadow, BB);
385         }
386
387         Value *WrappedFnCst =
388             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
389         F.replaceAllUsesWith(WrappedFnCst);
390         UnwrappedFnMap[WrappedFnCst] = &F;
391         break;
392       }
393       default:
394         break;
395       }
396     }
397   }
398
399   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
400                                          e = FnsToInstrument.end();
401        i != e; ++i) {
402     if ((*i)->isDeclaration())
403       continue;
404
405     DFSanFunction DFSF(*this, *i);
406
407     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
408     // Build a copy of the list before iterating over it.
409     llvm::SmallVector<BasicBlock *, 4> BBList;
410     std::copy(df_begin(&(*i)->getEntryBlock()), df_end(&(*i)->getEntryBlock()),
411               std::back_inserter(BBList));
412
413     for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
414                                                       e = BBList.end();
415          i != e; ++i) {
416       Instruction *Inst = &(*i)->front();
417       while (1) {
418         // DFSanVisitor may split the current basic block, changing the current
419         // instruction's next pointer and moving the next instruction to the
420         // tail block from which we should continue.
421         Instruction *Next = Inst->getNextNode();
422         if (!DFSF.SkipInsts.count(Inst))
423           DFSanVisitor(DFSF).visit(Inst);
424         if (isa<TerminatorInst>(Inst))
425           break;
426         Inst = Next;
427       }
428     }
429
430     for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
431              i = DFSF.PHIFixups.begin(),
432              e = DFSF.PHIFixups.end();
433          i != e; ++i) {
434       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
435            ++val) {
436         i->second->setIncomingValue(
437             val, DFSF.getShadow(i->first->getIncomingValue(val)));
438       }
439     }
440   }
441
442   return false;
443 }
444
445 Value *DFSanFunction::getArgTLSPtr() {
446   if (ArgTLSPtr)
447     return ArgTLSPtr;
448   if (DFS.ArgTLS)
449     return ArgTLSPtr = DFS.ArgTLS;
450
451   IRBuilder<> IRB(F->getEntryBlock().begin());
452   return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
453 }
454
455 Value *DFSanFunction::getRetvalTLS() {
456   if (RetvalTLSPtr)
457     return RetvalTLSPtr;
458   if (DFS.RetvalTLS)
459     return RetvalTLSPtr = DFS.RetvalTLS;
460
461   IRBuilder<> IRB(F->getEntryBlock().begin());
462   return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
463 }
464
465 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
466   IRBuilder<> IRB(Pos);
467   return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
468 }
469
470 Value *DFSanFunction::getShadow(Value *V) {
471   if (!isa<Argument>(V) && !isa<Instruction>(V))
472     return DFS.ZeroShadow;
473   Value *&Shadow = ValShadowMap[V];
474   if (!Shadow) {
475     if (Argument *A = dyn_cast<Argument>(V)) {
476       switch (IA) {
477       case DataFlowSanitizer::IA_TLS: {
478         Value *ArgTLSPtr = getArgTLSPtr();
479         Instruction *ArgTLSPos =
480             DFS.ArgTLS ? &*F->getEntryBlock().begin()
481                        : cast<Instruction>(ArgTLSPtr)->getNextNode();
482         IRBuilder<> IRB(ArgTLSPos);
483         Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
484         break;
485       }
486       case DataFlowSanitizer::IA_Args: {
487         unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
488         Function::arg_iterator i = F->arg_begin();
489         while (ArgIdx--)
490           ++i;
491         Shadow = i;
492         break;
493       }
494       default:
495         Shadow = DFS.ZeroShadow;
496         break;
497       }
498     } else {
499       Shadow = DFS.ZeroShadow;
500     }
501   }
502   return Shadow;
503 }
504
505 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
506   assert(!ValShadowMap.count(I));
507   assert(Shadow->getType() == DFS.ShadowTy);
508   ValShadowMap[I] = Shadow;
509 }
510
511 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
512   assert(Addr != RetvalTLS && "Reinstrumenting?");
513   IRBuilder<> IRB(Pos);
514   return IRB.CreateIntToPtr(
515       IRB.CreateMul(
516           IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
517           ShadowPtrMul),
518       ShadowPtrTy);
519 }
520
521 // Generates IR to compute the union of the two given shadows, inserting it
522 // before Pos.  Returns the computed union Value.
523 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
524                                          Instruction *Pos) {
525   if (V1 == ZeroShadow)
526     return V2;
527   if (V2 == ZeroShadow)
528     return V1;
529   if (V1 == V2)
530     return V1;
531   IRBuilder<> IRB(Pos);
532   BasicBlock *Head = Pos->getParent();
533   Value *Ne = IRB.CreateICmpNE(V1, V2);
534   Instruction *NeInst = dyn_cast<Instruction>(Ne);
535   if (NeInst) {
536     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
537         NeInst, /*Unreachable=*/ false, ColdCallWeights));
538     IRBuilder<> ThenIRB(BI);
539     CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
540     Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
541     Call->addAttribute(1, Attribute::ZExt);
542     Call->addAttribute(2, Attribute::ZExt);
543
544     BasicBlock *Tail = BI->getSuccessor(0);
545     PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
546     Phi->addIncoming(Call, Call->getParent());
547     Phi->addIncoming(ZeroShadow, Head);
548     Pos = Phi;
549     return Phi;
550   } else {
551     assert(0 && "todo");
552     return 0;
553   }
554 }
555
556 // A convenience function which folds the shadows of each of the operands
557 // of the provided instruction Inst, inserting the IR before Inst.  Returns
558 // the computed union Value.
559 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
560   if (Inst->getNumOperands() == 0)
561     return DFS.ZeroShadow;
562
563   Value *Shadow = getShadow(Inst->getOperand(0));
564   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
565     Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
566   }
567   return Shadow;
568 }
569
570 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
571   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
572   DFSF.setShadow(&I, CombinedShadow);
573 }
574
575 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
576 // Addr has alignment Align, and take the union of each of those shadows.
577 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
578                                  Instruction *Pos) {
579   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
580     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
581         AllocaShadowMap.find(AI);
582     if (i != AllocaShadowMap.end()) {
583       IRBuilder<> IRB(Pos);
584       return IRB.CreateLoad(i->second);
585     }
586   }
587
588   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
589   SmallVector<Value *, 2> Objs;
590   GetUnderlyingObjects(Addr, Objs, DFS.DL);
591   bool AllConstants = true;
592   for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
593        i != e; ++i) {
594     if (isa<Function>(*i) || isa<BlockAddress>(*i))
595       continue;
596     if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
597       continue;
598
599     AllConstants = false;
600     break;
601   }
602   if (AllConstants)
603     return DFS.ZeroShadow;
604
605   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
606   switch (Size) {
607   case 0:
608     return DFS.ZeroShadow;
609   case 1: {
610     LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
611     LI->setAlignment(ShadowAlign);
612     return LI;
613   }
614   case 2: {
615     IRBuilder<> IRB(Pos);
616     Value *ShadowAddr1 =
617         IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
618     return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
619                               IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
620                               Pos);
621   }
622   }
623   if (Size % (64 / DFS.ShadowWidth) == 0) {
624     // Fast path for the common case where each byte has identical shadow: load
625     // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
626     // shadow is non-equal.
627     BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
628     IRBuilder<> FallbackIRB(FallbackBB);
629     CallInst *FallbackCall = FallbackIRB.CreateCall2(
630         DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
631     FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
632
633     // Compare each of the shadows stored in the loaded 64 bits to each other,
634     // by computing (WideShadow rotl ShadowWidth) == WideShadow.
635     IRBuilder<> IRB(Pos);
636     Value *WideAddr =
637         IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
638     Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
639     Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
640     Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
641     Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
642     Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
643     Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
644
645     BasicBlock *Head = Pos->getParent();
646     BasicBlock *Tail = Head->splitBasicBlock(Pos);
647     // In the following code LastBr will refer to the previous basic block's
648     // conditional branch instruction, whose true successor is fixed up to point
649     // to the next block during the loop below or to the tail after the final
650     // iteration.
651     BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
652     ReplaceInstWithInst(Head->getTerminator(), LastBr);
653
654     for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
655          Ofs += 64 / DFS.ShadowWidth) {
656       BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
657       IRBuilder<> NextIRB(NextBB);
658       WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
659       Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
660       ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
661       LastBr->setSuccessor(0, NextBB);
662       LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
663     }
664
665     LastBr->setSuccessor(0, Tail);
666     FallbackIRB.CreateBr(Tail);
667     PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
668     Shadow->addIncoming(FallbackCall, FallbackBB);
669     Shadow->addIncoming(TruncShadow, LastBr->getParent());
670     return Shadow;
671   }
672
673   IRBuilder<> IRB(Pos);
674   CallInst *FallbackCall = IRB.CreateCall2(
675       DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
676   FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
677   return FallbackCall;
678 }
679
680 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
681   uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
682   uint64_t Align;
683   if (ClPreserveAlignment) {
684     Align = LI.getAlignment();
685     if (Align == 0)
686       Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
687   } else {
688     Align = 1;
689   }
690   IRBuilder<> IRB(&LI);
691   Value *LoadedShadow =
692       DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
693   Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
694   DFSF.setShadow(&LI, DFSF.DFS.combineShadows(LoadedShadow, PtrShadow, &LI));
695 }
696
697 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
698                                 Value *Shadow, Instruction *Pos) {
699   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
700     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
701         AllocaShadowMap.find(AI);
702     if (i != AllocaShadowMap.end()) {
703       IRBuilder<> IRB(Pos);
704       IRB.CreateStore(Shadow, i->second);
705       return;
706     }
707   }
708
709   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
710   IRBuilder<> IRB(Pos);
711   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
712   if (Shadow == DFS.ZeroShadow) {
713     IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
714     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
715     Value *ExtShadowAddr =
716         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
717     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
718     return;
719   }
720
721   const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
722   uint64_t Offset = 0;
723   if (Size >= ShadowVecSize) {
724     VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
725     Value *ShadowVec = UndefValue::get(ShadowVecTy);
726     for (unsigned i = 0; i != ShadowVecSize; ++i) {
727       ShadowVec = IRB.CreateInsertElement(
728           ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
729     }
730     Value *ShadowVecAddr =
731         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
732     do {
733       Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
734       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
735       Size -= ShadowVecSize;
736       ++Offset;
737     } while (Size >= ShadowVecSize);
738     Offset *= ShadowVecSize;
739   }
740   while (Size > 0) {
741     Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
742     IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
743     --Size;
744     ++Offset;
745   }
746 }
747
748 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
749   uint64_t Size =
750       DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
751   uint64_t Align;
752   if (ClPreserveAlignment) {
753     Align = SI.getAlignment();
754     if (Align == 0)
755       Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
756   } else {
757     Align = 1;
758   }
759   DFSF.storeShadow(SI.getPointerOperand(), Size, Align,
760                    DFSF.getShadow(SI.getValueOperand()), &SI);
761 }
762
763 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
764   visitOperandShadowInst(BO);
765 }
766
767 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
768
769 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
770
771 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
772   visitOperandShadowInst(GEPI);
773 }
774
775 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
776   visitOperandShadowInst(I);
777 }
778
779 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
780   visitOperandShadowInst(I);
781 }
782
783 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
784   visitOperandShadowInst(I);
785 }
786
787 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
788   visitOperandShadowInst(I);
789 }
790
791 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
792   visitOperandShadowInst(I);
793 }
794
795 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
796   bool AllLoadsStores = true;
797   for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e;
798        ++i) {
799     if (isa<LoadInst>(*i))
800       continue;
801
802     if (StoreInst *SI = dyn_cast<StoreInst>(*i)) {
803       if (SI->getPointerOperand() == &I)
804         continue;
805     }
806
807     AllLoadsStores = false;
808     break;
809   }
810   if (AllLoadsStores) {
811     IRBuilder<> IRB(&I);
812     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
813   }
814   DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
815 }
816
817 void DFSanVisitor::visitSelectInst(SelectInst &I) {
818   Value *CondShadow = DFSF.getShadow(I.getCondition());
819   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
820   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
821
822   if (isa<VectorType>(I.getCondition()->getType())) {
823     DFSF.setShadow(
824         &I, DFSF.DFS.combineShadows(
825                 CondShadow,
826                 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
827   } else {
828     Value *ShadowSel;
829     if (TrueShadow == FalseShadow) {
830       ShadowSel = TrueShadow;
831     } else {
832       ShadowSel =
833           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
834     }
835     DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
836   }
837 }
838
839 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
840   IRBuilder<> IRB(&I);
841   Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
842   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
843   Value *LenShadow = IRB.CreateMul(
844       I.getLength(),
845       ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
846   Value *AlignShadow;
847   if (ClPreserveAlignment) {
848     AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
849                                 ConstantInt::get(I.getAlignmentCst()->getType(),
850                                                  DFSF.DFS.ShadowWidth / 8));
851   } else {
852     AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
853                                    DFSF.DFS.ShadowWidth / 8);
854   }
855   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
856   DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
857   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
858   IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
859                   AlignShadow, I.getVolatileCst());
860 }
861
862 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
863   if (RI.getReturnValue()) {
864     switch (DFSF.IA) {
865     case DataFlowSanitizer::IA_TLS: {
866       Value *S = DFSF.getShadow(RI.getReturnValue());
867       IRBuilder<> IRB(&RI);
868       IRB.CreateStore(S, DFSF.getRetvalTLS());
869       break;
870     }
871     case DataFlowSanitizer::IA_Args: {
872       IRBuilder<> IRB(&RI);
873       Type *RT = DFSF.F->getFunctionType()->getReturnType();
874       Value *InsVal =
875           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
876       Value *InsShadow =
877           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
878       RI.setOperand(0, InsShadow);
879       break;
880     }
881     default:
882       break;
883     }
884   }
885 }
886
887 void DFSanVisitor::visitCallSite(CallSite CS) {
888   Function *F = CS.getCalledFunction();
889   if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
890     visitOperandShadowInst(*CS.getInstruction());
891     return;
892   }
893
894   DenseMap<Value *, Function *>::iterator i =
895       DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
896   if (i != DFSF.DFS.UnwrappedFnMap.end()) {
897     CS.setCalledFunction(i->second);
898     DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
899     return;
900   }
901
902   IRBuilder<> IRB(CS.getInstruction());
903
904   FunctionType *FT = cast<FunctionType>(
905       CS.getCalledValue()->getType()->getPointerElementType());
906   if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
907     for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
908       IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
909                       DFSF.getArgTLS(i, CS.getInstruction()));
910     }
911   }
912
913   Instruction *Next = 0;
914   if (!CS.getType()->isVoidTy()) {
915     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
916       if (II->getNormalDest()->getSinglePredecessor()) {
917         Next = II->getNormalDest()->begin();
918       } else {
919         BasicBlock *NewBB =
920             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
921         Next = NewBB->begin();
922       }
923     } else {
924       Next = CS->getNextNode();
925     }
926
927     if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
928       IRBuilder<> NextIRB(Next);
929       LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
930       DFSF.SkipInsts.insert(LI);
931       DFSF.setShadow(CS.getInstruction(), LI);
932     }
933   }
934
935   // Do all instrumentation for IA_Args down here to defer tampering with the
936   // CFG in a way that SplitEdge may be able to detect.
937   if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_Args) {
938     FunctionType *NewFT = DFSF.DFS.getInstrumentedFunctionType(FT);
939     Value *Func =
940         IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
941     std::vector<Value *> Args;
942
943     CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
944     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
945       Args.push_back(*i);
946
947     i = CS.arg_begin();
948     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
949       Args.push_back(DFSF.getShadow(*i));
950
951     if (FT->isVarArg()) {
952       unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
953       ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
954       AllocaInst *VarArgShadow =
955           new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
956       Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
957       for (unsigned n = 0; i != e; ++i, ++n) {
958         IRB.CreateStore(DFSF.getShadow(*i),
959                         IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
960         Args.push_back(*i);
961       }
962     }
963
964     CallSite NewCS;
965     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
966       NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
967                                Args);
968     } else {
969       NewCS = IRB.CreateCall(Func, Args);
970     }
971     NewCS.setCallingConv(CS.getCallingConv());
972     NewCS.setAttributes(CS.getAttributes().removeAttributes(
973         *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
974         AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
975                                          AttributeSet::ReturnIndex)));
976
977     if (Next) {
978       ExtractValueInst *ExVal =
979           ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
980       DFSF.SkipInsts.insert(ExVal);
981       ExtractValueInst *ExShadow =
982           ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
983       DFSF.SkipInsts.insert(ExShadow);
984       DFSF.setShadow(ExVal, ExShadow);
985
986       CS.getInstruction()->replaceAllUsesWith(ExVal);
987     }
988
989     CS.getInstruction()->eraseFromParent();
990   }
991 }
992
993 void DFSanVisitor::visitPHINode(PHINode &PN) {
994   PHINode *ShadowPN =
995       PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
996
997   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
998   Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
999   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1000        ++i) {
1001     ShadowPN->addIncoming(UndefShadow, *i);
1002   }
1003
1004   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1005   DFSF.setShadow(&PN, ShadowPN);
1006 }