blob: 8b6d64d5ba0c116d54f0b678cfcff0f4f44005a7 [file] [log] [blame]
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001//===-- 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#define DEBUG_TYPE "asan"
17
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000019#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov1c8b8252012-12-27 08:50:58 +000020#include "llvm/ADT/DenseMap.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000021#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000022#include "llvm/ADT/OwningPtr.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000027#include "llvm/ADT/Triple.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000028#include "llvm/DIBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000037#include "llvm/InstVisitor.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/DataTypes.h"
40#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000041#include "llvm/Support/raw_ostream.h"
42#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043#include "llvm/Target/TargetMachine.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth90230c82013-01-19 08:03:47 +000045#include "llvm/Transforms/Utils/BlackList.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000046#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000047#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000048#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000049#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000050
51using namespace llvm;
52
53static const uint64_t kDefaultShadowScale = 3;
54static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
55static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
56
57static const size_t kMaxStackMallocSize = 1 << 16; // 64K
58static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
59static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
60
61static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000062static const char *kAsanModuleDtorName = "asan.module_dtor";
63static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000064static const char *kAsanReportErrorTemplate = "__asan_report_";
65static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000066static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000067static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
68static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000069static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000070static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000071static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
72static const char *kAsanMappingScaleName = "__asan_mapping_scale";
73static const char *kAsanStackMallocName = "__asan_stack_malloc";
74static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000075static const char *kAsanGenPrefix = "__asan_gen_";
Alexey Samsonovf985f442012-12-04 01:34:23 +000076static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
77static const char *kAsanUnpoisonStackMemoryName =
78 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000079
80static const int kAsanStackLeftRedzoneMagic = 0xf1;
81static const int kAsanStackMidRedzoneMagic = 0xf2;
82static const int kAsanStackRightRedzoneMagic = 0xf3;
83static const int kAsanStackPartialRedzoneMagic = 0xf4;
84
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000085// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
86static const size_t kNumberOfAccessSizes = 5;
87
Kostya Serebryany800e03f2011-11-16 01:35:23 +000088// Command-line flags.
89
90// This flag may need to be replaced with -f[no-]asan-reads.
91static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
92 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
93static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
94 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000095static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
96 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
97 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +000098static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
99 cl::desc("use instrumentation with slow path for all accesses"),
100 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000101// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000102// in any given BB. Normally, this should be set to unlimited (INT_MAX),
103// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
104// set it to 10000.
105static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
106 cl::init(10000),
107 cl::desc("maximal number of instructions to instrument in any given BB"),
108 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000109// This flag may need to be replaced with -f[no]asan-stack.
110static cl::opt<bool> ClStack("asan-stack",
111 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
112// This flag may need to be replaced with -f[no]asan-use-after-return.
113static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
114 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
115// This flag may need to be replaced with -f[no]asan-globals.
116static cl::opt<bool> ClGlobals("asan-globals",
117 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000118static cl::opt<bool> ClInitializers("asan-initialization-order",
119 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000120static cl::opt<bool> ClMemIntrin("asan-memintrin",
121 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000122static cl::opt<bool> ClRealignStack("asan-realign-stack",
123 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000124static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
125 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000126 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000127
128// These flags allow to change the shadow mapping.
129// The shadow mapping looks like
130// Shadow = (Mem >> scale) + (1 << offset_log)
131static cl::opt<int> ClMappingScale("asan-mapping-scale",
132 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
133static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
134 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
135
136// Optimization flags. Not user visible, used mostly for testing
137// and benchmarking the tool.
138static cl::opt<bool> ClOpt("asan-opt",
139 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
140static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
141 cl::desc("Instrument the same temp just once"), cl::Hidden,
142 cl::init(true));
143static cl::opt<bool> ClOptGlobals("asan-opt-globals",
144 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
145
Alexey Samsonovee548272012-11-29 18:14:24 +0000146static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
147 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
148 cl::Hidden, cl::init(false));
149
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000150// Debug flags.
151static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
152 cl::init(0));
153static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
154 cl::Hidden, cl::init(0));
155static cl::opt<std::string> ClDebugFunc("asan-debug-func",
156 cl::Hidden, cl::desc("Debug func"));
157static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
158 cl::Hidden, cl::init(-1));
159static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
160 cl::Hidden, cl::init(-1));
161
162namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000163/// A set of dynamically initialized globals extracted from metadata.
164class SetOfDynamicallyInitializedGlobals {
165 public:
166 void Init(Module& M) {
167 // Clang generates metadata identifying all dynamically initialized globals.
168 NamedMDNode *DynamicGlobals =
169 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
170 if (!DynamicGlobals)
171 return;
172 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
173 MDNode *MDN = DynamicGlobals->getOperand(i);
174 assert(MDN->getNumOperands() == 1);
175 Value *VG = MDN->getOperand(0);
176 // The optimizer may optimize away a global entirely, in which case we
177 // cannot instrument access to it.
178 if (!VG)
179 continue;
180 DynInitGlobals.insert(cast<GlobalVariable>(VG));
181 }
182 }
183 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
184 private:
185 SmallSet<GlobalValue*, 32> DynInitGlobals;
186};
187
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000188/// This struct defines the shadow mapping using the rule:
189/// shadow = (mem >> Scale) + Offset.
190struct ShadowMapping {
191 int Scale;
192 uint64_t Offset;
193};
194
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000195static ShadowMapping getShadowMapping(const Module &M, int LongSize,
196 bool ZeroBaseShadow) {
197 llvm::Triple TargetTriple(M.getTargetTriple());
198 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000199
200 ShadowMapping Mapping;
201
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000202 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000203 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
204 if (ClMappingOffsetLog >= 0) {
205 // Zero offset log is the special case.
206 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
207 }
208
209 Mapping.Scale = kDefaultShadowScale;
210 if (ClMappingScale) {
211 Mapping.Scale = ClMappingScale;
212 }
213
214 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000215}
216
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000217static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000218 // Redzone used for stack and globals is at least 32 bytes.
219 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000220 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000221}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000222
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000223/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000224struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000225 AddressSanitizer(bool CheckInitOrder = false,
226 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000227 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000228 StringRef BlacklistFile = StringRef(),
229 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000230 : FunctionPass(ID),
231 CheckInitOrder(CheckInitOrder || ClInitializers),
232 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000233 CheckLifetime(CheckLifetime || ClCheckLifetime),
234 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000235 : BlacklistFile),
236 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000237 virtual const char *getPassName() const {
238 return "AddressSanitizerFunctionPass";
239 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000240 void instrumentMop(Instruction *I);
241 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000242 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000243 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
244 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000245 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000246 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000247 bool instrumentMemIntrinsic(MemIntrinsic *MI);
248 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000249 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000250 Instruction *InsertBefore, bool IsWrite);
251 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000252 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000253 void createInitializerPoisonCalls(Module &M,
254 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000255 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000256 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000257 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000258 static char ID; // Pass identification, replacement for typeid
259
260 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000261 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000262
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000263 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000264 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000265 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000266
Alexey Samsonovee548272012-11-29 18:14:24 +0000267 bool CheckInitOrder;
268 bool CheckUseAfterReturn;
269 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000270 SmallString<64> BlacklistFile;
271 bool ZeroBaseShadow;
272
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000273 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000274 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000275 int LongSize;
276 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000277 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000278 Function *AsanCtorFunction;
279 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000280 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000281 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000282 // This array is indexed by AccessIsWrite and log2(AccessSize).
283 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000284 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000285 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000286
287 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000288};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000289
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000290class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000291 public:
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000292 AddressSanitizerModule(bool CheckInitOrder = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000293 StringRef BlacklistFile = StringRef(),
294 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000295 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000296 CheckInitOrder(CheckInitOrder || ClInitializers),
297 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000298 : BlacklistFile),
299 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000300 bool runOnModule(Module &M);
301 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000302 virtual const char *getPassName() const {
303 return "AddressSanitizerModule";
304 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000305
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000306 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000307 void initializeCallbacks(Module &M);
308
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000309 bool ShouldInstrumentGlobal(GlobalVariable *G);
310 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
311 Value *LastAddr);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000312 size_t RedzoneSize() const {
313 return RedzoneSizeForScale(Mapping.Scale);
314 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000315
Alexey Samsonovee548272012-11-29 18:14:24 +0000316 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000317 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000318 bool ZeroBaseShadow;
319
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000320 OwningPtr<BlackList> BL;
321 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
322 Type *IntptrTy;
323 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000324 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000325 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000326 Function *AsanPoisonGlobals;
327 Function *AsanUnpoisonGlobals;
328 Function *AsanRegisterGlobals;
329 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000330};
331
Alexey Samsonov59cca132012-12-25 12:04:36 +0000332// Stack poisoning does not play well with exception handling.
333// When an exception is thrown, we essentially bypass the code
334// that unpoisones the stack. This is why the run-time library has
335// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
336// stack in the interceptor. This however does not work inside the
337// actual function which catches the exception. Most likely because the
338// compiler hoists the load of the shadow value somewhere too high.
339// This causes asan to report a non-existing bug on 453.povray.
340// It sounds like an LLVM bug.
341struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
342 Function &F;
343 AddressSanitizer &ASan;
344 DIBuilder DIB;
345 LLVMContext *C;
346 Type *IntptrTy;
347 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000348 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000349
350 SmallVector<AllocaInst*, 16> AllocaVec;
351 SmallVector<Instruction*, 8> RetVec;
352 uint64_t TotalStackSize;
353 unsigned StackAlignment;
354
355 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
356 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
357
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000358 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
359 struct AllocaPoisonCall {
360 IntrinsicInst *InsBefore;
361 uint64_t Size;
362 bool DoPoison;
363 };
364 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
365
366 // Maps Value to an AllocaInst from which the Value is originated.
367 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
368 AllocaForValueMapTy AllocaForValue;
369
Alexey Samsonov59cca132012-12-25 12:04:36 +0000370 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
371 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
372 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000373 Mapping(ASan.Mapping),
374 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000375
376 bool runOnFunction() {
377 if (!ClStack) return false;
378 // Collect alloca, ret, lifetime instructions etc.
379 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
380 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
381 BasicBlock *BB = *DI;
382 visit(*BB);
383 }
384 if (AllocaVec.empty()) return false;
385
386 initializeCallbacks(*F.getParent());
387
388 poisonStack();
389
390 if (ClDebugStack) {
391 DEBUG(dbgs() << F);
392 }
393 return true;
394 }
395
396 // Finds all static Alloca instructions and puts
397 // poisoned red zones around all of them.
398 // Then unpoison everything back before the function returns.
399 void poisonStack();
400
401 // ----------------------- Visitors.
402 /// \brief Collect all Ret instructions.
403 void visitReturnInst(ReturnInst &RI) {
404 RetVec.push_back(&RI);
405 }
406
407 /// \brief Collect Alloca instructions we want (and can) handle.
408 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000409 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000410
411 StackAlignment = std::max(StackAlignment, AI.getAlignment());
412 AllocaVec.push_back(&AI);
413 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
414 TotalStackSize += AlignedSize;
415 }
416
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000417 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
418 /// errors.
419 void visitIntrinsicInst(IntrinsicInst &II) {
420 if (!ASan.CheckLifetime) return;
421 Intrinsic::ID ID = II.getIntrinsicID();
422 if (ID != Intrinsic::lifetime_start &&
423 ID != Intrinsic::lifetime_end)
424 return;
425 // Found lifetime intrinsic, add ASan instrumentation if necessary.
426 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
427 // If size argument is undefined, don't do anything.
428 if (Size->isMinusOne()) return;
429 // Check that size doesn't saturate uint64_t and can
430 // be stored in IntptrTy.
431 const uint64_t SizeValue = Size->getValue().getLimitedValue();
432 if (SizeValue == ~0ULL ||
433 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
434 return;
435 // Find alloca instruction that corresponds to llvm.lifetime argument.
436 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
437 if (!AI) return;
438 bool DoPoison = (ID == Intrinsic::lifetime_end);
439 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
440 AllocaPoisonCallVec.push_back(APC);
441 }
442
Alexey Samsonov59cca132012-12-25 12:04:36 +0000443 // ---------------------- Helpers.
444 void initializeCallbacks(Module &M);
445
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000446 // Check if we want (and can) handle this alloca.
447 bool isInterestingAlloca(AllocaInst &AI) {
448 return (!AI.isArrayAllocation() &&
449 AI.isStaticAlloca() &&
450 AI.getAllocatedType()->isSized());
451 }
452
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000453 size_t RedzoneSize() const {
454 return RedzoneSizeForScale(Mapping.Scale);
455 }
Alexey Samsonov59cca132012-12-25 12:04:36 +0000456 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
457 Type *Ty = AI->getAllocatedType();
458 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
459 return SizeInBytes;
460 }
461 uint64_t getAlignedSize(uint64_t SizeInBytes) {
462 size_t RZ = RedzoneSize();
463 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
464 }
465 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
466 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
467 return getAlignedSize(SizeInBytes);
468 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000469 /// Finds alloca where the value comes from.
470 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000471 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
472 Value *ShadowBase, bool DoPoison);
473 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000474};
475
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000476} // namespace
477
478char AddressSanitizer::ID = 0;
479INITIALIZE_PASS(AddressSanitizer, "asan",
480 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
481 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000482FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000483 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000484 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000485 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000486 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000487}
488
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000489char AddressSanitizerModule::ID = 0;
490INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
491 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
492 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000493ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000494 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
495 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
496 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000497}
498
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000499static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
500 size_t Res = CountTrailingZeros_32(TypeSize / 8);
501 assert(Res < kNumberOfAccessSizes);
502 return Res;
503}
504
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000505// Create a constant for Str so that we can pass it to the run-time lib.
506static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000507 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000508 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000509 GlobalValue::PrivateLinkage, StrConst,
510 kAsanGenPrefix);
511}
512
513static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
514 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000515}
516
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000517Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
518 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000519 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
520 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000521 return Shadow;
522 // (Shadow >> scale) | offset
523 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000524 Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000525}
526
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000527void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000528 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000529 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
530 // Check the first byte.
531 {
532 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000533 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000534 }
535 // Check the last byte.
536 {
537 IRBuilder<> IRB(InsertBefore);
538 Value *SizeMinusOne = IRB.CreateSub(
539 Size, ConstantInt::get(Size->getType(), 1));
540 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
541 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
542 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000543 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000544 }
545}
546
547// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000548bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000549 Value *Dst = MI->getDest();
550 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000551 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000552 Value *Length = MI->getLength();
553
554 Constant *ConstLength = dyn_cast<Constant>(Length);
555 Instruction *InsertBefore = MI;
556 if (ConstLength) {
557 if (ConstLength->isNullValue()) return false;
558 } else {
559 // The size is not a constant so it could be zero -- check at run-time.
560 IRBuilder<> IRB(InsertBefore);
561
562 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000563 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000564 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000565 }
566
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000567 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000568 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000569 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000570 return true;
571}
572
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000573// If I is an interesting memory access, return the PointerOperand
574// and set IsWrite. Otherwise return NULL.
575static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000576 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000577 if (!ClInstrumentReads) return NULL;
578 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000579 return LI->getPointerOperand();
580 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000581 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
582 if (!ClInstrumentWrites) return NULL;
583 *IsWrite = true;
584 return SI->getPointerOperand();
585 }
586 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
587 if (!ClInstrumentAtomics) return NULL;
588 *IsWrite = true;
589 return RMW->getPointerOperand();
590 }
591 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
592 if (!ClInstrumentAtomics) return NULL;
593 *IsWrite = true;
594 return XCHG->getPointerOperand();
595 }
596 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000597}
598
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000599void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000600 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000601 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
602 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000603 if (ClOpt && ClOptGlobals) {
604 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
605 // If initialization order checking is disabled, a simple access to a
606 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000607 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000608 return;
609 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000610 // have to instrument it. However, if a global does not have initailizer
611 // at all, we assume it has dynamic initializer (in other TU).
612 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000613 return;
614 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000615 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000616
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000617 Type *OrigPtrTy = Addr->getType();
618 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
619
620 assert(OrigTy->isSized());
621 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
622
623 if (TypeSize != 8 && TypeSize != 16 &&
624 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
625 // Ignore all unusual sizes.
626 return;
627 }
628
629 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000630 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000631}
632
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000633// Validate the result of Module::getOrInsertFunction called for an interface
634// function of AddressSanitizer. If the instrumented module defines a function
635// with the same name, their prototypes must match, otherwise
636// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000637static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000638 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
639 FuncOrBitcast->dump();
640 report_fatal_error("trying to redefine an AddressSanitizer "
641 "interface function");
642}
643
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000644Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000645 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000646 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000647 IRBuilder<> IRB(InsertBefore);
648 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
649 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000650 // We don't do Call->setDoesNotReturn() because the BB already has
651 // UnreachableInst at the end.
652 // This EmptyAsm is required to avoid callback merge.
653 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000654 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000655}
656
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000657Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000658 Value *ShadowValue,
659 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000660 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000661 // Addr & (Granularity - 1)
662 Value *LastAccessedByte = IRB.CreateAnd(
663 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
664 // (Addr & (Granularity - 1)) + size - 1
665 if (TypeSize / 8 > 1)
666 LastAccessedByte = IRB.CreateAdd(
667 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
668 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
669 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000670 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000671 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
672 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
673}
674
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000675void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000676 IRBuilder<> &IRB, Value *Addr,
677 uint32_t TypeSize, bool IsWrite) {
678 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
679
680 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000681 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000682 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
683 Value *ShadowPtr = memToShadow(AddrLong, IRB);
684 Value *CmpVal = Constant::getNullValue(ShadowTy);
685 Value *ShadowValue = IRB.CreateLoad(
686 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
687
688 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000689 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000690 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000691 TerminatorInst *CrashTerm = 0;
692
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000693 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000694 TerminatorInst *CheckTerm =
695 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000696 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000697 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000698 IRB.SetInsertPoint(CheckTerm);
699 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000700 BasicBlock *CrashBlock =
701 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000702 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000703 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
704 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000705 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000706 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000707 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000708
709 Instruction *Crash =
710 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
711 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000712}
713
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000714void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000715 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000716 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
717 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
718 // If that function is not present, this TU contains no globals, or they have
719 // all been optimized away
720 if (!GlobalInit)
721 return;
722
723 // Set up the arguments to our poison/unpoison functions.
724 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
725
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000726 // Add a call to poison all external globals before the given function starts.
727 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
728
729 // Add calls to unpoison all globals before each return instruction.
730 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
731 I != E; ++I) {
732 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
733 CallInst::Create(AsanUnpoisonGlobals, "", RI);
734 }
735 }
736}
737
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000738bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000739 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000740 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000741
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000742 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000743 if (!Ty->isSized()) return false;
744 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000745 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000746 // Touch only those globals that will not be defined in other modules.
747 // Don't handle ODR type linkages since other modules may be built w/o asan.
748 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
749 G->getLinkage() != GlobalVariable::PrivateLinkage &&
750 G->getLinkage() != GlobalVariable::InternalLinkage)
751 return false;
752 // Two problems with thread-locals:
753 // - The address of the main thread's copy can't be computed at link-time.
754 // - Need to poison all copies, not just the main thread's one.
755 if (G->isThreadLocal())
756 return false;
757 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000758 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000759
760 // Ignore all the globals with the names starting with "\01L_OBJC_".
761 // Many of those are put into the .cstring section. The linker compresses
762 // that section by removing the spare \0s after the string terminator, so
763 // our redzones get broken.
764 if ((G->getName().find("\01L_OBJC_") == 0) ||
765 (G->getName().find("\01l_OBJC_") == 0)) {
766 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
767 return false;
768 }
769
770 if (G->hasSection()) {
771 StringRef Section(G->getSection());
772 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
773 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
774 // them.
775 if ((Section.find("__OBJC,") == 0) ||
776 (Section.find("__DATA, __objc_") == 0)) {
777 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
778 return false;
779 }
780 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
781 // Constant CFString instances are compiled in the following way:
782 // -- the string buffer is emitted into
783 // __TEXT,__cstring,cstring_literals
784 // -- the constant NSConstantString structure referencing that buffer
785 // is placed into __DATA,__cfstring
786 // Therefore there's no point in placing redzones into __DATA,__cfstring.
787 // Moreover, it causes the linker to crash on OS X 10.7
788 if (Section.find("__DATA,__cfstring") == 0) {
789 DEBUG(dbgs() << "Ignoring CFString: " << *G);
790 return false;
791 }
792 }
793
794 return true;
795}
796
Alexey Samsonov46848582012-12-25 12:28:20 +0000797void AddressSanitizerModule::initializeCallbacks(Module &M) {
798 IRBuilder<> IRB(*C);
799 // Declare our poisoning and unpoisoning functions.
800 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
801 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
802 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
803 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
804 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
805 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
806 // Declare functions that register/unregister globals.
807 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
808 kAsanRegisterGlobalsName, IRB.getVoidTy(),
809 IntptrTy, IntptrTy, NULL));
810 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
811 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
812 kAsanUnregisterGlobalsName,
813 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
814 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
815}
816
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000817// This function replaces all global variables with new variables that have
818// trailing redzones. It also creates a function that poisons
819// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000820bool AddressSanitizerModule::runOnModule(Module &M) {
821 if (!ClGlobals) return false;
822 TD = getAnalysisIfAvailable<DataLayout>();
823 if (!TD)
824 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000825 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000826 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000827 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000828 int LongSize = TD->getPointerSizeInBits();
829 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000830 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000831 initializeCallbacks(M);
832 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000833
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000834 SmallVector<GlobalVariable *, 16> GlobalsToChange;
835
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000836 for (Module::GlobalListType::iterator G = M.global_begin(),
837 E = M.global_end(); G != E; ++G) {
838 if (ShouldInstrumentGlobal(G))
839 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000840 }
841
842 size_t n = GlobalsToChange.size();
843 if (n == 0) return false;
844
845 // A global is described by a structure
846 // size_t beg;
847 // size_t size;
848 // size_t size_with_redzone;
849 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000850 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000851 // We initialize an array of such structures and pass it to a run-time call.
852 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000853 IntptrTy, IntptrTy,
854 IntptrTy, NULL);
855 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000856
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000857
858 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
859 assert(CtorFunc);
860 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000861
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000862 // The addresses of the first and last dynamically initialized globals in
863 // this TU. Used in initialization order checking.
864 Value *FirstDynamic = 0, *LastDynamic = 0;
865
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000866 for (size_t i = 0; i < n; i++) {
867 GlobalVariable *G = GlobalsToChange[i];
868 PointerType *PtrTy = cast<PointerType>(G->getType());
869 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000870 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000871 size_t RZ = RedzoneSize();
872 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000873 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000874 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000875 bool GlobalHasDynamicInitializer =
876 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000877 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000878 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000879
880 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
881 Constant *NewInitializer = ConstantStruct::get(
882 NewTy, G->getInitializer(),
883 Constant::getNullValue(RightRedZoneTy), NULL);
884
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000885 SmallString<2048> DescriptionOfGlobal = G->getName();
886 DescriptionOfGlobal += " (";
887 DescriptionOfGlobal += M.getModuleIdentifier();
888 DescriptionOfGlobal += ")";
889 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000890
891 // Create a new global variable with enough space for a redzone.
892 GlobalVariable *NewGlobal = new GlobalVariable(
893 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000894 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000895 NewGlobal->copyAttributesFrom(G);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000896 NewGlobal->setAlignment(RZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000897
898 Value *Indices2[2];
899 Indices2[0] = IRB.getInt32(0);
900 Indices2[1] = IRB.getInt32(0);
901
902 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000903 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000904 NewGlobal->takeName(G);
905 G->eraseFromParent();
906
907 Initializers[i] = ConstantStruct::get(
908 GlobalStructTy,
909 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
910 ConstantInt::get(IntptrTy, SizeInBytes),
911 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
912 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000913 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000914 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000915
916 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000917 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000918 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
919 if (FirstDynamic == 0)
920 FirstDynamic = LastDynamic;
921 }
922
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000923 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000924 }
925
926 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
927 GlobalVariable *AllGlobals = new GlobalVariable(
928 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
929 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
930
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000931 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000932 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000933 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000934 IRB.CreateCall2(AsanRegisterGlobals,
935 IRB.CreatePointerCast(AllGlobals, IntptrTy),
936 ConstantInt::get(IntptrTy, n));
937
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000938 // We also need to unregister globals at the end, e.g. when a shared library
939 // gets closed.
940 Function *AsanDtorFunction = Function::Create(
941 FunctionType::get(Type::getVoidTy(*C), false),
942 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
943 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
944 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000945 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
946 IRB.CreatePointerCast(AllGlobals, IntptrTy),
947 ConstantInt::get(IntptrTy, n));
948 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
949
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000950 DEBUG(dbgs() << M);
951 return true;
952}
953
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000954void AddressSanitizer::initializeCallbacks(Module &M) {
955 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000956 // Create __asan_report* callbacks.
957 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
958 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
959 AccessSizeIndex++) {
960 // IsWrite and TypeSize are encoded in the function name.
961 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
962 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000963 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000964 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
965 checkInterfaceFunction(M.getOrInsertFunction(
966 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000967 }
968 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000969
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000970 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
971 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000972 // We insert an empty inline asm after __asan_report* to avoid callback merge.
973 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
974 StringRef(""), StringRef(""),
975 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000976}
977
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000978void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000979 // Tell the values of mapping offset and scale to the run-time.
980 GlobalValue *asan_mapping_offset =
981 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
982 ConstantInt::get(IntptrTy, Mapping.Offset),
983 kAsanMappingOffsetName);
984 // Read the global, otherwise it may be optimized away.
985 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000986
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000987 GlobalValue *asan_mapping_scale =
988 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
989 ConstantInt::get(IntptrTy, Mapping.Scale),
990 kAsanMappingScaleName);
991 // Read the global, otherwise it may be optimized away.
992 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000993}
994
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000995// virtual
996bool AddressSanitizer::doInitialization(Module &M) {
997 // Initialize the private fields. No one has accessed them before.
998 TD = getAnalysisIfAvailable<DataLayout>();
999
1000 if (!TD)
1001 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +00001002 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001003 DynamicallyInitializedGlobals.Init(M);
1004
1005 C = &(M.getContext());
1006 LongSize = TD->getPointerSizeInBits();
1007 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001008
1009 AsanCtorFunction = Function::Create(
1010 FunctionType::get(Type::getVoidTy(*C), false),
1011 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1012 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1013 // call __asan_init in the module ctor.
1014 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1015 AsanInitFunction = checkInterfaceFunction(
1016 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1017 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1018 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001019
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001020 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001021 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001022
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001023 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001024 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001025}
1026
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001027bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1028 // For each NSObject descendant having a +load method, this method is invoked
1029 // by the ObjC runtime before any of the static constructors is called.
1030 // Therefore we need to instrument such methods with a call to __asan_init
1031 // at the beginning in order to initialize our runtime before any access to
1032 // the shadow memory.
1033 // We cannot just ignore these methods, because they may call other
1034 // instrumented functions.
1035 if (F.getName().find(" load]") != std::string::npos) {
1036 IRBuilder<> IRB(F.begin()->begin());
1037 IRB.CreateCall(AsanInitFunction);
1038 return true;
1039 }
1040 return false;
1041}
1042
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001043bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001044 if (BL->isIn(F)) return false;
1045 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001046 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001047 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001048
1049 // If needed, insert __asan_init before checking for AddressSafety attr.
1050 maybeInsertAsanInitAtFunctionEntry(F);
1051
Bill Wendling831737d2012-12-30 10:32:01 +00001052 if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1053 Attribute::AddressSafety))
Bill Wendling67658342012-10-09 07:45:08 +00001054 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001055
1056 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1057 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001058
1059 // We want to instrument every address only once per basic block (unless there
1060 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001061 SmallSet<Value*, 16> TempsToInstrument;
1062 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001063 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001064 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001065
1066 // Fill the set of memory operations to instrument.
1067 for (Function::iterator FI = F.begin(), FE = F.end();
1068 FI != FE; ++FI) {
1069 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001070 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001071 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1072 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001073 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001074 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001075 if (ClOpt && ClOptSameTemp) {
1076 if (!TempsToInstrument.insert(Addr))
1077 continue; // We've seen this temp in the current BB.
1078 }
1079 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1080 // ok, take it.
1081 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001082 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001083 // A call inside BB.
1084 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +00001085 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001086 NoReturnCalls.push_back(CI);
1087 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001088 }
1089 continue;
1090 }
1091 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001092 NumInsnsPerBB++;
1093 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1094 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001095 }
1096 }
1097
1098 // Instrument.
1099 int NumInstrumented = 0;
1100 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1101 Instruction *Inst = ToInstrument[i];
1102 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1103 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001104 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001105 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001106 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001107 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001108 }
1109 NumInstrumented++;
1110 }
1111
Alexey Samsonov59cca132012-12-25 12:04:36 +00001112 FunctionStackPoisoner FSP(F, *this);
1113 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001114
1115 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1116 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1117 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1118 Instruction *CI = NoReturnCalls[i];
1119 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001120 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001121 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001122 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001123
1124 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001125}
1126
1127static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1128 if (ShadowRedzoneSize == 1) return PoisonByte;
1129 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1130 if (ShadowRedzoneSize == 4)
1131 return (PoisonByte << 24) + (PoisonByte << 16) +
1132 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001133 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001134}
1135
1136static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1137 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001138 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001139 size_t ShadowGranularity,
1140 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001141 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001142 i+= ShadowGranularity, Shadow++) {
1143 if (i + ShadowGranularity <= Size) {
1144 *Shadow = 0; // fully addressable
1145 } else if (i >= Size) {
1146 *Shadow = Magic; // unaddressable
1147 } else {
1148 *Shadow = Size - i; // first Size-i bytes are addressable
1149 }
1150 }
1151}
1152
Alexey Samsonov59cca132012-12-25 12:04:36 +00001153// Workaround for bug 11395: we don't want to instrument stack in functions
1154// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1155// FIXME: remove once the bug 11395 is fixed.
1156bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1157 if (LongSize != 32) return false;
1158 CallInst *CI = dyn_cast<CallInst>(I);
1159 if (!CI || !CI->isInlineAsm()) return false;
1160 if (CI->getNumArgOperands() <= 5) return false;
1161 // We have inline assembly with quite a few arguments.
1162 return true;
1163}
1164
1165void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1166 IRBuilder<> IRB(*C);
1167 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1168 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1169 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1170 kAsanStackFreeName, IRB.getVoidTy(),
1171 IntptrTy, IntptrTy, IntptrTy, NULL));
1172 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1173 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1174 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1175 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1176}
1177
1178void FunctionStackPoisoner::poisonRedZones(
1179 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1180 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001181 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001182 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1183 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1184 Type *RZPtrTy = PointerType::get(RZTy, 0);
1185
1186 Value *PoisonLeft = ConstantInt::get(RZTy,
1187 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1188 Value *PoisonMid = ConstantInt::get(RZTy,
1189 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1190 Value *PoisonRight = ConstantInt::get(RZTy,
1191 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1192
1193 // poison the first red zone.
1194 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1195
1196 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001197 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001198 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1199 AllocaInst *AI = AllocaVec[i];
1200 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1201 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001202 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001203 Value *Ptr = NULL;
1204
1205 Pos += AlignedSize;
1206
1207 assert(ShadowBase->getType() == IntptrTy);
1208 if (SizeInBytes < AlignedSize) {
1209 // Poison the partial redzone at right
1210 Ptr = IRB.CreateAdd(
1211 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001212 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001213 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001214 uint32_t Poison = 0;
1215 if (DoPoison) {
1216 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001217 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001218 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001219 kAsanStackPartialRedzoneMagic);
1220 }
1221 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1222 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1223 }
1224
1225 // Poison the full redzone at right.
1226 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001227 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001228 bool LastAlloca = (i == AllocaVec.size() - 1);
1229 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001230 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1231
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001232 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001233 }
1234}
1235
Alexey Samsonov59cca132012-12-25 12:04:36 +00001236void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001237 uint64_t LocalStackSize = TotalStackSize +
1238 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001239
Alexey Samsonov59cca132012-12-25 12:04:36 +00001240 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001241 && LocalStackSize <= kMaxStackMallocSize;
1242
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001243 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001244 Instruction *InsBefore = AllocaVec[0];
1245 IRBuilder<> IRB(InsBefore);
1246
1247
1248 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1249 AllocaInst *MyAlloca =
1250 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001251 if (ClRealignStack && StackAlignment < RedzoneSize())
1252 StackAlignment = RedzoneSize();
1253 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001254 assert(MyAlloca->isStaticAlloca());
1255 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1256 Value *LocalStackBase = OrigStackBase;
1257
1258 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001259 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1260 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1261 }
1262
1263 // This string will be parsed by the run-time (DescribeStackAddress).
1264 SmallString<2048> StackDescriptionStorage;
1265 raw_svector_ostream StackDescription(StackDescriptionStorage);
1266 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1267
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001268 // Insert poison calls for lifetime intrinsics for alloca.
1269 bool HavePoisonedAllocas = false;
1270 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1271 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1272 IntrinsicInst *II = APC.InsBefore;
1273 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1274 assert(AI);
1275 IRBuilder<> IRB(II);
1276 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1277 HavePoisonedAllocas |= APC.DoPoison;
1278 }
1279
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001280 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001281 // Replace Alloca instructions with base+offset.
1282 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1283 AllocaInst *AI = AllocaVec[i];
1284 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1285 StringRef Name = AI->getName();
1286 StackDescription << Pos << " " << SizeInBytes << " "
1287 << Name.size() << " " << Name << " ";
1288 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001289 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001290 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001291 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001292 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001293 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001294 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001295 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001296 }
1297 assert(Pos == LocalStackSize);
1298
1299 // Write the Magic value and the frame description constant to the redzone.
1300 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1301 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1302 BasePlus0);
1303 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001304 ConstantInt::get(IntptrTy,
1305 ASan.LongSize/8));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001306 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001307 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001308 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001309 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1310 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001311 IRB.CreateStore(Description, BasePlus1);
1312
1313 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001314 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1315 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001316
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001317 // Unpoison the stack before all ret instructions.
1318 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1319 Instruction *Ret = RetVec[i];
1320 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001321 // Mark the current frame as retired.
1322 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1323 BasePlus0);
1324 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001325 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001326 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001327 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001328 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1329 ConstantInt::get(IntptrTy, LocalStackSize),
1330 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001331 } else if (HavePoisonedAllocas) {
1332 // If we poisoned some allocas in llvm.lifetime analysis,
1333 // unpoison whole stack frame now.
1334 assert(LocalStackBase == OrigStackBase);
1335 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001336 }
1337 }
1338
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001339 // We are done. Remove the old unused alloca instructions.
1340 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1341 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001342}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001343
Alexey Samsonov59cca132012-12-25 12:04:36 +00001344void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1345 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001346 // For now just insert the call to ASan runtime.
1347 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1348 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1349 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1350 : AsanUnpoisonStackMemoryFunc,
1351 AddrArg, SizeArg);
1352}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001353
1354// Handling llvm.lifetime intrinsics for a given %alloca:
1355// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1356// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1357// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1358// could be poisoned by previous llvm.lifetime.end instruction, as the
1359// variable may go in and out of scope several times, e.g. in loops).
1360// (3) if we poisoned at least one %alloca in a function,
1361// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001362
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001363AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1364 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1365 // We're intested only in allocas we can handle.
1366 return isInterestingAlloca(*AI) ? AI : 0;
1367 // See if we've already calculated (or started to calculate) alloca for a
1368 // given value.
1369 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1370 if (I != AllocaForValue.end())
1371 return I->second;
1372 // Store 0 while we're calculating alloca for value V to avoid
1373 // infinite recursion if the value references itself.
1374 AllocaForValue[V] = 0;
1375 AllocaInst *Res = 0;
1376 if (CastInst *CI = dyn_cast<CastInst>(V))
1377 Res = findAllocaForValue(CI->getOperand(0));
1378 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1379 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1380 Value *IncValue = PN->getIncomingValue(i);
1381 // Allow self-referencing phi-nodes.
1382 if (IncValue == PN) continue;
1383 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1384 // AI for incoming values should exist and should all be equal.
1385 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1386 return 0;
1387 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001388 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001389 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001390 if (Res != 0)
1391 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001392 return Res;
1393}