Replace Count{Leading,Trailing}Zeros_{32,64} with count{Leading,Trailing}Zeros.
[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 #define DEBUG_TYPE "asan"
17
18 #include "llvm/Transforms/Instrumentation.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #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"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/DIBuilder.h"
29 #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"
37 #include "llvm/InstVisitor.h"
38 #include "llvm/Support/CallSite.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/DataTypes.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Support/system_error.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/BlackList.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/ModuleUtils.h"
48 #include <algorithm>
49 #include <string>
50
51 using namespace llvm;
52
53 static const uint64_t kDefaultShadowScale = 3;
54 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
55 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
56 static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000;  // < 2G.
57 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
58
59 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
60 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
61 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
62
63 static const char *kAsanModuleCtorName = "asan.module_ctor";
64 static const char *kAsanModuleDtorName = "asan.module_dtor";
65 static const int   kAsanCtorAndCtorPriority = 1;
66 static const char *kAsanReportErrorTemplate = "__asan_report_";
67 static const char *kAsanReportLoadN = "__asan_report_load_n";
68 static const char *kAsanReportStoreN = "__asan_report_store_n";
69 static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
70 static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
71 static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
72 static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
73 static const char *kAsanInitName = "__asan_init_v3";
74 static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
75 static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
76 static const char *kAsanMappingScaleName = "__asan_mapping_scale";
77 static const char *kAsanStackMallocName = "__asan_stack_malloc";
78 static const char *kAsanStackFreeName = "__asan_stack_free";
79 static const char *kAsanGenPrefix = "__asan_gen_";
80 static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
81 static const char *kAsanUnpoisonStackMemoryName =
82     "__asan_unpoison_stack_memory";
83
84 static const int kAsanStackLeftRedzoneMagic = 0xf1;
85 static const int kAsanStackMidRedzoneMagic = 0xf2;
86 static const int kAsanStackRightRedzoneMagic = 0xf3;
87 static const int kAsanStackPartialRedzoneMagic = 0xf4;
88
89 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
90 static const size_t kNumberOfAccessSizes = 5;
91
92 // Command-line flags.
93
94 // This flag may need to be replaced with -f[no-]asan-reads.
95 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
96        cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
97 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
98        cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
99 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
100        cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
101        cl::Hidden, cl::init(true));
102 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
103        cl::desc("use instrumentation with slow path for all accesses"),
104        cl::Hidden, cl::init(false));
105 // This flag limits the number of instructions to be instrumented
106 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
107 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
108 // set it to 10000.
109 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
110        cl::init(10000),
111        cl::desc("maximal number of instructions to instrument in any given BB"),
112        cl::Hidden);
113 // This flag may need to be replaced with -f[no]asan-stack.
114 static cl::opt<bool> ClStack("asan-stack",
115        cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
116 // This flag may need to be replaced with -f[no]asan-use-after-return.
117 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
118        cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
119 // This flag may need to be replaced with -f[no]asan-globals.
120 static cl::opt<bool> ClGlobals("asan-globals",
121        cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
122 static cl::opt<bool> ClInitializers("asan-initialization-order",
123        cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
124 static cl::opt<bool> ClMemIntrin("asan-memintrin",
125        cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
126 static cl::opt<bool> ClRealignStack("asan-realign-stack",
127        cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
128 static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
129        cl::desc("File containing the list of objects to ignore "
130                 "during instrumentation"), cl::Hidden);
131
132 // These flags allow to change the shadow mapping.
133 // The shadow mapping looks like
134 //    Shadow = (Mem >> scale) + (1 << offset_log)
135 static cl::opt<int> ClMappingScale("asan-mapping-scale",
136        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
137 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
138        cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
139 static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
140        cl::desc("Use short immediate constant as the mapping offset for 64bit"),
141        cl::Hidden, cl::init(true));
142
143 // Optimization flags. Not user visible, used mostly for testing
144 // and benchmarking the tool.
145 static cl::opt<bool> ClOpt("asan-opt",
146        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
147 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
148        cl::desc("Instrument the same temp just once"), cl::Hidden,
149        cl::init(true));
150 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
151        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
152
153 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
154        cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
155        cl::Hidden, cl::init(false));
156
157 // Debug flags.
158 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
159                             cl::init(0));
160 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
161                                  cl::Hidden, cl::init(0));
162 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
163                                         cl::Hidden, cl::desc("Debug func"));
164 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
165                                cl::Hidden, cl::init(-1));
166 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
167                                cl::Hidden, cl::init(-1));
168
169 namespace {
170 /// A set of dynamically initialized globals extracted from metadata.
171 class SetOfDynamicallyInitializedGlobals {
172  public:
173   void Init(Module& M) {
174     // Clang generates metadata identifying all dynamically initialized globals.
175     NamedMDNode *DynamicGlobals =
176         M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
177     if (!DynamicGlobals)
178       return;
179     for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
180       MDNode *MDN = DynamicGlobals->getOperand(i);
181       assert(MDN->getNumOperands() == 1);
182       Value *VG = MDN->getOperand(0);
183       // The optimizer may optimize away a global entirely, in which case we
184       // cannot instrument access to it.
185       if (!VG)
186         continue;
187       DynInitGlobals.insert(cast<GlobalVariable>(VG));
188     }
189   }
190   bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
191  private:
192   SmallSet<GlobalValue*, 32> DynInitGlobals;
193 };
194
195 /// This struct defines the shadow mapping using the rule:
196 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
197 struct ShadowMapping {
198   int Scale;
199   uint64_t Offset;
200   bool OrShadowOffset;
201 };
202
203 static ShadowMapping getShadowMapping(const Module &M, int LongSize,
204                                       bool ZeroBaseShadow) {
205   llvm::Triple TargetTriple(M.getTargetTriple());
206   bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
207   bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
208   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64;
209   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
210
211   ShadowMapping Mapping;
212
213   // OR-ing shadow offset if more efficient (at least on x86),
214   // but on ppc64 we have to use add since the shadow offset is not neccesary
215   // 1/8-th of the address space.
216   Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
217
218   Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
219       (LongSize == 32 ? kDefaultShadowOffset32 :
220        IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
221   if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
222     assert(LongSize == 64);
223     Mapping.Offset = kDefaultShort64bitShadowOffset;
224   }
225   if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
226     // Zero offset log is the special case.
227     Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
228   }
229
230   Mapping.Scale = kDefaultShadowScale;
231   if (ClMappingScale) {
232     Mapping.Scale = ClMappingScale;
233   }
234
235   return Mapping;
236 }
237
238 static size_t RedzoneSizeForScale(int MappingScale) {
239   // Redzone used for stack and globals is at least 32 bytes.
240   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
241   return std::max(32U, 1U << MappingScale);
242 }
243
244 /// AddressSanitizer: instrument the code in module to find memory bugs.
245 struct AddressSanitizer : public FunctionPass {
246   AddressSanitizer(bool CheckInitOrder = true,
247                    bool CheckUseAfterReturn = false,
248                    bool CheckLifetime = false,
249                    StringRef BlacklistFile = StringRef(),
250                    bool ZeroBaseShadow = false)
251       : FunctionPass(ID),
252         CheckInitOrder(CheckInitOrder || ClInitializers),
253         CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
254         CheckLifetime(CheckLifetime || ClCheckLifetime),
255         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
256                                             : BlacklistFile),
257         ZeroBaseShadow(ZeroBaseShadow) {}
258   virtual const char *getPassName() const {
259     return "AddressSanitizerFunctionPass";
260   }
261   void instrumentMop(Instruction *I);
262   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
263                          Value *Addr, uint32_t TypeSize, bool IsWrite,
264                          Value *SizeArgument);
265   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
266                            Value *ShadowValue, uint32_t TypeSize);
267   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
268                                  bool IsWrite, size_t AccessSizeIndex,
269                                  Value *SizeArgument);
270   bool instrumentMemIntrinsic(MemIntrinsic *MI);
271   void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
272                                    Value *Size,
273                                    Instruction *InsertBefore, bool IsWrite);
274   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
275   bool runOnFunction(Function &F);
276   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
277   void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
278   virtual bool doInitialization(Module &M);
279   static char ID;  // Pass identification, replacement for typeid
280
281  private:
282   void initializeCallbacks(Module &M);
283
284   bool ShouldInstrumentGlobal(GlobalVariable *G);
285   bool LooksLikeCodeInBug11395(Instruction *I);
286   void FindDynamicInitializers(Module &M);
287
288   bool CheckInitOrder;
289   bool CheckUseAfterReturn;
290   bool CheckLifetime;
291   SmallString<64> BlacklistFile;
292   bool ZeroBaseShadow;
293
294   LLVMContext *C;
295   DataLayout *TD;
296   int LongSize;
297   Type *IntptrTy;
298   ShadowMapping Mapping;
299   Function *AsanCtorFunction;
300   Function *AsanInitFunction;
301   Function *AsanHandleNoReturnFunc;
302   OwningPtr<BlackList> BL;
303   // This array is indexed by AccessIsWrite and log2(AccessSize).
304   Function *AsanErrorCallback[2][kNumberOfAccessSizes];
305   // This array is indexed by AccessIsWrite.
306   Function *AsanErrorCallbackSized[2];
307   InlineAsm *EmptyAsm;
308   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
309
310   friend struct FunctionStackPoisoner;
311 };
312
313 class AddressSanitizerModule : public ModulePass {
314  public:
315   AddressSanitizerModule(bool CheckInitOrder = true,
316                          StringRef BlacklistFile = StringRef(),
317                          bool ZeroBaseShadow = false)
318       : ModulePass(ID),
319         CheckInitOrder(CheckInitOrder || ClInitializers),
320         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
321                                             : BlacklistFile),
322         ZeroBaseShadow(ZeroBaseShadow) {}
323   bool runOnModule(Module &M);
324   static char ID;  // Pass identification, replacement for typeid
325   virtual const char *getPassName() const {
326     return "AddressSanitizerModule";
327   }
328
329  private:
330   void initializeCallbacks(Module &M);
331
332   bool ShouldInstrumentGlobal(GlobalVariable *G);
333   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
334   size_t RedzoneSize() const {
335     return RedzoneSizeForScale(Mapping.Scale);
336   }
337
338   bool CheckInitOrder;
339   SmallString<64> BlacklistFile;
340   bool ZeroBaseShadow;
341
342   OwningPtr<BlackList> BL;
343   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
344   Type *IntptrTy;
345   LLVMContext *C;
346   DataLayout *TD;
347   ShadowMapping Mapping;
348   Function *AsanPoisonGlobals;
349   Function *AsanUnpoisonGlobals;
350   Function *AsanRegisterGlobals;
351   Function *AsanUnregisterGlobals;
352 };
353
354 // Stack poisoning does not play well with exception handling.
355 // When an exception is thrown, we essentially bypass the code
356 // that unpoisones the stack. This is why the run-time library has
357 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
358 // stack in the interceptor. This however does not work inside the
359 // actual function which catches the exception. Most likely because the
360 // compiler hoists the load of the shadow value somewhere too high.
361 // This causes asan to report a non-existing bug on 453.povray.
362 // It sounds like an LLVM bug.
363 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
364   Function &F;
365   AddressSanitizer &ASan;
366   DIBuilder DIB;
367   LLVMContext *C;
368   Type *IntptrTy;
369   Type *IntptrPtrTy;
370   ShadowMapping Mapping;
371
372   SmallVector<AllocaInst*, 16> AllocaVec;
373   SmallVector<Instruction*, 8> RetVec;
374   uint64_t TotalStackSize;
375   unsigned StackAlignment;
376
377   Function *AsanStackMallocFunc, *AsanStackFreeFunc;
378   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
379
380   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
381   struct AllocaPoisonCall {
382     IntrinsicInst *InsBefore;
383     uint64_t Size;
384     bool DoPoison;
385   };
386   SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
387
388   // Maps Value to an AllocaInst from which the Value is originated.
389   typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
390   AllocaForValueMapTy AllocaForValue;
391
392   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
393       : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
394         IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
395         Mapping(ASan.Mapping),
396         TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
397
398   bool runOnFunction() {
399     if (!ClStack) return false;
400     // Collect alloca, ret, lifetime instructions etc.
401     for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
402          DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
403       BasicBlock *BB = *DI;
404       visit(*BB);
405     }
406     if (AllocaVec.empty()) return false;
407
408     initializeCallbacks(*F.getParent());
409
410     poisonStack();
411
412     if (ClDebugStack) {
413       DEBUG(dbgs() << F);
414     }
415     return true;
416   }
417
418   // Finds all static Alloca instructions and puts
419   // poisoned red zones around all of them.
420   // Then unpoison everything back before the function returns.
421   void poisonStack();
422
423   // ----------------------- Visitors.
424   /// \brief Collect all Ret instructions.
425   void visitReturnInst(ReturnInst &RI) {
426     RetVec.push_back(&RI);
427   }
428
429   /// \brief Collect Alloca instructions we want (and can) handle.
430   void visitAllocaInst(AllocaInst &AI) {
431     if (!isInterestingAlloca(AI)) return;
432
433     StackAlignment = std::max(StackAlignment, AI.getAlignment());
434     AllocaVec.push_back(&AI);
435     uint64_t AlignedSize =  getAlignedAllocaSize(&AI);
436     TotalStackSize += AlignedSize;
437   }
438
439   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
440   /// errors.
441   void visitIntrinsicInst(IntrinsicInst &II) {
442     if (!ASan.CheckLifetime) return;
443     Intrinsic::ID ID = II.getIntrinsicID();
444     if (ID != Intrinsic::lifetime_start &&
445         ID != Intrinsic::lifetime_end)
446       return;
447     // Found lifetime intrinsic, add ASan instrumentation if necessary.
448     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
449     // If size argument is undefined, don't do anything.
450     if (Size->isMinusOne()) return;
451     // Check that size doesn't saturate uint64_t and can
452     // be stored in IntptrTy.
453     const uint64_t SizeValue = Size->getValue().getLimitedValue();
454     if (SizeValue == ~0ULL ||
455         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
456       return;
457     // Find alloca instruction that corresponds to llvm.lifetime argument.
458     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
459     if (!AI) return;
460     bool DoPoison = (ID == Intrinsic::lifetime_end);
461     AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
462     AllocaPoisonCallVec.push_back(APC);
463   }
464
465   // ---------------------- Helpers.
466   void initializeCallbacks(Module &M);
467
468   // Check if we want (and can) handle this alloca.
469   bool isInterestingAlloca(AllocaInst &AI) {
470     return (!AI.isArrayAllocation() &&
471             AI.isStaticAlloca() &&
472             AI.getAllocatedType()->isSized());
473   }
474
475   size_t RedzoneSize() const {
476     return RedzoneSizeForScale(Mapping.Scale);
477   }
478   uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
479     Type *Ty = AI->getAllocatedType();
480     uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
481     return SizeInBytes;
482   }
483   uint64_t getAlignedSize(uint64_t SizeInBytes) {
484     size_t RZ = RedzoneSize();
485     return ((SizeInBytes + RZ - 1) / RZ) * RZ;
486   }
487   uint64_t getAlignedAllocaSize(AllocaInst *AI) {
488     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
489     return getAlignedSize(SizeInBytes);
490   }
491   /// Finds alloca where the value comes from.
492   AllocaInst *findAllocaForValue(Value *V);
493   void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
494                       Value *ShadowBase, bool DoPoison);
495   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
496 };
497
498 }  // namespace
499
500 char AddressSanitizer::ID = 0;
501 INITIALIZE_PASS(AddressSanitizer, "asan",
502     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
503     false, false)
504 FunctionPass *llvm::createAddressSanitizerFunctionPass(
505     bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
506     StringRef BlacklistFile, bool ZeroBaseShadow) {
507   return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
508                               CheckLifetime, BlacklistFile, ZeroBaseShadow);
509 }
510
511 char AddressSanitizerModule::ID = 0;
512 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
513     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
514     "ModulePass", false, false)
515 ModulePass *llvm::createAddressSanitizerModulePass(
516     bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
517   return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
518                                     ZeroBaseShadow);
519 }
520
521 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
522   size_t Res = countTrailingZeros(TypeSize / 8);
523   assert(Res < kNumberOfAccessSizes);
524   return Res;
525 }
526
527 // Create a constant for Str so that we can pass it to the run-time lib.
528 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
529   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
530   GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
531                             GlobalValue::PrivateLinkage, StrConst,
532                             kAsanGenPrefix);
533   GV->setUnnamedAddr(true);  // Ok to merge these.
534   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
535   return GV;
536 }
537
538 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
539   return G->getName().find(kAsanGenPrefix) == 0;
540 }
541
542 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
543   // Shadow >> scale
544   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
545   if (Mapping.Offset == 0)
546     return Shadow;
547   // (Shadow >> scale) | offset
548   if (Mapping.OrShadowOffset)
549     return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
550   else
551     return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
552 }
553
554 void AddressSanitizer::instrumentMemIntrinsicParam(
555     Instruction *OrigIns,
556     Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
557   IRBuilder<> IRB(InsertBefore);
558   if (Size->getType() != IntptrTy)
559     Size = IRB.CreateIntCast(Size, IntptrTy, false);
560   // Check the first byte.
561   instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
562   // Check the last byte.
563   IRB.SetInsertPoint(InsertBefore);
564   Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
565   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
566   Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
567   instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
568 }
569
570 // Instrument memset/memmove/memcpy
571 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
572   Value *Dst = MI->getDest();
573   MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
574   Value *Src = MemTran ? MemTran->getSource() : 0;
575   Value *Length = MI->getLength();
576
577   Constant *ConstLength = dyn_cast<Constant>(Length);
578   Instruction *InsertBefore = MI;
579   if (ConstLength) {
580     if (ConstLength->isNullValue()) return false;
581   } else {
582     // The size is not a constant so it could be zero -- check at run-time.
583     IRBuilder<> IRB(InsertBefore);
584
585     Value *Cmp = IRB.CreateICmpNE(Length,
586                                   Constant::getNullValue(Length->getType()));
587     InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
588   }
589
590   instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
591   if (Src)
592     instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
593   return true;
594 }
595
596 // If I is an interesting memory access, return the PointerOperand
597 // and set IsWrite. Otherwise return NULL.
598 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
599   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
600     if (!ClInstrumentReads) return NULL;
601     *IsWrite = false;
602     return LI->getPointerOperand();
603   }
604   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
605     if (!ClInstrumentWrites) return NULL;
606     *IsWrite = true;
607     return SI->getPointerOperand();
608   }
609   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
610     if (!ClInstrumentAtomics) return NULL;
611     *IsWrite = true;
612     return RMW->getPointerOperand();
613   }
614   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
615     if (!ClInstrumentAtomics) return NULL;
616     *IsWrite = true;
617     return XCHG->getPointerOperand();
618   }
619   return NULL;
620 }
621
622 void AddressSanitizer::instrumentMop(Instruction *I) {
623   bool IsWrite = false;
624   Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
625   assert(Addr);
626   if (ClOpt && ClOptGlobals) {
627     if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
628       // If initialization order checking is disabled, a simple access to a
629       // dynamically initialized global is always valid.
630       if (!CheckInitOrder)
631         return;
632       // If a global variable does not have dynamic initialization we don't
633       // have to instrument it.  However, if a global does not have initailizer
634       // at all, we assume it has dynamic initializer (in other TU).
635       if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
636         return;
637     }
638   }
639
640   Type *OrigPtrTy = Addr->getType();
641   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
642
643   assert(OrigTy->isSized());
644   uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
645
646   assert((TypeSize % 8) == 0);
647
648   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
649   if (TypeSize == 8  || TypeSize == 16 ||
650       TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
651     return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
652   // Instrument unusual size (but still multiple of 8).
653   // We can not do it with a single check, so we do 1-byte check for the first
654   // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
655   // to report the actual access size.
656   IRBuilder<> IRB(I);
657   Value *LastByte =  IRB.CreateIntToPtr(
658       IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
659                     ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
660       OrigPtrTy);
661   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
662   instrumentAddress(I, I, Addr, 8, IsWrite, Size);
663   instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
664 }
665
666 // Validate the result of Module::getOrInsertFunction called for an interface
667 // function of AddressSanitizer. If the instrumented module defines a function
668 // with the same name, their prototypes must match, otherwise
669 // getOrInsertFunction returns a bitcast.
670 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
671   if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
672   FuncOrBitcast->dump();
673   report_fatal_error("trying to redefine an AddressSanitizer "
674                      "interface function");
675 }
676
677 Instruction *AddressSanitizer::generateCrashCode(
678     Instruction *InsertBefore, Value *Addr,
679     bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
680   IRBuilder<> IRB(InsertBefore);
681   CallInst *Call = SizeArgument
682     ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
683     : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
684
685   // We don't do Call->setDoesNotReturn() because the BB already has
686   // UnreachableInst at the end.
687   // This EmptyAsm is required to avoid callback merge.
688   IRB.CreateCall(EmptyAsm);
689   return Call;
690 }
691
692 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
693                                             Value *ShadowValue,
694                                             uint32_t TypeSize) {
695   size_t Granularity = 1 << Mapping.Scale;
696   // Addr & (Granularity - 1)
697   Value *LastAccessedByte = IRB.CreateAnd(
698       AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
699   // (Addr & (Granularity - 1)) + size - 1
700   if (TypeSize / 8 > 1)
701     LastAccessedByte = IRB.CreateAdd(
702         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
703   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
704   LastAccessedByte = IRB.CreateIntCast(
705       LastAccessedByte, ShadowValue->getType(), false);
706   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
707   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
708 }
709
710 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
711                                          Instruction *InsertBefore,
712                                          Value *Addr, uint32_t TypeSize,
713                                          bool IsWrite, Value *SizeArgument) {
714   IRBuilder<> IRB(InsertBefore);
715   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
716
717   Type *ShadowTy  = IntegerType::get(
718       *C, std::max(8U, TypeSize >> Mapping.Scale));
719   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
720   Value *ShadowPtr = memToShadow(AddrLong, IRB);
721   Value *CmpVal = Constant::getNullValue(ShadowTy);
722   Value *ShadowValue = IRB.CreateLoad(
723       IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
724
725   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
726   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
727   size_t Granularity = 1 << Mapping.Scale;
728   TerminatorInst *CrashTerm = 0;
729
730   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
731     TerminatorInst *CheckTerm =
732         SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
733     assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
734     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
735     IRB.SetInsertPoint(CheckTerm);
736     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
737     BasicBlock *CrashBlock =
738         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
739     CrashTerm = new UnreachableInst(*C, CrashBlock);
740     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
741     ReplaceInstWithInst(CheckTerm, NewTerm);
742   } else {
743     CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
744   }
745
746   Instruction *Crash = generateCrashCode(
747       CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
748   Crash->setDebugLoc(OrigIns->getDebugLoc());
749 }
750
751 void AddressSanitizerModule::createInitializerPoisonCalls(
752     Module &M, GlobalValue *ModuleName) {
753   // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
754   Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
755   // If that function is not present, this TU contains no globals, or they have
756   // all been optimized away
757   if (!GlobalInit)
758     return;
759
760   // Set up the arguments to our poison/unpoison functions.
761   IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
762
763   // Add a call to poison all external globals before the given function starts.
764   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
765   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
766
767   // Add calls to unpoison all globals before each return instruction.
768   for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
769       I != E; ++I) {
770     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
771       CallInst::Create(AsanUnpoisonGlobals, "", RI);
772     }
773   }
774 }
775
776 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
777   Type *Ty = cast<PointerType>(G->getType())->getElementType();
778   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
779
780   if (BL->isIn(*G)) return false;
781   if (!Ty->isSized()) return false;
782   if (!G->hasInitializer()) return false;
783   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
784   // Touch only those globals that will not be defined in other modules.
785   // Don't handle ODR type linkages since other modules may be built w/o asan.
786   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
787       G->getLinkage() != GlobalVariable::PrivateLinkage &&
788       G->getLinkage() != GlobalVariable::InternalLinkage)
789     return false;
790   // Two problems with thread-locals:
791   //   - The address of the main thread's copy can't be computed at link-time.
792   //   - Need to poison all copies, not just the main thread's one.
793   if (G->isThreadLocal())
794     return false;
795   // For now, just ignore this Alloca if the alignment is large.
796   if (G->getAlignment() > RedzoneSize()) return false;
797
798   // Ignore all the globals with the names starting with "\01L_OBJC_".
799   // Many of those are put into the .cstring section. The linker compresses
800   // that section by removing the spare \0s after the string terminator, so
801   // our redzones get broken.
802   if ((G->getName().find("\01L_OBJC_") == 0) ||
803       (G->getName().find("\01l_OBJC_") == 0)) {
804     DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
805     return false;
806   }
807
808   if (G->hasSection()) {
809     StringRef Section(G->getSection());
810     // Ignore the globals from the __OBJC section. The ObjC runtime assumes
811     // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
812     // them.
813     if ((Section.find("__OBJC,") == 0) ||
814         (Section.find("__DATA, __objc_") == 0)) {
815       DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
816       return false;
817     }
818     // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
819     // Constant CFString instances are compiled in the following way:
820     //  -- the string buffer is emitted into
821     //     __TEXT,__cstring,cstring_literals
822     //  -- the constant NSConstantString structure referencing that buffer
823     //     is placed into __DATA,__cfstring
824     // Therefore there's no point in placing redzones into __DATA,__cfstring.
825     // Moreover, it causes the linker to crash on OS X 10.7
826     if (Section.find("__DATA,__cfstring") == 0) {
827       DEBUG(dbgs() << "Ignoring CFString: " << *G);
828       return false;
829     }
830   }
831
832   return true;
833 }
834
835 void AddressSanitizerModule::initializeCallbacks(Module &M) {
836   IRBuilder<> IRB(*C);
837   // Declare our poisoning and unpoisoning functions.
838   AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
839       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
840   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
841   AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
842       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
843   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
844   // Declare functions that register/unregister globals.
845   AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
846       kAsanRegisterGlobalsName, IRB.getVoidTy(),
847       IntptrTy, IntptrTy, NULL));
848   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
849   AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
850       kAsanUnregisterGlobalsName,
851       IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
852   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
853 }
854
855 // This function replaces all global variables with new variables that have
856 // trailing redzones. It also creates a function that poisons
857 // redzones and inserts this function into llvm.global_ctors.
858 bool AddressSanitizerModule::runOnModule(Module &M) {
859   if (!ClGlobals) return false;
860   TD = getAnalysisIfAvailable<DataLayout>();
861   if (!TD)
862     return false;
863   BL.reset(new BlackList(BlacklistFile));
864   if (BL->isIn(M)) return false;
865   C = &(M.getContext());
866   int LongSize = TD->getPointerSizeInBits();
867   IntptrTy = Type::getIntNTy(*C, LongSize);
868   Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
869   initializeCallbacks(M);
870   DynamicallyInitializedGlobals.Init(M);
871
872   SmallVector<GlobalVariable *, 16> GlobalsToChange;
873
874   for (Module::GlobalListType::iterator G = M.global_begin(),
875        E = M.global_end(); G != E; ++G) {
876     if (ShouldInstrumentGlobal(G))
877       GlobalsToChange.push_back(G);
878   }
879
880   size_t n = GlobalsToChange.size();
881   if (n == 0) return false;
882
883   // A global is described by a structure
884   //   size_t beg;
885   //   size_t size;
886   //   size_t size_with_redzone;
887   //   const char *name;
888   //   const char *module_name;
889   //   size_t has_dynamic_init;
890   // We initialize an array of such structures and pass it to a run-time call.
891   StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
892                                                IntptrTy, IntptrTy,
893                                                IntptrTy, IntptrTy, NULL);
894   SmallVector<Constant *, 16> Initializers(n), DynamicInit;
895
896
897   Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
898   assert(CtorFunc);
899   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
900
901   bool HasDynamicallyInitializedGlobals = false;
902
903   GlobalVariable *ModuleName = createPrivateGlobalForString(
904       M, M.getModuleIdentifier());
905   // We shouldn't merge same module names, as this string serves as unique
906   // module ID in runtime.
907   ModuleName->setUnnamedAddr(false);
908
909   for (size_t i = 0; i < n; i++) {
910     static const uint64_t kMaxGlobalRedzone = 1 << 18;
911     GlobalVariable *G = GlobalsToChange[i];
912     PointerType *PtrTy = cast<PointerType>(G->getType());
913     Type *Ty = PtrTy->getElementType();
914     uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
915     uint64_t MinRZ = RedzoneSize();
916     // MinRZ <= RZ <= kMaxGlobalRedzone
917     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
918     uint64_t RZ = std::max(MinRZ,
919                          std::min(kMaxGlobalRedzone,
920                                   (SizeInBytes / MinRZ / 4) * MinRZ));
921     uint64_t RightRedzoneSize = RZ;
922     // Round up to MinRZ
923     if (SizeInBytes % MinRZ)
924       RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
925     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
926     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
927     // Determine whether this global should be poisoned in initialization.
928     bool GlobalHasDynamicInitializer =
929         DynamicallyInitializedGlobals.Contains(G);
930     // Don't check initialization order if this global is blacklisted.
931     GlobalHasDynamicInitializer &= !BL->isInInit(*G);
932
933     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
934     Constant *NewInitializer = ConstantStruct::get(
935         NewTy, G->getInitializer(),
936         Constant::getNullValue(RightRedZoneTy), NULL);
937
938     GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
939
940     // Create a new global variable with enough space for a redzone.
941     GlobalVariable *NewGlobal = new GlobalVariable(
942         M, NewTy, G->isConstant(), G->getLinkage(),
943         NewInitializer, "", G, G->getThreadLocalMode());
944     NewGlobal->copyAttributesFrom(G);
945     NewGlobal->setAlignment(MinRZ);
946
947     Value *Indices2[2];
948     Indices2[0] = IRB.getInt32(0);
949     Indices2[1] = IRB.getInt32(0);
950
951     G->replaceAllUsesWith(
952         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
953     NewGlobal->takeName(G);
954     G->eraseFromParent();
955
956     Initializers[i] = ConstantStruct::get(
957         GlobalStructTy,
958         ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
959         ConstantInt::get(IntptrTy, SizeInBytes),
960         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
961         ConstantExpr::getPointerCast(Name, IntptrTy),
962         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
963         ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
964         NULL);
965
966     // Populate the first and last globals declared in this TU.
967     if (CheckInitOrder && GlobalHasDynamicInitializer)
968       HasDynamicallyInitializedGlobals = true;
969
970     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
971   }
972
973   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
974   GlobalVariable *AllGlobals = new GlobalVariable(
975       M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
976       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
977
978   // Create calls for poisoning before initializers run and unpoisoning after.
979   if (CheckInitOrder && HasDynamicallyInitializedGlobals)
980     createInitializerPoisonCalls(M, ModuleName);
981   IRB.CreateCall2(AsanRegisterGlobals,
982                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
983                   ConstantInt::get(IntptrTy, n));
984
985   // We also need to unregister globals at the end, e.g. when a shared library
986   // gets closed.
987   Function *AsanDtorFunction = Function::Create(
988       FunctionType::get(Type::getVoidTy(*C), false),
989       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
990   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
991   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
992   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
993                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
994                        ConstantInt::get(IntptrTy, n));
995   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
996
997   DEBUG(dbgs() << M);
998   return true;
999 }
1000
1001 void AddressSanitizer::initializeCallbacks(Module &M) {
1002   IRBuilder<> IRB(*C);
1003   // Create __asan_report* callbacks.
1004   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1005     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1006          AccessSizeIndex++) {
1007       // IsWrite and TypeSize are encoded in the function name.
1008       std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1009           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1010       // If we are merging crash callbacks, they have two parameters.
1011       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1012           checkInterfaceFunction(M.getOrInsertFunction(
1013               FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
1014     }
1015   }
1016   AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1017               kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1018   AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1019               kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1020
1021   AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1022       kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1023   // We insert an empty inline asm after __asan_report* to avoid callback merge.
1024   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1025                             StringRef(""), StringRef(""),
1026                             /*hasSideEffects=*/true);
1027 }
1028
1029 void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
1030   // Tell the values of mapping offset and scale to the run-time.
1031   GlobalValue *asan_mapping_offset =
1032       new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1033                      ConstantInt::get(IntptrTy, Mapping.Offset),
1034                      kAsanMappingOffsetName);
1035   // Read the global, otherwise it may be optimized away.
1036   IRB.CreateLoad(asan_mapping_offset, true);
1037
1038   GlobalValue *asan_mapping_scale =
1039       new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1040                          ConstantInt::get(IntptrTy, Mapping.Scale),
1041                          kAsanMappingScaleName);
1042   // Read the global, otherwise it may be optimized away.
1043   IRB.CreateLoad(asan_mapping_scale, true);
1044 }
1045
1046 // virtual
1047 bool AddressSanitizer::doInitialization(Module &M) {
1048   // Initialize the private fields. No one has accessed them before.
1049   TD = getAnalysisIfAvailable<DataLayout>();
1050
1051   if (!TD)
1052     return false;
1053   BL.reset(new BlackList(BlacklistFile));
1054   DynamicallyInitializedGlobals.Init(M);
1055
1056   C = &(M.getContext());
1057   LongSize = TD->getPointerSizeInBits();
1058   IntptrTy = Type::getIntNTy(*C, LongSize);
1059
1060   AsanCtorFunction = Function::Create(
1061       FunctionType::get(Type::getVoidTy(*C), false),
1062       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1063   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1064   // call __asan_init in the module ctor.
1065   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1066   AsanInitFunction = checkInterfaceFunction(
1067       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1068   AsanInitFunction->setLinkage(Function::ExternalLinkage);
1069   IRB.CreateCall(AsanInitFunction);
1070
1071   Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
1072   emitShadowMapping(M, IRB);
1073
1074   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1075   return true;
1076 }
1077
1078 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1079   // For each NSObject descendant having a +load method, this method is invoked
1080   // by the ObjC runtime before any of the static constructors is called.
1081   // Therefore we need to instrument such methods with a call to __asan_init
1082   // at the beginning in order to initialize our runtime before any access to
1083   // the shadow memory.
1084   // We cannot just ignore these methods, because they may call other
1085   // instrumented functions.
1086   if (F.getName().find(" load]") != std::string::npos) {
1087     IRBuilder<> IRB(F.begin()->begin());
1088     IRB.CreateCall(AsanInitFunction);
1089     return true;
1090   }
1091   return false;
1092 }
1093
1094 bool AddressSanitizer::runOnFunction(Function &F) {
1095   if (BL->isIn(F)) return false;
1096   if (&F == AsanCtorFunction) return false;
1097   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1098   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1099   initializeCallbacks(*F.getParent());
1100
1101   // If needed, insert __asan_init before checking for SanitizeAddress attr.
1102   maybeInsertAsanInitAtFunctionEntry(F);
1103
1104   if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1105                                       Attribute::SanitizeAddress))
1106     return false;
1107
1108   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1109     return false;
1110
1111   // We want to instrument every address only once per basic block (unless there
1112   // are calls between uses).
1113   SmallSet<Value*, 16> TempsToInstrument;
1114   SmallVector<Instruction*, 16> ToInstrument;
1115   SmallVector<Instruction*, 8> NoReturnCalls;
1116   bool IsWrite;
1117
1118   // Fill the set of memory operations to instrument.
1119   for (Function::iterator FI = F.begin(), FE = F.end();
1120        FI != FE; ++FI) {
1121     TempsToInstrument.clear();
1122     int NumInsnsPerBB = 0;
1123     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1124          BI != BE; ++BI) {
1125       if (LooksLikeCodeInBug11395(BI)) return false;
1126       if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1127         if (ClOpt && ClOptSameTemp) {
1128           if (!TempsToInstrument.insert(Addr))
1129             continue;  // We've seen this temp in the current BB.
1130         }
1131       } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1132         // ok, take it.
1133       } else {
1134         CallSite CS(BI);
1135         if (CS) {
1136           // A call inside BB.
1137           TempsToInstrument.clear();
1138           if (CS.doesNotReturn())
1139             NoReturnCalls.push_back(CS.getInstruction());
1140         }
1141         continue;
1142       }
1143       ToInstrument.push_back(BI);
1144       NumInsnsPerBB++;
1145       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1146         break;
1147     }
1148   }
1149
1150   // Instrument.
1151   int NumInstrumented = 0;
1152   for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1153     Instruction *Inst = ToInstrument[i];
1154     if (ClDebugMin < 0 || ClDebugMax < 0 ||
1155         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1156       if (isInterestingMemoryAccess(Inst, &IsWrite))
1157         instrumentMop(Inst);
1158       else
1159         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1160     }
1161     NumInstrumented++;
1162   }
1163
1164   FunctionStackPoisoner FSP(F, *this);
1165   bool ChangedStack = FSP.runOnFunction();
1166
1167   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1168   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1169   for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1170     Instruction *CI = NoReturnCalls[i];
1171     IRBuilder<> IRB(CI);
1172     IRB.CreateCall(AsanHandleNoReturnFunc);
1173   }
1174   DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
1175
1176   return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1177 }
1178
1179 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1180   if (ShadowRedzoneSize == 1) return PoisonByte;
1181   if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1182   if (ShadowRedzoneSize == 4)
1183     return (PoisonByte << 24) + (PoisonByte << 16) +
1184         (PoisonByte << 8) + (PoisonByte);
1185   llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
1186 }
1187
1188 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1189                                             size_t Size,
1190                                             size_t RZSize,
1191                                             size_t ShadowGranularity,
1192                                             uint8_t Magic) {
1193   for (size_t i = 0; i < RZSize;
1194        i+= ShadowGranularity, Shadow++) {
1195     if (i + ShadowGranularity <= Size) {
1196       *Shadow = 0;  // fully addressable
1197     } else if (i >= Size) {
1198       *Shadow = Magic;  // unaddressable
1199     } else {
1200       *Shadow = Size - i;  // first Size-i bytes are addressable
1201     }
1202   }
1203 }
1204
1205 // Workaround for bug 11395: we don't want to instrument stack in functions
1206 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1207 // FIXME: remove once the bug 11395 is fixed.
1208 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1209   if (LongSize != 32) return false;
1210   CallInst *CI = dyn_cast<CallInst>(I);
1211   if (!CI || !CI->isInlineAsm()) return false;
1212   if (CI->getNumArgOperands() <= 5) return false;
1213   // We have inline assembly with quite a few arguments.
1214   return true;
1215 }
1216
1217 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1218   IRBuilder<> IRB(*C);
1219   AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1220       kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1221   AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1222       kAsanStackFreeName, IRB.getVoidTy(),
1223       IntptrTy, IntptrTy, IntptrTy, NULL));
1224   AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1225       kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1226   AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1227       kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1228 }
1229
1230 void FunctionStackPoisoner::poisonRedZones(
1231   const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1232   bool DoPoison) {
1233   size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
1234   assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1235   Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1236   Type *RZPtrTy = PointerType::get(RZTy, 0);
1237
1238   Value *PoisonLeft  = ConstantInt::get(RZTy,
1239     ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1240   Value *PoisonMid   = ConstantInt::get(RZTy,
1241     ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1242   Value *PoisonRight = ConstantInt::get(RZTy,
1243     ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1244
1245   // poison the first red zone.
1246   IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1247
1248   // poison all other red zones.
1249   uint64_t Pos = RedzoneSize();
1250   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1251     AllocaInst *AI = AllocaVec[i];
1252     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1253     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1254     assert(AlignedSize - SizeInBytes < RedzoneSize());
1255     Value *Ptr = NULL;
1256
1257     Pos += AlignedSize;
1258
1259     assert(ShadowBase->getType() == IntptrTy);
1260     if (SizeInBytes < AlignedSize) {
1261       // Poison the partial redzone at right
1262       Ptr = IRB.CreateAdd(
1263           ShadowBase, ConstantInt::get(IntptrTy,
1264                                        (Pos >> Mapping.Scale) - ShadowRZSize));
1265       size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1266       uint32_t Poison = 0;
1267       if (DoPoison) {
1268         PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1269                                         RedzoneSize(),
1270                                         1ULL << Mapping.Scale,
1271                                         kAsanStackPartialRedzoneMagic);
1272       }
1273       Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1274       IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1275     }
1276
1277     // Poison the full redzone at right.
1278     Ptr = IRB.CreateAdd(ShadowBase,
1279                         ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
1280     bool LastAlloca = (i == AllocaVec.size() - 1);
1281     Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
1282     IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1283
1284     Pos += RedzoneSize();
1285   }
1286 }
1287
1288 void FunctionStackPoisoner::poisonStack() {
1289   uint64_t LocalStackSize = TotalStackSize +
1290                             (AllocaVec.size() + 1) * RedzoneSize();
1291
1292   bool DoStackMalloc = ASan.CheckUseAfterReturn
1293       && LocalStackSize <= kMaxStackMallocSize;
1294
1295   assert(AllocaVec.size() > 0);
1296   Instruction *InsBefore = AllocaVec[0];
1297   IRBuilder<> IRB(InsBefore);
1298
1299
1300   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1301   AllocaInst *MyAlloca =
1302       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1303   if (ClRealignStack && StackAlignment < RedzoneSize())
1304     StackAlignment = RedzoneSize();
1305   MyAlloca->setAlignment(StackAlignment);
1306   assert(MyAlloca->isStaticAlloca());
1307   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1308   Value *LocalStackBase = OrigStackBase;
1309
1310   if (DoStackMalloc) {
1311     LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1312         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1313   }
1314
1315   // This string will be parsed by the run-time (DescribeAddressIfStack).
1316   SmallString<2048> StackDescriptionStorage;
1317   raw_svector_ostream StackDescription(StackDescriptionStorage);
1318   StackDescription << AllocaVec.size() << " ";
1319
1320   // Insert poison calls for lifetime intrinsics for alloca.
1321   bool HavePoisonedAllocas = false;
1322   for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1323     const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1324     IntrinsicInst *II = APC.InsBefore;
1325     AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1326     assert(AI);
1327     IRBuilder<> IRB(II);
1328     poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1329     HavePoisonedAllocas |= APC.DoPoison;
1330   }
1331
1332   uint64_t Pos = RedzoneSize();
1333   // Replace Alloca instructions with base+offset.
1334   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1335     AllocaInst *AI = AllocaVec[i];
1336     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1337     StringRef Name = AI->getName();
1338     StackDescription << Pos << " " << SizeInBytes << " "
1339                      << Name.size() << " " << Name << " ";
1340     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1341     assert((AlignedSize % RedzoneSize()) == 0);
1342     Value *NewAllocaPtr = IRB.CreateIntToPtr(
1343             IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1344             AI->getType());
1345     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1346     AI->replaceAllUsesWith(NewAllocaPtr);
1347     Pos += AlignedSize + RedzoneSize();
1348   }
1349   assert(Pos == LocalStackSize);
1350
1351   // The left-most redzone has enough space for at least 4 pointers.
1352   // Write the Magic value to redzone[0].
1353   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1354   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1355                   BasePlus0);
1356   // Write the frame description constant to redzone[1].
1357   Value *BasePlus1 = IRB.CreateIntToPtr(
1358     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1359     IntptrPtrTy);
1360   GlobalVariable *StackDescriptionGlobal =
1361       createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1362   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1363                                              IntptrTy);
1364   IRB.CreateStore(Description, BasePlus1);
1365   // Write the PC to redzone[2].
1366   Value *BasePlus2 = IRB.CreateIntToPtr(
1367     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1368                                                    2 * ASan.LongSize/8)),
1369     IntptrPtrTy);
1370   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1371
1372   // Poison the stack redzones at the entry.
1373   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1374   poisonRedZones(AllocaVec, IRB, ShadowBase, true);
1375
1376   // Unpoison the stack before all ret instructions.
1377   for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1378     Instruction *Ret = RetVec[i];
1379     IRBuilder<> IRBRet(Ret);
1380     // Mark the current frame as retired.
1381     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1382                        BasePlus0);
1383     // Unpoison the stack.
1384     poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
1385     if (DoStackMalloc) {
1386       // In use-after-return mode, mark the whole stack frame unaddressable.
1387       IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1388                          ConstantInt::get(IntptrTy, LocalStackSize),
1389                          OrigStackBase);
1390     } else if (HavePoisonedAllocas) {
1391       // If we poisoned some allocas in llvm.lifetime analysis,
1392       // unpoison whole stack frame now.
1393       assert(LocalStackBase == OrigStackBase);
1394       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1395     }
1396   }
1397
1398   // We are done. Remove the old unused alloca instructions.
1399   for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1400     AllocaVec[i]->eraseFromParent();
1401 }
1402
1403 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1404                                          IRBuilder<> IRB, bool DoPoison) {
1405   // For now just insert the call to ASan runtime.
1406   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1407   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1408   IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1409                            : AsanUnpoisonStackMemoryFunc,
1410                   AddrArg, SizeArg);
1411 }
1412
1413 // Handling llvm.lifetime intrinsics for a given %alloca:
1414 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1415 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1416 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1417 //     could be poisoned by previous llvm.lifetime.end instruction, as the
1418 //     variable may go in and out of scope several times, e.g. in loops).
1419 // (3) if we poisoned at least one %alloca in a function,
1420 //     unpoison the whole stack frame at function exit.
1421
1422 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1423   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1424     // We're intested only in allocas we can handle.
1425     return isInterestingAlloca(*AI) ? AI : 0;
1426   // See if we've already calculated (or started to calculate) alloca for a
1427   // given value.
1428   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1429   if (I != AllocaForValue.end())
1430     return I->second;
1431   // Store 0 while we're calculating alloca for value V to avoid
1432   // infinite recursion if the value references itself.
1433   AllocaForValue[V] = 0;
1434   AllocaInst *Res = 0;
1435   if (CastInst *CI = dyn_cast<CastInst>(V))
1436     Res = findAllocaForValue(CI->getOperand(0));
1437   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1438     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1439       Value *IncValue = PN->getIncomingValue(i);
1440       // Allow self-referencing phi-nodes.
1441       if (IncValue == PN) continue;
1442       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1443       // AI for incoming values should exist and should all be equal.
1444       if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1445         return 0;
1446       Res = IncValueAI;
1447     }
1448   }
1449   if (Res != 0)
1450     AllocaForValue[V] = Res;
1451   return Res;
1452 }