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