IR: Split Metadata from Value
[oota-llvm.git] / lib / Transforms / Instrumentation / AddressSanitizer.cpp
1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
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 //
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 // Details of the algorithm:
12 //  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Transforms/Instrumentation.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/InstVisitor.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/MC/MCSectionMachO.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/DataTypes.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/Endian.h"
45 #include "llvm/Support/SwapByteOrder.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Cloning.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include "llvm/Transforms/Utils/ModuleUtils.h"
52 #include <algorithm>
53 #include <string>
54 #include <system_error>
55
56 using namespace llvm;
57
58 #define DEBUG_TYPE "asan"
59
60 static const uint64_t kDefaultShadowScale = 3;
61 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
62 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
63 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
64 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000;  // < 2G.
65 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
66 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
67 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 36;
68 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
69 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
70
71 static const size_t kMinStackMallocSize = 1 << 6;  // 64B
72 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
73 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
74 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
75
76 static const char *const kAsanModuleCtorName = "asan.module_ctor";
77 static const char *const kAsanModuleDtorName = "asan.module_dtor";
78 static const uint64_t    kAsanCtorAndDtorPriority = 1;
79 static const char *const kAsanReportErrorTemplate = "__asan_report_";
80 static const char *const kAsanReportLoadN = "__asan_report_load_n";
81 static const char *const kAsanReportStoreN = "__asan_report_store_n";
82 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
83 static const char *const kAsanUnregisterGlobalsName =
84     "__asan_unregister_globals";
85 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
86 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
87 static const char *const kAsanInitName = "__asan_init_v4";
88 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
89 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
90 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
91 static const int         kMaxAsanStackMallocSizeClass = 10;
92 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
93 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
94 static const char *const kAsanGenPrefix = "__asan_gen_";
95 static const char *const kSanCovGenPrefix = "__sancov_gen_";
96 static const char *const kAsanPoisonStackMemoryName =
97     "__asan_poison_stack_memory";
98 static const char *const kAsanUnpoisonStackMemoryName =
99     "__asan_unpoison_stack_memory";
100
101 static const char *const kAsanOptionDetectUAR =
102     "__asan_option_detect_stack_use_after_return";
103
104 #ifndef NDEBUG
105 static const int kAsanStackAfterReturnMagic = 0xf5;
106 #endif
107
108 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
109 static const size_t kNumberOfAccessSizes = 5;
110
111 static const unsigned kAllocaRzSize = 32;
112 static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU;
113 static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU;
114 static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U;
115 static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU;
116
117 // Command-line flags.
118
119 // This flag may need to be replaced with -f[no-]asan-reads.
120 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
121        cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
122 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
123        cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
124 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
125        cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
126        cl::Hidden, cl::init(true));
127 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
128        cl::desc("use instrumentation with slow path for all accesses"),
129        cl::Hidden, cl::init(false));
130 // This flag limits the number of instructions to be instrumented
131 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
132 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
133 // set it to 10000.
134 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
135        cl::init(10000),
136        cl::desc("maximal number of instructions to instrument in any given BB"),
137        cl::Hidden);
138 // This flag may need to be replaced with -f[no]asan-stack.
139 static cl::opt<bool> ClStack("asan-stack",
140        cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
141 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
142        cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
143 // This flag may need to be replaced with -f[no]asan-globals.
144 static cl::opt<bool> ClGlobals("asan-globals",
145        cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
146 static cl::opt<bool> ClInitializers("asan-initialization-order",
147        cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
148 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
149        cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
150        cl::Hidden, cl::init(false));
151 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
152        cl::desc("Realign stack to the value of this flag (power of two)"),
153        cl::Hidden, cl::init(32));
154 static cl::opt<int> ClInstrumentationWithCallsThreshold(
155     "asan-instrumentation-with-call-threshold",
156        cl::desc("If the function being instrumented contains more than "
157                 "this number of memory accesses, use callbacks instead of "
158                 "inline checks (-1 means never use callbacks)."),
159        cl::Hidden, cl::init(7000));
160 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
161        "asan-memory-access-callback-prefix",
162        cl::desc("Prefix for memory access callbacks"), cl::Hidden,
163        cl::init("__asan_"));
164 static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
165        cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false));
166
167 // These flags allow to change the shadow mapping.
168 // The shadow mapping looks like
169 //    Shadow = (Mem >> scale) + (1 << offset_log)
170 static cl::opt<int> ClMappingScale("asan-mapping-scale",
171        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
172
173 // Optimization flags. Not user visible, used mostly for testing
174 // and benchmarking the tool.
175 static cl::opt<bool> ClOpt("asan-opt",
176        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
177 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
178        cl::desc("Instrument the same temp just once"), cl::Hidden,
179        cl::init(true));
180 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
181        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
182
183 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
184        cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
185        cl::Hidden, cl::init(false));
186
187 // Debug flags.
188 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
189                             cl::init(0));
190 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
191                                  cl::Hidden, cl::init(0));
192 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
193                                         cl::Hidden, cl::desc("Debug func"));
194 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
195                                cl::Hidden, cl::init(-1));
196 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
197                                cl::Hidden, cl::init(-1));
198
199 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
200 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
201 STATISTIC(NumInstrumentedDynamicAllocas,
202           "Number of instrumented dynamic allocas");
203 STATISTIC(NumOptimizedAccessesToGlobalArray,
204           "Number of optimized accesses to global arrays");
205 STATISTIC(NumOptimizedAccessesToGlobalVar,
206           "Number of optimized accesses to global vars");
207
208 namespace {
209 /// Frontend-provided metadata for source location.
210 struct LocationMetadata {
211   StringRef Filename;
212   int LineNo;
213   int ColumnNo;
214
215   LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
216
217   bool empty() const { return Filename.empty(); }
218
219   void parse(MDNode *MDN) {
220     assert(MDN->getNumOperands() == 3);
221     MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
222     Filename = MDFilename->getString();
223     LineNo =
224         mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
225     ColumnNo =
226         mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
227   }
228 };
229
230 /// Frontend-provided metadata for global variables.
231 class GlobalsMetadata {
232  public:
233   struct Entry {
234     Entry()
235         : SourceLoc(), Name(), IsDynInit(false),
236           IsBlacklisted(false) {}
237     LocationMetadata SourceLoc;
238     StringRef Name;
239     bool IsDynInit;
240     bool IsBlacklisted;
241   };
242
243   GlobalsMetadata() : inited_(false) {}
244
245   void init(Module& M) {
246     assert(!inited_);
247     inited_ = true;
248     NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
249     if (!Globals)
250       return;
251     for (auto MDN : Globals->operands()) {
252       // Metadata node contains the global and the fields of "Entry".
253       assert(MDN->getNumOperands() == 5);
254       auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
255       // The optimizer may optimize away a global entirely.
256       if (!GV)
257         continue;
258       // We can already have an entry for GV if it was merged with another
259       // global.
260       Entry &E = Entries[GV];
261       if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
262         E.SourceLoc.parse(Loc);
263       if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
264         E.Name = Name->getString();
265       ConstantInt *IsDynInit =
266           mdconst::extract<ConstantInt>(MDN->getOperand(3));
267       E.IsDynInit |= IsDynInit->isOne();
268       ConstantInt *IsBlacklisted =
269           mdconst::extract<ConstantInt>(MDN->getOperand(4));
270       E.IsBlacklisted |= IsBlacklisted->isOne();
271     }
272   }
273
274   /// Returns metadata entry for a given global.
275   Entry get(GlobalVariable *G) const {
276     auto Pos = Entries.find(G);
277     return (Pos != Entries.end()) ? Pos->second : Entry();
278   }
279
280  private:
281   bool inited_;
282   DenseMap<GlobalVariable*, Entry> Entries;
283 };
284
285 /// This struct defines the shadow mapping using the rule:
286 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
287 struct ShadowMapping {
288   int Scale;
289   uint64_t Offset;
290   bool OrShadowOffset;
291 };
292
293 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize) {
294   bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
295   bool IsIOS = TargetTriple.isiOS();
296   bool IsFreeBSD = TargetTriple.isOSFreeBSD();
297   bool IsLinux = TargetTriple.isOSLinux();
298   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
299                  TargetTriple.getArch() == llvm::Triple::ppc64le;
300   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
301   bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
302                   TargetTriple.getArch() == llvm::Triple::mipsel;
303   bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
304                   TargetTriple.getArch() == llvm::Triple::mips64el;
305
306   ShadowMapping Mapping;
307
308   if (LongSize == 32) {
309     if (IsAndroid)
310       Mapping.Offset = 0;
311     else if (IsMIPS32)
312       Mapping.Offset = kMIPS32_ShadowOffset32;
313     else if (IsFreeBSD)
314       Mapping.Offset = kFreeBSD_ShadowOffset32;
315     else if (IsIOS)
316       Mapping.Offset = kIOSShadowOffset32;
317     else
318       Mapping.Offset = kDefaultShadowOffset32;
319   } else {  // LongSize == 64
320     if (IsPPC64)
321       Mapping.Offset = kPPC64_ShadowOffset64;
322     else if (IsFreeBSD)
323       Mapping.Offset = kFreeBSD_ShadowOffset64;
324     else if (IsLinux && IsX86_64)
325       Mapping.Offset = kSmallX86_64ShadowOffset;
326     else if (IsMIPS64)
327       Mapping.Offset = kMIPS64_ShadowOffset64;
328     else
329       Mapping.Offset = kDefaultShadowOffset64;
330   }
331
332   Mapping.Scale = kDefaultShadowScale;
333   if (ClMappingScale) {
334     Mapping.Scale = ClMappingScale;
335   }
336
337   // OR-ing shadow offset if more efficient (at least on x86) if the offset
338   // is a power of two, but on ppc64 we have to use add since the shadow
339   // offset is not necessary 1/8-th of the address space.
340   Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
341
342   return Mapping;
343 }
344
345 static size_t RedzoneSizeForScale(int MappingScale) {
346   // Redzone used for stack and globals is at least 32 bytes.
347   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
348   return std::max(32U, 1U << MappingScale);
349 }
350
351 /// AddressSanitizer: instrument the code in module to find memory bugs.
352 struct AddressSanitizer : public FunctionPass {
353   AddressSanitizer() : FunctionPass(ID) {
354     initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
355   }
356   const char *getPassName() const override {
357     return "AddressSanitizerFunctionPass";
358   }
359   void getAnalysisUsage(AnalysisUsage &AU) const override {
360     AU.addRequired<DominatorTreeWrapperPass>();
361   }
362   void instrumentMop(Instruction *I, bool UseCalls);
363   void instrumentPointerComparisonOrSubtraction(Instruction *I);
364   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
365                          Value *Addr, uint32_t TypeSize, bool IsWrite,
366                          Value *SizeArgument, bool UseCalls);
367   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
368                            Value *ShadowValue, uint32_t TypeSize);
369   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
370                                  bool IsWrite, size_t AccessSizeIndex,
371                                  Value *SizeArgument);
372   void instrumentMemIntrinsic(MemIntrinsic *MI);
373   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
374   bool runOnFunction(Function &F) override;
375   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
376   bool doInitialization(Module &M) override;
377   static char ID;  // Pass identification, replacement for typeid
378
379   DominatorTree &getDominatorTree() const { return *DT; }
380
381  private:
382   void initializeCallbacks(Module &M);
383
384   bool LooksLikeCodeInBug11395(Instruction *I);
385   bool GlobalIsLinkerInitialized(GlobalVariable *G);
386
387   LLVMContext *C;
388   const DataLayout *DL;
389   Triple TargetTriple;
390   int LongSize;
391   Type *IntptrTy;
392   ShadowMapping Mapping;
393   DominatorTree *DT;
394   Function *AsanCtorFunction;
395   Function *AsanInitFunction;
396   Function *AsanHandleNoReturnFunc;
397   Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
398   // This array is indexed by AccessIsWrite and log2(AccessSize).
399   Function *AsanErrorCallback[2][kNumberOfAccessSizes];
400   Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
401   // This array is indexed by AccessIsWrite.
402   Function *AsanErrorCallbackSized[2],
403            *AsanMemoryAccessCallbackSized[2];
404   Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
405   InlineAsm *EmptyAsm;
406   GlobalsMetadata GlobalsMD;
407
408   friend struct FunctionStackPoisoner;
409 };
410
411 class AddressSanitizerModule : public ModulePass {
412  public:
413   AddressSanitizerModule() : ModulePass(ID) {}
414   bool runOnModule(Module &M) override;
415   static char ID;  // Pass identification, replacement for typeid
416   const char *getPassName() const override {
417     return "AddressSanitizerModule";
418   }
419
420  private:
421   void initializeCallbacks(Module &M);
422
423   bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
424   bool ShouldInstrumentGlobal(GlobalVariable *G);
425   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
426   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
427   size_t MinRedzoneSizeForGlobal() const {
428     return RedzoneSizeForScale(Mapping.Scale);
429   }
430
431   GlobalsMetadata GlobalsMD;
432   Type *IntptrTy;
433   LLVMContext *C;
434   const DataLayout *DL;
435   Triple TargetTriple;
436   ShadowMapping Mapping;
437   Function *AsanPoisonGlobals;
438   Function *AsanUnpoisonGlobals;
439   Function *AsanRegisterGlobals;
440   Function *AsanUnregisterGlobals;
441 };
442
443 // Stack poisoning does not play well with exception handling.
444 // When an exception is thrown, we essentially bypass the code
445 // that unpoisones the stack. This is why the run-time library has
446 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
447 // stack in the interceptor. This however does not work inside the
448 // actual function which catches the exception. Most likely because the
449 // compiler hoists the load of the shadow value somewhere too high.
450 // This causes asan to report a non-existing bug on 453.povray.
451 // It sounds like an LLVM bug.
452 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
453   Function &F;
454   AddressSanitizer &ASan;
455   DIBuilder DIB;
456   LLVMContext *C;
457   Type *IntptrTy;
458   Type *IntptrPtrTy;
459   ShadowMapping Mapping;
460
461   SmallVector<AllocaInst*, 16> AllocaVec;
462   SmallVector<Instruction*, 8> RetVec;
463   unsigned StackAlignment;
464
465   Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
466            *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
467   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
468
469   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
470   struct AllocaPoisonCall {
471     IntrinsicInst *InsBefore;
472     AllocaInst *AI;
473     uint64_t Size;
474     bool DoPoison;
475   };
476   SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
477
478   // Stores left and right redzone shadow addresses for dynamic alloca
479   // and pointer to alloca instruction itself.
480   // LeftRzAddr is a shadow address for alloca left redzone.
481   // RightRzAddr is a shadow address for alloca right redzone.
482   struct DynamicAllocaCall {
483     AllocaInst *AI;
484     Value *LeftRzAddr;
485     Value *RightRzAddr;
486     bool Poison;
487     explicit DynamicAllocaCall(AllocaInst *AI,
488                       Value *LeftRzAddr = nullptr,
489                       Value *RightRzAddr = nullptr)
490       : AI(AI), LeftRzAddr(LeftRzAddr), RightRzAddr(RightRzAddr), Poison(true)
491     {}
492   };
493   SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
494
495   // Maps Value to an AllocaInst from which the Value is originated.
496   typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
497   AllocaForValueMapTy AllocaForValue;
498
499   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
500       : F(F), ASan(ASan), DIB(*F.getParent(), /*AllowUnresolved*/ false),
501         C(ASan.C), IntptrTy(ASan.IntptrTy),
502         IntptrPtrTy(PointerType::get(IntptrTy, 0)), Mapping(ASan.Mapping),
503         StackAlignment(1 << Mapping.Scale) {}
504
505   bool runOnFunction() {
506     if (!ClStack) return false;
507     // Collect alloca, ret, lifetime instructions etc.
508     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
509       visit(*BB);
510
511     if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
512
513     initializeCallbacks(*F.getParent());
514
515     poisonStack();
516
517     if (ClDebugStack) {
518       DEBUG(dbgs() << F);
519     }
520     return true;
521   }
522
523   // Finds all Alloca instructions and puts
524   // poisoned red zones around all of them.
525   // Then unpoison everything back before the function returns.
526   void poisonStack();
527
528   // ----------------------- Visitors.
529   /// \brief Collect all Ret instructions.
530   void visitReturnInst(ReturnInst &RI) {
531     RetVec.push_back(&RI);
532   }
533
534   // Unpoison dynamic allocas redzones.
535   void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
536     if (!AllocaCall.Poison)
537       return;
538     for (auto Ret : RetVec) {
539       IRBuilder<> IRBRet(Ret);
540       PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
541       Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
542       Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
543                                               ConstantInt::get(IntptrTy, 4));
544       IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr,
545                                                      Int32PtrTy));
546       IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(PartialRzAddr,
547                                                      Int32PtrTy));
548       IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr,
549                                                      Int32PtrTy));
550     }
551   }
552
553   // Right shift for BigEndian and left shift for LittleEndian.
554   Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
555     return ASan.DL->isLittleEndian() ? IRB.CreateShl(Val, Shift)
556                                      : IRB.CreateLShr(Val, Shift);
557   }
558
559   // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
560   // size of requested memory until runtime, we should compute it dynamically.
561   // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
562   // otherwise it would contain the value that we will use to poison the
563   // partial redzone for alloca call.
564   Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
565
566   // Deploy and poison redzones around dynamic alloca call. To do this, we
567   // should replace this call with another one with changed parameters and
568   // replace all its uses with new address, so
569   //   addr = alloca type, old_size, align
570   // is replaced by
571   //   new_size = (old_size + additional_size) * sizeof(type)
572   //   tmp = alloca i8, new_size, max(align, 32)
573   //   addr = tmp + 32 (first 32 bytes are for the left redzone).
574   // Additional_size is added to make new memory allocation contain not only
575   // requested memory, but also left, partial and right redzones.
576   // After that, we should poison redzones:
577   // (1) Left redzone with kAsanAllocaLeftMagic.
578   // (2) Partial redzone with the value, computed in runtime by
579   //     computePartialRzMagic function.
580   // (3) Right redzone with kAsanAllocaRightMagic.
581   void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
582
583   /// \brief Collect Alloca instructions we want (and can) handle.
584   void visitAllocaInst(AllocaInst &AI) {
585     if (!isInterestingAlloca(AI)) return;
586
587     StackAlignment = std::max(StackAlignment, AI.getAlignment());
588     if (isDynamicAlloca(AI))
589       DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
590     else
591       AllocaVec.push_back(&AI);
592   }
593
594   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
595   /// errors.
596   void visitIntrinsicInst(IntrinsicInst &II) {
597     if (!ClCheckLifetime) return;
598     Intrinsic::ID ID = II.getIntrinsicID();
599     if (ID != Intrinsic::lifetime_start &&
600         ID != Intrinsic::lifetime_end)
601       return;
602     // Found lifetime intrinsic, add ASan instrumentation if necessary.
603     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
604     // If size argument is undefined, don't do anything.
605     if (Size->isMinusOne()) return;
606     // Check that size doesn't saturate uint64_t and can
607     // be stored in IntptrTy.
608     const uint64_t SizeValue = Size->getValue().getLimitedValue();
609     if (SizeValue == ~0ULL ||
610         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
611       return;
612     // Find alloca instruction that corresponds to llvm.lifetime argument.
613     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
614     if (!AI) return;
615     bool DoPoison = (ID == Intrinsic::lifetime_end);
616     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
617     AllocaPoisonCallVec.push_back(APC);
618   }
619
620   // ---------------------- Helpers.
621   void initializeCallbacks(Module &M);
622
623   bool doesDominateAllExits(const Instruction *I) const {
624     for (auto Ret : RetVec) {
625       if (!ASan.getDominatorTree().dominates(I, Ret))
626         return false;
627     }
628     return true;
629   }
630
631   bool isDynamicAlloca(AllocaInst &AI) const {
632     return AI.isArrayAllocation() || !AI.isStaticAlloca();
633   }
634
635   // Check if we want (and can) handle this alloca.
636   bool isInterestingAlloca(AllocaInst &AI) const {
637     return (AI.getAllocatedType()->isSized() &&
638             // alloca() may be called with 0 size, ignore it.
639             getAllocaSizeInBytes(&AI) > 0);
640   }
641
642   uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
643     Type *Ty = AI->getAllocatedType();
644     uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
645     return SizeInBytes;
646   }
647   /// Finds alloca where the value comes from.
648   AllocaInst *findAllocaForValue(Value *V);
649   void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
650                       Value *ShadowBase, bool DoPoison);
651   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
652
653   void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
654                                           int Size);
655 };
656
657 }  // namespace
658
659 char AddressSanitizer::ID = 0;
660 INITIALIZE_PASS_BEGIN(AddressSanitizer, "asan",
661     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
662     false, false)
663 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
664 INITIALIZE_PASS_END(AddressSanitizer, "asan",
665     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
666     false, false)
667 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
668   return new AddressSanitizer();
669 }
670
671 char AddressSanitizerModule::ID = 0;
672 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
673     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
674     "ModulePass", false, false)
675 ModulePass *llvm::createAddressSanitizerModulePass() {
676   return new AddressSanitizerModule();
677 }
678
679 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
680   size_t Res = countTrailingZeros(TypeSize / 8);
681   assert(Res < kNumberOfAccessSizes);
682   return Res;
683 }
684
685 // \brief Create a constant for Str so that we can pass it to the run-time lib.
686 static GlobalVariable *createPrivateGlobalForString(
687     Module &M, StringRef Str, bool AllowMerging) {
688   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
689   // We use private linkage for module-local strings. If they can be merged
690   // with another one, we set the unnamed_addr attribute.
691   GlobalVariable *GV =
692       new GlobalVariable(M, StrConst->getType(), true,
693                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
694   if (AllowMerging)
695     GV->setUnnamedAddr(true);
696   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
697   return GV;
698 }
699
700 /// \brief Create a global describing a source location.
701 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
702                                                        LocationMetadata MD) {
703   Constant *LocData[] = {
704       createPrivateGlobalForString(M, MD.Filename, true),
705       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
706       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
707   };
708   auto LocStruct = ConstantStruct::getAnon(LocData);
709   auto GV = new GlobalVariable(M, LocStruct->getType(), true,
710                                GlobalValue::PrivateLinkage, LocStruct,
711                                kAsanGenPrefix);
712   GV->setUnnamedAddr(true);
713   return GV;
714 }
715
716 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
717   return G->getName().find(kAsanGenPrefix) == 0 ||
718          G->getName().find(kSanCovGenPrefix) == 0;
719 }
720
721 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
722   // Shadow >> scale
723   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
724   if (Mapping.Offset == 0)
725     return Shadow;
726   // (Shadow >> scale) | offset
727   if (Mapping.OrShadowOffset)
728     return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
729   else
730     return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
731 }
732
733 // Instrument memset/memmove/memcpy
734 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
735   IRBuilder<> IRB(MI);
736   if (isa<MemTransferInst>(MI)) {
737     IRB.CreateCall3(
738         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
739         IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
740         IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
741         IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
742   } else if (isa<MemSetInst>(MI)) {
743     IRB.CreateCall3(
744         AsanMemset,
745         IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
746         IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
747         IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
748   }
749   MI->eraseFromParent();
750 }
751
752 // If I is an interesting memory access, return the PointerOperand
753 // and set IsWrite/Alignment. Otherwise return nullptr.
754 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
755                                         unsigned *Alignment) {
756   // Skip memory accesses inserted by another instrumentation.
757   if (I->getMetadata("nosanitize"))
758     return nullptr;
759   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
760     if (!ClInstrumentReads) return nullptr;
761     *IsWrite = false;
762     *Alignment = LI->getAlignment();
763     return LI->getPointerOperand();
764   }
765   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
766     if (!ClInstrumentWrites) return nullptr;
767     *IsWrite = true;
768     *Alignment = SI->getAlignment();
769     return SI->getPointerOperand();
770   }
771   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
772     if (!ClInstrumentAtomics) return nullptr;
773     *IsWrite = true;
774     *Alignment = 0;
775     return RMW->getPointerOperand();
776   }
777   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
778     if (!ClInstrumentAtomics) return nullptr;
779     *IsWrite = true;
780     *Alignment = 0;
781     return XCHG->getPointerOperand();
782   }
783   return nullptr;
784 }
785
786 static bool isPointerOperand(Value *V) {
787   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
788 }
789
790 // This is a rough heuristic; it may cause both false positives and
791 // false negatives. The proper implementation requires cooperation with
792 // the frontend.
793 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
794   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
795     if (!Cmp->isRelational())
796       return false;
797   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
798     if (BO->getOpcode() != Instruction::Sub)
799       return false;
800   } else {
801     return false;
802   }
803   if (!isPointerOperand(I->getOperand(0)) ||
804       !isPointerOperand(I->getOperand(1)))
805       return false;
806   return true;
807 }
808
809 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
810   // If a global variable does not have dynamic initialization we don't
811   // have to instrument it.  However, if a global does not have initializer
812   // at all, we assume it has dynamic initializer (in other TU).
813   return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
814 }
815
816 void
817 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
818   IRBuilder<> IRB(I);
819   Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
820   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
821   for (int i = 0; i < 2; i++) {
822     if (Param[i]->getType()->isPointerTy())
823       Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
824   }
825   IRB.CreateCall2(F, Param[0], Param[1]);
826 }
827
828 void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
829   bool IsWrite = false;
830   unsigned Alignment = 0;
831   Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
832   assert(Addr);
833   if (ClOpt && ClOptGlobals) {
834     if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
835       // If initialization order checking is disabled, a simple access to a
836       // dynamically initialized global is always valid.
837       if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
838         NumOptimizedAccessesToGlobalVar++;
839         return;
840       }
841     }
842     ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
843     if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
844       if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
845         if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
846           NumOptimizedAccessesToGlobalArray++;
847           return;
848         }
849       }
850     }
851   }
852
853   Type *OrigPtrTy = Addr->getType();
854   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
855
856   assert(OrigTy->isSized());
857   uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
858
859   assert((TypeSize % 8) == 0);
860
861   if (IsWrite)
862     NumInstrumentedWrites++;
863   else
864     NumInstrumentedReads++;
865
866   unsigned Granularity = 1 << Mapping.Scale;
867   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
868   // if the data is properly aligned.
869   if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
870        TypeSize == 128) &&
871       (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
872     return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
873   // Instrument unusual size or unusual alignment.
874   // We can not do it with a single check, so we do 1-byte check for the first
875   // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
876   // to report the actual access size.
877   IRBuilder<> IRB(I);
878   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
879   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
880   if (UseCalls) {
881     IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
882   } else {
883     Value *LastByte = IRB.CreateIntToPtr(
884         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
885         OrigPtrTy);
886     instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
887     instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
888   }
889 }
890
891 // Validate the result of Module::getOrInsertFunction called for an interface
892 // function of AddressSanitizer. If the instrumented module defines a function
893 // with the same name, their prototypes must match, otherwise
894 // getOrInsertFunction returns a bitcast.
895 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
896   if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
897   FuncOrBitcast->dump();
898   report_fatal_error("trying to redefine an AddressSanitizer "
899                      "interface function");
900 }
901
902 Instruction *AddressSanitizer::generateCrashCode(
903     Instruction *InsertBefore, Value *Addr,
904     bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
905   IRBuilder<> IRB(InsertBefore);
906   CallInst *Call = SizeArgument
907     ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
908     : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
909
910   // We don't do Call->setDoesNotReturn() because the BB already has
911   // UnreachableInst at the end.
912   // This EmptyAsm is required to avoid callback merge.
913   IRB.CreateCall(EmptyAsm);
914   return Call;
915 }
916
917 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
918                                             Value *ShadowValue,
919                                             uint32_t TypeSize) {
920   size_t Granularity = 1 << Mapping.Scale;
921   // Addr & (Granularity - 1)
922   Value *LastAccessedByte = IRB.CreateAnd(
923       AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
924   // (Addr & (Granularity - 1)) + size - 1
925   if (TypeSize / 8 > 1)
926     LastAccessedByte = IRB.CreateAdd(
927         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
928   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
929   LastAccessedByte = IRB.CreateIntCast(
930       LastAccessedByte, ShadowValue->getType(), false);
931   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
932   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
933 }
934
935 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
936                                          Instruction *InsertBefore, Value *Addr,
937                                          uint32_t TypeSize, bool IsWrite,
938                                          Value *SizeArgument, bool UseCalls) {
939   IRBuilder<> IRB(InsertBefore);
940   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
941   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
942
943   if (UseCalls) {
944     IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
945                    AddrLong);
946     return;
947   }
948
949   Type *ShadowTy  = IntegerType::get(
950       *C, std::max(8U, TypeSize >> Mapping.Scale));
951   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
952   Value *ShadowPtr = memToShadow(AddrLong, IRB);
953   Value *CmpVal = Constant::getNullValue(ShadowTy);
954   Value *ShadowValue = IRB.CreateLoad(
955       IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
956
957   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
958   size_t Granularity = 1 << Mapping.Scale;
959   TerminatorInst *CrashTerm = nullptr;
960
961   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
962     // We use branch weights for the slow path check, to indicate that the slow
963     // path is rarely taken. This seems to be the case for SPEC benchmarks.
964     TerminatorInst *CheckTerm =
965         SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
966             MDBuilder(*C).createBranchWeights(1, 100000));
967     assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
968     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
969     IRB.SetInsertPoint(CheckTerm);
970     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
971     BasicBlock *CrashBlock =
972         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
973     CrashTerm = new UnreachableInst(*C, CrashBlock);
974     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
975     ReplaceInstWithInst(CheckTerm, NewTerm);
976   } else {
977     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
978   }
979
980   Instruction *Crash = generateCrashCode(
981       CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
982   Crash->setDebugLoc(OrigIns->getDebugLoc());
983 }
984
985 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
986                                                   GlobalValue *ModuleName) {
987   // Set up the arguments to our poison/unpoison functions.
988   IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
989
990   // Add a call to poison all external globals before the given function starts.
991   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
992   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
993
994   // Add calls to unpoison all globals before each return instruction.
995   for (auto &BB : GlobalInit.getBasicBlockList())
996     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
997       CallInst::Create(AsanUnpoisonGlobals, "", RI);
998 }
999
1000 void AddressSanitizerModule::createInitializerPoisonCalls(
1001     Module &M, GlobalValue *ModuleName) {
1002   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1003
1004   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1005   for (Use &OP : CA->operands()) {
1006     if (isa<ConstantAggregateZero>(OP))
1007       continue;
1008     ConstantStruct *CS = cast<ConstantStruct>(OP);
1009
1010     // Must have a function or null ptr.
1011     if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
1012       if (F->getName() == kAsanModuleCtorName) continue;
1013       ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1014       // Don't instrument CTORs that will run before asan.module_ctor.
1015       if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1016       poisonOneInitializer(*F, ModuleName);
1017     }
1018   }
1019 }
1020
1021 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1022   Type *Ty = cast<PointerType>(G->getType())->getElementType();
1023   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1024
1025   if (GlobalsMD.get(G).IsBlacklisted) return false;
1026   if (!Ty->isSized()) return false;
1027   if (!G->hasInitializer()) return false;
1028   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
1029   // Touch only those globals that will not be defined in other modules.
1030   // Don't handle ODR linkage types and COMDATs since other modules may be built
1031   // without ASan.
1032   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1033       G->getLinkage() != GlobalVariable::PrivateLinkage &&
1034       G->getLinkage() != GlobalVariable::InternalLinkage)
1035     return false;
1036   if (G->hasComdat())
1037     return false;
1038   // Two problems with thread-locals:
1039   //   - The address of the main thread's copy can't be computed at link-time.
1040   //   - Need to poison all copies, not just the main thread's one.
1041   if (G->isThreadLocal())
1042     return false;
1043   // For now, just ignore this Global if the alignment is large.
1044   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1045
1046   if (G->hasSection()) {
1047     StringRef Section(G->getSection());
1048
1049     if (TargetTriple.isOSBinFormatMachO()) {
1050       StringRef ParsedSegment, ParsedSection;
1051       unsigned TAA = 0, StubSize = 0;
1052       bool TAAParsed;
1053       std::string ErrorCode =
1054         MCSectionMachO::ParseSectionSpecifier(Section, ParsedSegment,
1055                                               ParsedSection, TAA, TAAParsed,
1056                                               StubSize);
1057       if (!ErrorCode.empty()) {
1058         report_fatal_error("Invalid section specifier '" + ParsedSection +
1059                            "': " + ErrorCode + ".");
1060       }
1061
1062       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1063       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1064       // them.
1065       if (ParsedSegment == "__OBJC" ||
1066           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1067         DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1068         return false;
1069       }
1070       // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1071       // Constant CFString instances are compiled in the following way:
1072       //  -- the string buffer is emitted into
1073       //     __TEXT,__cstring,cstring_literals
1074       //  -- the constant NSConstantString structure referencing that buffer
1075       //     is placed into __DATA,__cfstring
1076       // Therefore there's no point in placing redzones into __DATA,__cfstring.
1077       // Moreover, it causes the linker to crash on OS X 10.7
1078       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1079         DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1080         return false;
1081       }
1082       // The linker merges the contents of cstring_literals and removes the
1083       // trailing zeroes.
1084       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1085         DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1086         return false;
1087       }
1088     }
1089
1090     // Callbacks put into the CRT initializer/terminator sections
1091     // should not be instrumented.
1092     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1093     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1094     if (Section.startswith(".CRT")) {
1095       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1096       return false;
1097     }
1098
1099     // Globals from llvm.metadata aren't emitted, do not instrument them.
1100     if (Section == "llvm.metadata") return false;
1101   }
1102
1103   return true;
1104 }
1105
1106 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1107   IRBuilder<> IRB(*C);
1108   // Declare our poisoning and unpoisoning functions.
1109   AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1110       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1111   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1112   AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1113       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1114   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1115   // Declare functions that register/unregister globals.
1116   AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1117       kAsanRegisterGlobalsName, IRB.getVoidTy(),
1118       IntptrTy, IntptrTy, nullptr));
1119   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1120   AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1121       kAsanUnregisterGlobalsName,
1122       IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1123   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1124 }
1125
1126 // This function replaces all global variables with new variables that have
1127 // trailing redzones. It also creates a function that poisons
1128 // redzones and inserts this function into llvm.global_ctors.
1129 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1130   GlobalsMD.init(M);
1131
1132   SmallVector<GlobalVariable *, 16> GlobalsToChange;
1133
1134   for (auto &G : M.globals()) {
1135     if (ShouldInstrumentGlobal(&G))
1136       GlobalsToChange.push_back(&G);
1137   }
1138
1139   size_t n = GlobalsToChange.size();
1140   if (n == 0) return false;
1141
1142   // A global is described by a structure
1143   //   size_t beg;
1144   //   size_t size;
1145   //   size_t size_with_redzone;
1146   //   const char *name;
1147   //   const char *module_name;
1148   //   size_t has_dynamic_init;
1149   //   void *source_location;
1150   // We initialize an array of such structures and pass it to a run-time call.
1151   StructType *GlobalStructTy =
1152       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1153                       IntptrTy, IntptrTy, nullptr);
1154   SmallVector<Constant *, 16> Initializers(n);
1155
1156   bool HasDynamicallyInitializedGlobals = false;
1157
1158   // We shouldn't merge same module names, as this string serves as unique
1159   // module ID in runtime.
1160   GlobalVariable *ModuleName = createPrivateGlobalForString(
1161       M, M.getModuleIdentifier(), /*AllowMerging*/false);
1162
1163   for (size_t i = 0; i < n; i++) {
1164     static const uint64_t kMaxGlobalRedzone = 1 << 18;
1165     GlobalVariable *G = GlobalsToChange[i];
1166
1167     auto MD = GlobalsMD.get(G);
1168     // Create string holding the global name (use global name from metadata
1169     // if it's available, otherwise just write the name of global variable).
1170     GlobalVariable *Name = createPrivateGlobalForString(
1171         M, MD.Name.empty() ? G->getName() : MD.Name,
1172         /*AllowMerging*/ true);
1173
1174     PointerType *PtrTy = cast<PointerType>(G->getType());
1175     Type *Ty = PtrTy->getElementType();
1176     uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1177     uint64_t MinRZ = MinRedzoneSizeForGlobal();
1178     // MinRZ <= RZ <= kMaxGlobalRedzone
1179     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1180     uint64_t RZ = std::max(MinRZ,
1181                          std::min(kMaxGlobalRedzone,
1182                                   (SizeInBytes / MinRZ / 4) * MinRZ));
1183     uint64_t RightRedzoneSize = RZ;
1184     // Round up to MinRZ
1185     if (SizeInBytes % MinRZ)
1186       RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1187     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1188     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1189
1190     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1191     Constant *NewInitializer = ConstantStruct::get(
1192         NewTy, G->getInitializer(),
1193         Constant::getNullValue(RightRedZoneTy), nullptr);
1194
1195     // Create a new global variable with enough space for a redzone.
1196     GlobalValue::LinkageTypes Linkage = G->getLinkage();
1197     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1198       Linkage = GlobalValue::InternalLinkage;
1199     GlobalVariable *NewGlobal = new GlobalVariable(
1200         M, NewTy, G->isConstant(), Linkage,
1201         NewInitializer, "", G, G->getThreadLocalMode());
1202     NewGlobal->copyAttributesFrom(G);
1203     NewGlobal->setAlignment(MinRZ);
1204
1205     Value *Indices2[2];
1206     Indices2[0] = IRB.getInt32(0);
1207     Indices2[1] = IRB.getInt32(0);
1208
1209     G->replaceAllUsesWith(
1210         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1211     NewGlobal->takeName(G);
1212     G->eraseFromParent();
1213
1214     Constant *SourceLoc;
1215     if (!MD.SourceLoc.empty()) {
1216       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1217       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1218     } else {
1219       SourceLoc = ConstantInt::get(IntptrTy, 0);
1220     }
1221
1222     Initializers[i] = ConstantStruct::get(
1223         GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1224         ConstantInt::get(IntptrTy, SizeInBytes),
1225         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1226         ConstantExpr::getPointerCast(Name, IntptrTy),
1227         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1228         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
1229
1230     if (ClInitializers && MD.IsDynInit)
1231       HasDynamicallyInitializedGlobals = true;
1232
1233     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1234   }
1235
1236   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1237   GlobalVariable *AllGlobals = new GlobalVariable(
1238       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1239       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1240
1241   // Create calls for poisoning before initializers run and unpoisoning after.
1242   if (HasDynamicallyInitializedGlobals)
1243     createInitializerPoisonCalls(M, ModuleName);
1244   IRB.CreateCall2(AsanRegisterGlobals,
1245                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
1246                   ConstantInt::get(IntptrTy, n));
1247
1248   // We also need to unregister globals at the end, e.g. when a shared library
1249   // gets closed.
1250   Function *AsanDtorFunction = Function::Create(
1251       FunctionType::get(Type::getVoidTy(*C), false),
1252       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1253   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1254   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1255   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1256                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
1257                        ConstantInt::get(IntptrTy, n));
1258   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1259
1260   DEBUG(dbgs() << M);
1261   return true;
1262 }
1263
1264 bool AddressSanitizerModule::runOnModule(Module &M) {
1265   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1266   if (!DLP)
1267     return false;
1268   DL = &DLP->getDataLayout();
1269   C = &(M.getContext());
1270   int LongSize = DL->getPointerSizeInBits();
1271   IntptrTy = Type::getIntNTy(*C, LongSize);
1272   TargetTriple = Triple(M.getTargetTriple());
1273   Mapping = getShadowMapping(TargetTriple, LongSize);
1274   initializeCallbacks(M);
1275
1276   bool Changed = false;
1277
1278   Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1279   assert(CtorFunc);
1280   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1281
1282   if (ClGlobals)
1283     Changed |= InstrumentGlobals(IRB, M);
1284
1285   return Changed;
1286 }
1287
1288 void AddressSanitizer::initializeCallbacks(Module &M) {
1289   IRBuilder<> IRB(*C);
1290   // Create __asan_report* callbacks.
1291   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1292     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1293          AccessSizeIndex++) {
1294       // IsWrite and TypeSize are encoded in the function name.
1295       std::string Suffix =
1296           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1297       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1298           checkInterfaceFunction(
1299               M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1300                                     IRB.getVoidTy(), IntptrTy, nullptr));
1301       AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1302           checkInterfaceFunction(
1303               M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1304                                     IRB.getVoidTy(), IntptrTy, nullptr));
1305     }
1306   }
1307   AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1308               kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1309   AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1310               kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1311
1312   AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1313       M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1314                             IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1315   AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1316       M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1317                             IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1318
1319   AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1320       ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1321       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1322   AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1323       ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1324       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1325   AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1326       ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1327       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1328
1329   AsanHandleNoReturnFunc = checkInterfaceFunction(
1330       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1331
1332   AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1333       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1334   AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1335       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1336   // We insert an empty inline asm after __asan_report* to avoid callback merge.
1337   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1338                             StringRef(""), StringRef(""),
1339                             /*hasSideEffects=*/true);
1340 }
1341
1342 // virtual
1343 bool AddressSanitizer::doInitialization(Module &M) {
1344   // Initialize the private fields. No one has accessed them before.
1345   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1346   if (!DLP)
1347     report_fatal_error("data layout missing");
1348   DL = &DLP->getDataLayout();
1349
1350   GlobalsMD.init(M);
1351
1352   C = &(M.getContext());
1353   LongSize = DL->getPointerSizeInBits();
1354   IntptrTy = Type::getIntNTy(*C, LongSize);
1355   TargetTriple = Triple(M.getTargetTriple());
1356
1357   AsanCtorFunction = Function::Create(
1358       FunctionType::get(Type::getVoidTy(*C), false),
1359       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1360   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1361   // call __asan_init in the module ctor.
1362   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1363   AsanInitFunction = checkInterfaceFunction(
1364       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
1365   AsanInitFunction->setLinkage(Function::ExternalLinkage);
1366   IRB.CreateCall(AsanInitFunction);
1367
1368   Mapping = getShadowMapping(TargetTriple, LongSize);
1369
1370   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1371   return true;
1372 }
1373
1374 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1375   // For each NSObject descendant having a +load method, this method is invoked
1376   // by the ObjC runtime before any of the static constructors is called.
1377   // Therefore we need to instrument such methods with a call to __asan_init
1378   // at the beginning in order to initialize our runtime before any access to
1379   // the shadow memory.
1380   // We cannot just ignore these methods, because they may call other
1381   // instrumented functions.
1382   if (F.getName().find(" load]") != std::string::npos) {
1383     IRBuilder<> IRB(F.begin()->begin());
1384     IRB.CreateCall(AsanInitFunction);
1385     return true;
1386   }
1387   return false;
1388 }
1389
1390 bool AddressSanitizer::runOnFunction(Function &F) {
1391   if (&F == AsanCtorFunction) return false;
1392   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1393   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1394   initializeCallbacks(*F.getParent());
1395
1396   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1397
1398   // If needed, insert __asan_init before checking for SanitizeAddress attr.
1399   maybeInsertAsanInitAtFunctionEntry(F);
1400
1401   if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1402     return false;
1403
1404   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1405     return false;
1406
1407   // We want to instrument every address only once per basic block (unless there
1408   // are calls between uses).
1409   SmallSet<Value*, 16> TempsToInstrument;
1410   SmallVector<Instruction*, 16> ToInstrument;
1411   SmallVector<Instruction*, 8> NoReturnCalls;
1412   SmallVector<BasicBlock*, 16> AllBlocks;
1413   SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1414   int NumAllocas = 0;
1415   bool IsWrite;
1416   unsigned Alignment;
1417
1418   // Fill the set of memory operations to instrument.
1419   for (auto &BB : F) {
1420     AllBlocks.push_back(&BB);
1421     TempsToInstrument.clear();
1422     int NumInsnsPerBB = 0;
1423     for (auto &Inst : BB) {
1424       if (LooksLikeCodeInBug11395(&Inst)) return false;
1425       if (Value *Addr =
1426               isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
1427         if (ClOpt && ClOptSameTemp) {
1428           if (!TempsToInstrument.insert(Addr).second)
1429             continue;  // We've seen this temp in the current BB.
1430         }
1431       } else if (ClInvalidPointerPairs &&
1432                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
1433         PointerComparisonsOrSubtracts.push_back(&Inst);
1434         continue;
1435       } else if (isa<MemIntrinsic>(Inst)) {
1436         // ok, take it.
1437       } else {
1438         if (isa<AllocaInst>(Inst))
1439           NumAllocas++;
1440         CallSite CS(&Inst);
1441         if (CS) {
1442           // A call inside BB.
1443           TempsToInstrument.clear();
1444           if (CS.doesNotReturn())
1445             NoReturnCalls.push_back(CS.getInstruction());
1446         }
1447         continue;
1448       }
1449       ToInstrument.push_back(&Inst);
1450       NumInsnsPerBB++;
1451       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1452         break;
1453     }
1454   }
1455
1456   bool UseCalls = false;
1457   if (ClInstrumentationWithCallsThreshold >= 0 &&
1458       ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1459     UseCalls = true;
1460
1461   // Instrument.
1462   int NumInstrumented = 0;
1463   for (auto Inst : ToInstrument) {
1464     if (ClDebugMin < 0 || ClDebugMax < 0 ||
1465         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1466       if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
1467         instrumentMop(Inst, UseCalls);
1468       else
1469         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1470     }
1471     NumInstrumented++;
1472   }
1473
1474   FunctionStackPoisoner FSP(F, *this);
1475   bool ChangedStack = FSP.runOnFunction();
1476
1477   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1478   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1479   for (auto CI : NoReturnCalls) {
1480     IRBuilder<> IRB(CI);
1481     IRB.CreateCall(AsanHandleNoReturnFunc);
1482   }
1483
1484   for (auto Inst : PointerComparisonsOrSubtracts) {
1485     instrumentPointerComparisonOrSubtraction(Inst);
1486     NumInstrumented++;
1487   }
1488
1489   bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1490
1491   DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1492
1493   return res;
1494 }
1495
1496 // Workaround for bug 11395: we don't want to instrument stack in functions
1497 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1498 // FIXME: remove once the bug 11395 is fixed.
1499 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1500   if (LongSize != 32) return false;
1501   CallInst *CI = dyn_cast<CallInst>(I);
1502   if (!CI || !CI->isInlineAsm()) return false;
1503   if (CI->getNumArgOperands() <= 5) return false;
1504   // We have inline assembly with quite a few arguments.
1505   return true;
1506 }
1507
1508 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1509   IRBuilder<> IRB(*C);
1510   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1511     std::string Suffix = itostr(i);
1512     AsanStackMallocFunc[i] = checkInterfaceFunction(
1513         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1514                               IntptrTy, IntptrTy, nullptr));
1515     AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1516         kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1517         IntptrTy, IntptrTy, nullptr));
1518   }
1519   AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1520       M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1521                             IntptrTy, IntptrTy, nullptr));
1522   AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1523       M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1524                             IntptrTy, IntptrTy, nullptr));
1525 }
1526
1527 void
1528 FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1529                                       IRBuilder<> &IRB, Value *ShadowBase,
1530                                       bool DoPoison) {
1531   size_t n = ShadowBytes.size();
1532   size_t i = 0;
1533   // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1534   // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1535   // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1536   for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1537        LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1538     for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1539       uint64_t Val = 0;
1540       for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1541         if (ASan.DL->isLittleEndian())
1542           Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1543         else
1544           Val = (Val << 8) | ShadowBytes[i + j];
1545       }
1546       if (!Val) continue;
1547       Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1548       Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1549       Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1550       IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1551     }
1552   }
1553 }
1554
1555 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1556 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1557 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1558   assert(LocalStackSize <= kMaxStackMallocSize);
1559   uint64_t MaxSize = kMinStackMallocSize;
1560   for (int i = 0; ; i++, MaxSize *= 2)
1561     if (LocalStackSize <= MaxSize)
1562       return i;
1563   llvm_unreachable("impossible LocalStackSize");
1564 }
1565
1566 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1567 // We can not use MemSet intrinsic because it may end up calling the actual
1568 // memset. Size is a multiple of 8.
1569 // Currently this generates 8-byte stores on x86_64; it may be better to
1570 // generate wider stores.
1571 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1572     IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1573   assert(!(Size % 8));
1574   assert(kAsanStackAfterReturnMagic == 0xf5);
1575   for (int i = 0; i < Size; i += 8) {
1576     Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1577     IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1578                     IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1579   }
1580 }
1581
1582 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1583   for (const auto &Inst : F.getEntryBlock())
1584     if (!isa<AllocaInst>(Inst))
1585       return Inst.getDebugLoc();
1586   return DebugLoc();
1587 }
1588
1589 void FunctionStackPoisoner::poisonStack() {
1590   assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1591
1592   if (ClInstrumentAllocas)
1593     // Handle dynamic allocas.
1594     for (auto &AllocaCall : DynamicAllocaVec)
1595       handleDynamicAllocaCall(AllocaCall);
1596
1597   if (AllocaVec.size() == 0) return;
1598
1599   int StackMallocIdx = -1;
1600   DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
1601
1602   Instruction *InsBefore = AllocaVec[0];
1603   IRBuilder<> IRB(InsBefore);
1604   IRB.SetCurrentDebugLocation(EntryDebugLocation);
1605
1606   SmallVector<ASanStackVariableDescription, 16> SVD;
1607   SVD.reserve(AllocaVec.size());
1608   for (AllocaInst *AI : AllocaVec) {
1609     ASanStackVariableDescription D = { AI->getName().data(),
1610                                    getAllocaSizeInBytes(AI),
1611                                    AI->getAlignment(), AI, 0};
1612     SVD.push_back(D);
1613   }
1614   // Minimal header size (left redzone) is 4 pointers,
1615   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1616   size_t MinHeaderSize = ASan.LongSize / 2;
1617   ASanStackFrameLayout L;
1618   ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1619   DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1620   uint64_t LocalStackSize = L.FrameSize;
1621   bool DoStackMalloc =
1622       ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1623
1624   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1625   AllocaInst *MyAlloca =
1626       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1627   MyAlloca->setDebugLoc(EntryDebugLocation);
1628   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1629   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1630   MyAlloca->setAlignment(FrameAlignment);
1631   assert(MyAlloca->isStaticAlloca());
1632   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1633   Value *LocalStackBase = OrigStackBase;
1634
1635   if (DoStackMalloc) {
1636     // LocalStackBase = OrigStackBase
1637     // if (__asan_option_detect_stack_use_after_return)
1638     //   LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1639     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1640     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1641     Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1642         kAsanOptionDetectUAR, IRB.getInt32Ty());
1643     Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1644                                   Constant::getNullValue(IRB.getInt32Ty()));
1645     Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1646     BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1647     IRBuilder<> IRBIf(Term);
1648     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1649     LocalStackBase = IRBIf.CreateCall2(
1650         AsanStackMallocFunc[StackMallocIdx],
1651         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1652     BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1653     IRB.SetInsertPoint(InsBefore);
1654     IRB.SetCurrentDebugLocation(EntryDebugLocation);
1655     PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1656     Phi->addIncoming(OrigStackBase, CmpBlock);
1657     Phi->addIncoming(LocalStackBase, SetBlock);
1658     LocalStackBase = Phi;
1659   }
1660
1661   // Insert poison calls for lifetime intrinsics for alloca.
1662   bool HavePoisonedAllocas = false;
1663   for (const auto &APC : AllocaPoisonCallVec) {
1664     assert(APC.InsBefore);
1665     assert(APC.AI);
1666     IRBuilder<> IRB(APC.InsBefore);
1667     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1668     HavePoisonedAllocas |= APC.DoPoison;
1669   }
1670
1671   // Replace Alloca instructions with base+offset.
1672   for (const auto &Desc : SVD) {
1673     AllocaInst *AI = Desc.AI;
1674     Value *NewAllocaPtr = IRB.CreateIntToPtr(
1675         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1676         AI->getType());
1677     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1678     AI->replaceAllUsesWith(NewAllocaPtr);
1679   }
1680
1681   // The left-most redzone has enough space for at least 4 pointers.
1682   // Write the Magic value to redzone[0].
1683   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1684   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1685                   BasePlus0);
1686   // Write the frame description constant to redzone[1].
1687   Value *BasePlus1 = IRB.CreateIntToPtr(
1688     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1689     IntptrPtrTy);
1690   GlobalVariable *StackDescriptionGlobal =
1691       createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1692                                    /*AllowMerging*/true);
1693   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1694                                              IntptrTy);
1695   IRB.CreateStore(Description, BasePlus1);
1696   // Write the PC to redzone[2].
1697   Value *BasePlus2 = IRB.CreateIntToPtr(
1698     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1699                                                    2 * ASan.LongSize/8)),
1700     IntptrPtrTy);
1701   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1702
1703   // Poison the stack redzones at the entry.
1704   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1705   poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1706
1707   // (Un)poison the stack before all ret instructions.
1708   for (auto Ret : RetVec) {
1709     IRBuilder<> IRBRet(Ret);
1710     // Mark the current frame as retired.
1711     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1712                        BasePlus0);
1713     if (DoStackMalloc) {
1714       assert(StackMallocIdx >= 0);
1715       // if LocalStackBase != OrigStackBase:
1716       //     // In use-after-return mode, poison the whole stack frame.
1717       //     if StackMallocIdx <= 4
1718       //         // For small sizes inline the whole thing:
1719       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1720       //         **SavedFlagPtr(LocalStackBase) = 0
1721       //     else
1722       //         __asan_stack_free_N(LocalStackBase, OrigStackBase)
1723       // else
1724       //     <This is not a fake stack; unpoison the redzones>
1725       Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1726       TerminatorInst *ThenTerm, *ElseTerm;
1727       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1728
1729       IRBuilder<> IRBPoison(ThenTerm);
1730       if (StackMallocIdx <= 4) {
1731         int ClassSize = kMinStackMallocSize << StackMallocIdx;
1732         SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1733                                            ClassSize >> Mapping.Scale);
1734         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1735             LocalStackBase,
1736             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1737         Value *SavedFlagPtr = IRBPoison.CreateLoad(
1738             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1739         IRBPoison.CreateStore(
1740             Constant::getNullValue(IRBPoison.getInt8Ty()),
1741             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1742       } else {
1743         // For larger frames call __asan_stack_free_*.
1744         IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1745                               ConstantInt::get(IntptrTy, LocalStackSize),
1746                               OrigStackBase);
1747       }
1748
1749       IRBuilder<> IRBElse(ElseTerm);
1750       poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1751     } else if (HavePoisonedAllocas) {
1752       // If we poisoned some allocas in llvm.lifetime analysis,
1753       // unpoison whole stack frame now.
1754       assert(LocalStackBase == OrigStackBase);
1755       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1756     } else {
1757       poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1758     }
1759   }
1760
1761   if (ClInstrumentAllocas)
1762     // Unpoison dynamic allocas.
1763     for (auto &AllocaCall : DynamicAllocaVec)
1764       unpoisonDynamicAlloca(AllocaCall);
1765
1766   // We are done. Remove the old unused alloca instructions.
1767   for (auto AI : AllocaVec)
1768     AI->eraseFromParent();
1769 }
1770
1771 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1772                                          IRBuilder<> &IRB, bool DoPoison) {
1773   // For now just insert the call to ASan runtime.
1774   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1775   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1776   IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1777                            : AsanUnpoisonStackMemoryFunc,
1778                   AddrArg, SizeArg);
1779 }
1780
1781 // Handling llvm.lifetime intrinsics for a given %alloca:
1782 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1783 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1784 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1785 //     could be poisoned by previous llvm.lifetime.end instruction, as the
1786 //     variable may go in and out of scope several times, e.g. in loops).
1787 // (3) if we poisoned at least one %alloca in a function,
1788 //     unpoison the whole stack frame at function exit.
1789
1790 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1791   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1792     // We're intested only in allocas we can handle.
1793     return isInterestingAlloca(*AI) ? AI : nullptr;
1794   // See if we've already calculated (or started to calculate) alloca for a
1795   // given value.
1796   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1797   if (I != AllocaForValue.end())
1798     return I->second;
1799   // Store 0 while we're calculating alloca for value V to avoid
1800   // infinite recursion if the value references itself.
1801   AllocaForValue[V] = nullptr;
1802   AllocaInst *Res = nullptr;
1803   if (CastInst *CI = dyn_cast<CastInst>(V))
1804     Res = findAllocaForValue(CI->getOperand(0));
1805   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1806     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1807       Value *IncValue = PN->getIncomingValue(i);
1808       // Allow self-referencing phi-nodes.
1809       if (IncValue == PN) continue;
1810       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1811       // AI for incoming values should exist and should all be equal.
1812       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1813         return nullptr;
1814       Res = IncValueAI;
1815     }
1816   }
1817   if (Res)
1818     AllocaForValue[V] = Res;
1819   return Res;
1820 }
1821
1822 // Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1823 // constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1824 // (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1825 //     only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1826 //     8-byte chunk of user memory respectively.
1827 // (2) Val2 forms the value for marking first poisoned byte in shadow memory
1828 //     with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1829
1830 // Shift = Padding & ~7; // the number of bits we need to shift to access first
1831 //                          chunk in shadow memory, containing nonzero bytes.
1832 // Example:
1833 // Padding = 21                       Padding = 16
1834 // Shadow:  |00|00|05|cb|          Shadow:  |00|00|cb|cb|
1835 //                ^                               ^
1836 //                |                               |
1837 // Shift = 21 & ~7 = 16            Shift = 16 & ~7 = 16
1838 //
1839 // Val1 = 0xcbcbcbcb << Shift;
1840 // PartialBits = Padding ? Padding & 7 : 0xcb;
1841 // Val2 = PartialBits << Shift;
1842 // Result = Val1 | Val2;
1843 Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1844                                                     IRBuilder<> &IRB) {
1845   PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1846   Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1847   unsigned Val1Int = kAsanAllocaPartialVal1;
1848   unsigned Val2Int = kAsanAllocaPartialVal2;
1849   if (!ASan.DL->isLittleEndian()) {
1850     Val1Int = sys::getSwappedBytes(Val1Int);
1851     Val2Int = sys::getSwappedBytes(Val2Int);
1852   }
1853   Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1854   Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
1855   // For BigEndian get 0x000000YZ -> 0xYZ000000.
1856   if (ASan.DL->isBigEndian())
1857     PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
1858   Value *Val2 = IRB.getInt32(Val2Int);
1859   Value *Cond =
1860       IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
1861   Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
1862                           shiftAllocaMagic(Val2, IRB, Shift));
1863   return IRB.CreateOr(Val1, Val2);
1864 }
1865
1866 void FunctionStackPoisoner::handleDynamicAllocaCall(
1867     DynamicAllocaCall &AllocaCall) {
1868   AllocaInst *AI = AllocaCall.AI;
1869   if (!doesDominateAllExits(AI)) {
1870     // We do not yet handle complex allocas
1871     AllocaCall.Poison = false;
1872     return;
1873   }
1874
1875   IRBuilder<> IRB(AI);
1876
1877   PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
1878   const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1879   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1880
1881   Value *Zero = Constant::getNullValue(IntptrTy);
1882   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1883   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1884   Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
1885
1886   // Since we need to extend alloca with additional memory to locate
1887   // redzones, and OldSize is number of allocated blocks with
1888   // ElementSize size, get allocated memory size in bytes by
1889   // OldSize * ElementSize.
1890   unsigned ElementSize = ASan.DL->getTypeAllocSize(AI->getAllocatedType());
1891   Value *OldSize = IRB.CreateMul(AI->getArraySize(),
1892                                  ConstantInt::get(IntptrTy, ElementSize));
1893
1894   // PartialSize = OldSize % 32
1895   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1896
1897   // Misalign = kAllocaRzSize - PartialSize;
1898   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1899
1900   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1901   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1902   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1903
1904   // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1905   // Align is added to locate left redzone, PartialPadding for possible
1906   // partial redzone and kAllocaRzSize for right redzone respectively.
1907   Value *AdditionalChunkSize = IRB.CreateAdd(
1908       ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1909
1910   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1911
1912   // Insert new alloca with new NewSize and Align params.
1913   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1914   NewAlloca->setAlignment(Align);
1915
1916   // NewAddress = Address + Align
1917   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
1918                                     ConstantInt::get(IntptrTy, Align));
1919
1920   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
1921
1922   // LeftRzAddress = NewAddress - kAllocaRzSize
1923   Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
1924
1925   // Poisoning left redzone.
1926   AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
1927   IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
1928                   IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
1929
1930   // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
1931   Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
1932   Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
1933
1934   // Poisoning partial redzone.
1935   Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
1936   Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
1937   IRB.CreateStore(PartialRzMagic,
1938                   IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
1939
1940   // RightRzAddress
1941   //   =  (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
1942   Value *RightRzAddress = IRB.CreateAnd(
1943       IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
1944
1945   // Poisoning right redzone.
1946   AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
1947   IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
1948                   IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
1949
1950   // Replace all uses of AddessReturnedByAlloca with NewAddress.
1951   AI->replaceAllUsesWith(NewAddressPtr);
1952
1953   // We are done. Erase old alloca and store left, partial and right redzones
1954   // shadow addresses for future unpoisoning.
1955   AI->eraseFromParent();
1956   NumInstrumentedDynamicAllocas++;
1957 }