1 //===- AddressSanitizer.cpp - memory error detector -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of AddressSanitizer, an address sanity checker.
10 // Details of the algorithm:
11 //  https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/BinaryFormat/MachO.h"
30 #include "llvm/IR/Argument.h"
31 #include "llvm/IR/Attributes.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/Comdat.h"
34 #include "llvm/IR/Constant.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DIBuilder.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DebugInfoMetadata.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Dominators.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/IRBuilder.h"
47 #include "llvm/IR/InlineAsm.h"
48 #include "llvm/IR/InstVisitor.h"
49 #include "llvm/IR/InstrTypes.h"
50 #include "llvm/IR/Instruction.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/IntrinsicInst.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/MDBuilder.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/IR/Use.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/InitializePasses.h"
62 #include "llvm/MC/MCSectionMachO.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/ErrorHandling.h"
68 #include "llvm/Support/MathExtras.h"
69 #include "llvm/Support/ScopedPrinter.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/Transforms/Instrumentation.h"
72 #include "llvm/Transforms/Instrumentation/AddressSanitizerCommon.h"
73 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
74 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
75 #include "llvm/Transforms/Utils/Local.h"
76 #include "llvm/Transforms/Utils/ModuleUtils.h"
77 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
78 #include <algorithm>
79 #include <cassert>
80 #include <cstddef>
81 #include <cstdint>
82 #include <iomanip>
83 #include <limits>
84 #include <memory>
85 #include <sstream>
86 #include <string>
87 #include <tuple>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "asan"
92 
93 static const uint64_t kDefaultShadowScale = 3;
94 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
95 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
96 static const uint64_t kDynamicShadowSentinel =
97     std::numeric_limits<uint64_t>::max();
98 static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF;  // < 2G.
99 static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;
100 static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
101 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
102 static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
103 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
104 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
105 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
106 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
107 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
108 static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;
109 static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
110 static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff900000000000;
111 static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
112 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
113 static const uint64_t kEmscriptenShadowOffset = 0;
114 
115 static const uint64_t kMyriadShadowScale = 5;
116 static const uint64_t kMyriadMemoryOffset32 = 0x80000000ULL;
117 static const uint64_t kMyriadMemorySize32 = 0x20000000ULL;
118 static const uint64_t kMyriadTagShift = 29;
119 static const uint64_t kMyriadDDRTag = 4;
120 static const uint64_t kMyriadCacheBitMask32 = 0x40000000ULL;
121 
122 // The shadow memory space is dynamically allocated.
123 static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
124 
125 static const size_t kMinStackMallocSize = 1 << 6;   // 64B
126 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
127 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
128 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
129 
130 static const char *const kAsanModuleCtorName = "asan.module_ctor";
131 static const char *const kAsanModuleDtorName = "asan.module_dtor";
132 static const uint64_t kAsanCtorAndDtorPriority = 1;
133 // On Emscripten, the system needs more than one priorities for constructors.
134 static const uint64_t kAsanEmscriptenCtorAndDtorPriority = 50;
135 static const char *const kAsanReportErrorTemplate = "__asan_report_";
136 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
137 static const char *const kAsanUnregisterGlobalsName =
138     "__asan_unregister_globals";
139 static const char *const kAsanRegisterImageGlobalsName =
140   "__asan_register_image_globals";
141 static const char *const kAsanUnregisterImageGlobalsName =
142   "__asan_unregister_image_globals";
143 static const char *const kAsanRegisterElfGlobalsName =
144   "__asan_register_elf_globals";
145 static const char *const kAsanUnregisterElfGlobalsName =
146   "__asan_unregister_elf_globals";
147 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
148 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
149 static const char *const kAsanInitName = "__asan_init";
150 static const char *const kAsanVersionCheckNamePrefix =
151     "__asan_version_mismatch_check_v";
152 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
153 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
154 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
155 static const int kMaxAsanStackMallocSizeClass = 10;
156 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
157 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
158 static const char *const kAsanGenPrefix = "___asan_gen_";
159 static const char *const kODRGenPrefix = "__odr_asan_gen_";
160 static const char *const kSanCovGenPrefix = "__sancov_gen_";
161 static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
162 static const char *const kAsanPoisonStackMemoryName =
163     "__asan_poison_stack_memory";
164 static const char *const kAsanUnpoisonStackMemoryName =
165     "__asan_unpoison_stack_memory";
166 
167 // ASan version script has __asan_* wildcard. Triple underscore prevents a
168 // linker (gold) warning about attempting to export a local symbol.
169 static const char *const kAsanGlobalsRegisteredFlagName =
170     "___asan_globals_registered";
171 
172 static const char *const kAsanOptionDetectUseAfterReturn =
173     "__asan_option_detect_stack_use_after_return";
174 
175 static const char *const kAsanShadowMemoryDynamicAddress =
176     "__asan_shadow_memory_dynamic_address";
177 
178 static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
179 static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
180 
181 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
182 static const size_t kNumberOfAccessSizes = 5;
183 
184 static const unsigned kAllocaRzSize = 32;
185 
186 // Command-line flags.
187 
188 static cl::opt<bool> ClEnableKasan(
189     "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
190     cl::Hidden, cl::init(false));
191 
192 static cl::opt<bool> ClRecover(
193     "asan-recover",
194     cl::desc("Enable recovery mode (continue-after-error)."),
195     cl::Hidden, cl::init(false));
196 
197 static cl::opt<bool> ClInsertVersionCheck(
198     "asan-guard-against-version-mismatch",
199     cl::desc("Guard against compiler/runtime version mismatch."),
200     cl::Hidden, cl::init(true));
201 
202 // This flag may need to be replaced with -f[no-]asan-reads.
203 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
204                                        cl::desc("instrument read instructions"),
205                                        cl::Hidden, cl::init(true));
206 
207 static cl::opt<bool> ClInstrumentWrites(
208     "asan-instrument-writes", cl::desc("instrument write instructions"),
209     cl::Hidden, cl::init(true));
210 
211 static cl::opt<bool> ClInstrumentAtomics(
212     "asan-instrument-atomics",
213     cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
214     cl::init(true));
215 
216 static cl::opt<bool>
217     ClInstrumentByval("asan-instrument-byval",
218                       cl::desc("instrument byval call arguments"), cl::Hidden,
219                       cl::init(true));
220 
221 static cl::opt<bool> ClAlwaysSlowPath(
222     "asan-always-slow-path",
223     cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
224     cl::init(false));
225 
226 static cl::opt<bool> ClForceDynamicShadow(
227     "asan-force-dynamic-shadow",
228     cl::desc("Load shadow address into a local variable for each function"),
229     cl::Hidden, cl::init(false));
230 
231 static cl::opt<bool>
232     ClWithIfunc("asan-with-ifunc",
233                 cl::desc("Access dynamic shadow through an ifunc global on "
234                          "platforms that support this"),
235                 cl::Hidden, cl::init(true));
236 
237 static cl::opt<bool> ClWithIfuncSuppressRemat(
238     "asan-with-ifunc-suppress-remat",
239     cl::desc("Suppress rematerialization of dynamic shadow address by passing "
240              "it through inline asm in prologue."),
241     cl::Hidden, cl::init(true));
242 
243 // This flag limits the number of instructions to be instrumented
244 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
245 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
246 // set it to 10000.
247 static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
248     "asan-max-ins-per-bb", cl::init(10000),
249     cl::desc("maximal number of instructions to instrument in any given BB"),
250     cl::Hidden);
251 
252 // This flag may need to be replaced with -f[no]asan-stack.
253 static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
254                              cl::Hidden, cl::init(true));
255 static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
256     "asan-max-inline-poisoning-size",
257     cl::desc(
258         "Inline shadow poisoning for blocks up to the given size in bytes."),
259     cl::Hidden, cl::init(64));
260 
261 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
262                                       cl::desc("Check stack-use-after-return"),
263                                       cl::Hidden, cl::init(true));
264 
265 static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
266                                         cl::desc("Create redzones for byval "
267                                                  "arguments (extra copy "
268                                                  "required)"), cl::Hidden,
269                                         cl::init(true));
270 
271 static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
272                                      cl::desc("Check stack-use-after-scope"),
273                                      cl::Hidden, cl::init(false));
274 
275 // This flag may need to be replaced with -f[no]asan-globals.
276 static cl::opt<bool> ClGlobals("asan-globals",
277                                cl::desc("Handle global objects"), cl::Hidden,
278                                cl::init(true));
279 
280 static cl::opt<bool> ClInitializers("asan-initialization-order",
281                                     cl::desc("Handle C++ initializer order"),
282                                     cl::Hidden, cl::init(true));
283 
284 static cl::opt<bool> ClInvalidPointerPairs(
285     "asan-detect-invalid-pointer-pair",
286     cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
287     cl::init(false));
288 
289 static cl::opt<bool> ClInvalidPointerCmp(
290     "asan-detect-invalid-pointer-cmp",
291     cl::desc("Instrument <, <=, >, >= with pointer operands"), cl::Hidden,
292     cl::init(false));
293 
294 static cl::opt<bool> ClInvalidPointerSub(
295     "asan-detect-invalid-pointer-sub",
296     cl::desc("Instrument - operations with pointer operands"), cl::Hidden,
297     cl::init(false));
298 
299 static cl::opt<unsigned> ClRealignStack(
300     "asan-realign-stack",
301     cl::desc("Realign stack to the value of this flag (power of two)"),
302     cl::Hidden, cl::init(32));
303 
304 static cl::opt<int> ClInstrumentationWithCallsThreshold(
305     "asan-instrumentation-with-call-threshold",
306     cl::desc(
307         "If the function being instrumented contains more than "
308         "this number of memory accesses, use callbacks instead of "
309         "inline checks (-1 means never use callbacks)."),
310     cl::Hidden, cl::init(7000));
311 
312 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
313     "asan-memory-access-callback-prefix",
314     cl::desc("Prefix for memory access callbacks"), cl::Hidden,
315     cl::init("__asan_"));
316 
317 static cl::opt<bool>
318     ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
319                                cl::desc("instrument dynamic allocas"),
320                                cl::Hidden, cl::init(true));
321 
322 static cl::opt<bool> ClSkipPromotableAllocas(
323     "asan-skip-promotable-allocas",
324     cl::desc("Do not instrument promotable allocas"), cl::Hidden,
325     cl::init(true));
326 
327 // These flags allow to change the shadow mapping.
328 // The shadow mapping looks like
329 //    Shadow = (Mem >> scale) + offset
330 
331 static cl::opt<int> ClMappingScale("asan-mapping-scale",
332                                    cl::desc("scale of asan shadow mapping"),
333                                    cl::Hidden, cl::init(0));
334 
335 static cl::opt<uint64_t>
336     ClMappingOffset("asan-mapping-offset",
337                     cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"),
338                     cl::Hidden, cl::init(0));
339 
340 // Optimization flags. Not user visible, used mostly for testing
341 // and benchmarking the tool.
342 
343 static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
344                            cl::Hidden, cl::init(true));
345 
346 static cl::opt<bool> ClOptSameTemp(
347     "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
348     cl::Hidden, cl::init(true));
349 
350 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
351                                   cl::desc("Don't instrument scalar globals"),
352                                   cl::Hidden, cl::init(true));
353 
354 static cl::opt<bool> ClOptStack(
355     "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
356     cl::Hidden, cl::init(false));
357 
358 static cl::opt<bool> ClDynamicAllocaStack(
359     "asan-stack-dynamic-alloca",
360     cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
361     cl::init(true));
362 
363 static cl::opt<uint32_t> ClForceExperiment(
364     "asan-force-experiment",
365     cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
366     cl::init(0));
367 
368 static cl::opt<bool>
369     ClUsePrivateAlias("asan-use-private-alias",
370                       cl::desc("Use private aliases for global variables"),
371                       cl::Hidden, cl::init(false));
372 
373 static cl::opt<bool>
374     ClUseOdrIndicator("asan-use-odr-indicator",
375                       cl::desc("Use odr indicators to improve ODR reporting"),
376                       cl::Hidden, cl::init(false));
377 
378 static cl::opt<bool>
379     ClUseGlobalsGC("asan-globals-live-support",
380                    cl::desc("Use linker features to support dead "
381                             "code stripping of globals"),
382                    cl::Hidden, cl::init(true));
383 
384 // This is on by default even though there is a bug in gold:
385 // https://sourceware.org/bugzilla/show_bug.cgi?id=19002
386 static cl::opt<bool>
387     ClWithComdat("asan-with-comdat",
388                  cl::desc("Place ASan constructors in comdat sections"),
389                  cl::Hidden, cl::init(true));
390 
391 // Debug flags.
392 
393 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
394                             cl::init(0));
395 
396 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
397                                  cl::Hidden, cl::init(0));
398 
399 static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
400                                         cl::desc("Debug func"));
401 
402 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
403                                cl::Hidden, cl::init(-1));
404 
405 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
406                                cl::Hidden, cl::init(-1));
407 
408 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
409 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
410 STATISTIC(NumOptimizedAccessesToGlobalVar,
411           "Number of optimized accesses to global vars");
412 STATISTIC(NumOptimizedAccessesToStackVar,
413           "Number of optimized accesses to stack vars");
414 
415 namespace {
416 
417 /// This struct defines the shadow mapping using the rule:
418 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
419 /// If InGlobal is true, then
420 ///   extern char __asan_shadow[];
421 ///   shadow = (mem >> Scale) + &__asan_shadow
422 struct ShadowMapping {
423   int Scale;
424   uint64_t Offset;
425   bool OrShadowOffset;
426   bool InGlobal;
427 };
428 
429 } // end anonymous namespace
430 
431 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
432                                       bool IsKasan) {
433   bool IsAndroid = TargetTriple.isAndroid();
434   bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
435   bool IsFreeBSD = TargetTriple.isOSFreeBSD();
436   bool IsNetBSD = TargetTriple.isOSNetBSD();
437   bool IsPS4CPU = TargetTriple.isPS4CPU();
438   bool IsLinux = TargetTriple.isOSLinux();
439   bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
440                  TargetTriple.getArch() == Triple::ppc64le;
441   bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
442   bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
443   bool IsMIPS32 = TargetTriple.isMIPS32();
444   bool IsMIPS64 = TargetTriple.isMIPS64();
445   bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
446   bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
447   bool IsWindows = TargetTriple.isOSWindows();
448   bool IsFuchsia = TargetTriple.isOSFuchsia();
449   bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
450   bool IsEmscripten = TargetTriple.isOSEmscripten();
451 
452   ShadowMapping Mapping;
453 
454   Mapping.Scale = IsMyriad ? kMyriadShadowScale : kDefaultShadowScale;
455   if (ClMappingScale.getNumOccurrences() > 0) {
456     Mapping.Scale = ClMappingScale;
457   }
458 
459   if (LongSize == 32) {
460     if (IsAndroid)
461       Mapping.Offset = kDynamicShadowSentinel;
462     else if (IsMIPS32)
463       Mapping.Offset = kMIPS32_ShadowOffset32;
464     else if (IsFreeBSD)
465       Mapping.Offset = kFreeBSD_ShadowOffset32;
466     else if (IsNetBSD)
467       Mapping.Offset = kNetBSD_ShadowOffset32;
468     else if (IsIOS)
469       Mapping.Offset = kDynamicShadowSentinel;
470     else if (IsWindows)
471       Mapping.Offset = kWindowsShadowOffset32;
472     else if (IsEmscripten)
473       Mapping.Offset = kEmscriptenShadowOffset;
474     else if (IsMyriad) {
475       uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
476                                (kMyriadMemorySize32 >> Mapping.Scale));
477       Mapping.Offset = ShadowOffset - (kMyriadMemoryOffset32 >> Mapping.Scale);
478     }
479     else
480       Mapping.Offset = kDefaultShadowOffset32;
481   } else {  // LongSize == 64
482     // Fuchsia is always PIE, which means that the beginning of the address
483     // space is always available.
484     if (IsFuchsia)
485       Mapping.Offset = 0;
486     else if (IsPPC64)
487       Mapping.Offset = kPPC64_ShadowOffset64;
488     else if (IsSystemZ)
489       Mapping.Offset = kSystemZ_ShadowOffset64;
490     else if (IsFreeBSD && !IsMIPS64)
491       Mapping.Offset = kFreeBSD_ShadowOffset64;
492     else if (IsNetBSD) {
493       if (IsKasan)
494         Mapping.Offset = kNetBSDKasan_ShadowOffset64;
495       else
496         Mapping.Offset = kNetBSD_ShadowOffset64;
497     } else if (IsPS4CPU)
498       Mapping.Offset = kPS4CPU_ShadowOffset64;
499     else if (IsLinux && IsX86_64) {
500       if (IsKasan)
501         Mapping.Offset = kLinuxKasan_ShadowOffset64;
502       else
503         Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
504                           (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
505     } else if (IsWindows && IsX86_64) {
506       Mapping.Offset = kWindowsShadowOffset64;
507     } else if (IsMIPS64)
508       Mapping.Offset = kMIPS64_ShadowOffset64;
509     else if (IsIOS)
510       Mapping.Offset = kDynamicShadowSentinel;
511     else if (IsAArch64)
512       Mapping.Offset = kAArch64_ShadowOffset64;
513     else
514       Mapping.Offset = kDefaultShadowOffset64;
515   }
516 
517   if (ClForceDynamicShadow) {
518     Mapping.Offset = kDynamicShadowSentinel;
519   }
520 
521   if (ClMappingOffset.getNumOccurrences() > 0) {
522     Mapping.Offset = ClMappingOffset;
523   }
524 
525   // OR-ing shadow offset if more efficient (at least on x86) if the offset
526   // is a power of two, but on ppc64 we have to use add since the shadow
527   // offset is not necessary 1/8-th of the address space.  On SystemZ,
528   // we could OR the constant in a single instruction, but it's more
529   // efficient to load it once and use indexed addressing.
530   Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
531                            !(Mapping.Offset & (Mapping.Offset - 1)) &&
532                            Mapping.Offset != kDynamicShadowSentinel;
533   bool IsAndroidWithIfuncSupport =
534       IsAndroid && !TargetTriple.isAndroidVersionLT(21);
535   Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
536 
537   return Mapping;
538 }
539 
540 static size_t RedzoneSizeForScale(int MappingScale) {
541   // Redzone used for stack and globals is at least 32 bytes.
542   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
543   return std::max(32U, 1U << MappingScale);
544 }
545 
546 static uint64_t GetCtorAndDtorPriority(Triple &TargetTriple) {
547   if (TargetTriple.isOSEmscripten()) {
548     return kAsanEmscriptenCtorAndDtorPriority;
549   } else {
550     return kAsanCtorAndDtorPriority;
551   }
552 }
553 
554 namespace {
555 
556 /// Module analysis for getting various metadata about the module.
557 class ASanGlobalsMetadataWrapperPass : public ModulePass {
558 public:
559   static char ID;
560 
561   ASanGlobalsMetadataWrapperPass() : ModulePass(ID) {
562     initializeASanGlobalsMetadataWrapperPassPass(
563         *PassRegistry::getPassRegistry());
564   }
565 
566   bool runOnModule(Module &M) override {
567     GlobalsMD = GlobalsMetadata(M);
568     return false;
569   }
570 
571   StringRef getPassName() const override {
572     return "ASanGlobalsMetadataWrapperPass";
573   }
574 
575   void getAnalysisUsage(AnalysisUsage &AU) const override {
576     AU.setPreservesAll();
577   }
578 
579   GlobalsMetadata &getGlobalsMD() { return GlobalsMD; }
580 
581 private:
582   GlobalsMetadata GlobalsMD;
583 };
584 
585 char ASanGlobalsMetadataWrapperPass::ID = 0;
586 
587 /// AddressSanitizer: instrument the code in module to find memory bugs.
588 struct AddressSanitizer {
589   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
590                    bool CompileKernel = false, bool Recover = false,
591                    bool UseAfterScope = false)
592       : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
593                                                             : CompileKernel),
594         Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
595         UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
596     C = &(M.getContext());
597     LongSize = M.getDataLayout().getPointerSizeInBits();
598     IntptrTy = Type::getIntNTy(*C, LongSize);
599     TargetTriple = Triple(M.getTargetTriple());
600 
601     Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
602   }
603 
604   uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
605     uint64_t ArraySize = 1;
606     if (AI.isArrayAllocation()) {
607       const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
608       assert(CI && "non-constant array size");
609       ArraySize = CI->getZExtValue();
610     }
611     Type *Ty = AI.getAllocatedType();
612     uint64_t SizeInBytes =
613         AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
614     return SizeInBytes * ArraySize;
615   }
616 
617   /// Check if we want (and can) handle this alloca.
618   bool isInterestingAlloca(const AllocaInst &AI);
619 
620   bool ignoreAccess(Value *Ptr);
621   void getInterestingMemoryOperands(
622       Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting);
623 
624   void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
625                      InterestingMemoryOperand &O, bool UseCalls,
626                      const DataLayout &DL);
627   void instrumentPointerComparisonOrSubtraction(Instruction *I);
628   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
629                          Value *Addr, uint32_t TypeSize, bool IsWrite,
630                          Value *SizeArgument, bool UseCalls, uint32_t Exp);
631   void instrumentUnusualSizeOrAlignment(Instruction *I,
632                                         Instruction *InsertBefore, Value *Addr,
633                                         uint32_t TypeSize, bool IsWrite,
634                                         Value *SizeArgument, bool UseCalls,
635                                         uint32_t Exp);
636   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
637                            Value *ShadowValue, uint32_t TypeSize);
638   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
639                                  bool IsWrite, size_t AccessSizeIndex,
640                                  Value *SizeArgument, uint32_t Exp);
641   void instrumentMemIntrinsic(MemIntrinsic *MI);
642   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
643   bool suppressInstrumentationSiteForDebug(int &Instrumented);
644   bool instrumentFunction(Function &F, const TargetLibraryInfo *TLI);
645   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
646   bool maybeInsertDynamicShadowAtFunctionEntry(Function &F);
647   void markEscapedLocalAllocas(Function &F);
648 
649 private:
650   friend struct FunctionStackPoisoner;
651 
652   void initializeCallbacks(Module &M);
653 
654   bool LooksLikeCodeInBug11395(Instruction *I);
655   bool GlobalIsLinkerInitialized(GlobalVariable *G);
656   bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
657                     uint64_t TypeSize) const;
658 
659   /// Helper to cleanup per-function state.
660   struct FunctionStateRAII {
661     AddressSanitizer *Pass;
662 
663     FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
664       assert(Pass->ProcessedAllocas.empty() &&
665              "last pass forgot to clear cache");
666       assert(!Pass->LocalDynamicShadow);
667     }
668 
669     ~FunctionStateRAII() {
670       Pass->LocalDynamicShadow = nullptr;
671       Pass->ProcessedAllocas.clear();
672     }
673   };
674 
675   LLVMContext *C;
676   Triple TargetTriple;
677   int LongSize;
678   bool CompileKernel;
679   bool Recover;
680   bool UseAfterScope;
681   Type *IntptrTy;
682   ShadowMapping Mapping;
683   FunctionCallee AsanHandleNoReturnFunc;
684   FunctionCallee AsanPtrCmpFunction, AsanPtrSubFunction;
685   Constant *AsanShadowGlobal;
686 
687   // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
688   FunctionCallee AsanErrorCallback[2][2][kNumberOfAccessSizes];
689   FunctionCallee AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
690 
691   // These arrays is indexed by AccessIsWrite and Experiment.
692   FunctionCallee AsanErrorCallbackSized[2][2];
693   FunctionCallee AsanMemoryAccessCallbackSized[2][2];
694 
695   FunctionCallee AsanMemmove, AsanMemcpy, AsanMemset;
696   InlineAsm *EmptyAsm;
697   Value *LocalDynamicShadow = nullptr;
698   const GlobalsMetadata &GlobalsMD;
699   DenseMap<const AllocaInst *, bool> ProcessedAllocas;
700 };
701 
702 class AddressSanitizerLegacyPass : public FunctionPass {
703 public:
704   static char ID;
705 
706   explicit AddressSanitizerLegacyPass(bool CompileKernel = false,
707                                       bool Recover = false,
708                                       bool UseAfterScope = false)
709       : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
710         UseAfterScope(UseAfterScope) {
711     initializeAddressSanitizerLegacyPassPass(*PassRegistry::getPassRegistry());
712   }
713 
714   StringRef getPassName() const override {
715     return "AddressSanitizerFunctionPass";
716   }
717 
718   void getAnalysisUsage(AnalysisUsage &AU) const override {
719     AU.addRequired<ASanGlobalsMetadataWrapperPass>();
720     AU.addRequired<TargetLibraryInfoWrapperPass>();
721   }
722 
723   bool runOnFunction(Function &F) override {
724     GlobalsMetadata &GlobalsMD =
725         getAnalysis<ASanGlobalsMetadataWrapperPass>().getGlobalsMD();
726     const TargetLibraryInfo *TLI =
727         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
728     AddressSanitizer ASan(*F.getParent(), &GlobalsMD, CompileKernel, Recover,
729                           UseAfterScope);
730     return ASan.instrumentFunction(F, TLI);
731   }
732 
733 private:
734   bool CompileKernel;
735   bool Recover;
736   bool UseAfterScope;
737 };
738 
739 class ModuleAddressSanitizer {
740 public:
741   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
742                          bool CompileKernel = false, bool Recover = false,
743                          bool UseGlobalsGC = true, bool UseOdrIndicator = false)
744       : GlobalsMD(*GlobalsMD),
745         CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
746                                                             : CompileKernel),
747         Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
748         UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
749         // Enable aliases as they should have no downside with ODR indicators.
750         UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
751         UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
752         // Not a typo: ClWithComdat is almost completely pointless without
753         // ClUseGlobalsGC (because then it only works on modules without
754         // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
755         // and both suffer from gold PR19002 for which UseGlobalsGC constructor
756         // argument is designed as workaround. Therefore, disable both
757         // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
758         // do globals-gc.
759         UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel) {
760     C = &(M.getContext());
761     int LongSize = M.getDataLayout().getPointerSizeInBits();
762     IntptrTy = Type::getIntNTy(*C, LongSize);
763     TargetTriple = Triple(M.getTargetTriple());
764     Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
765   }
766 
767   bool instrumentModule(Module &);
768 
769 private:
770   void initializeCallbacks(Module &M);
771 
772   bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
773   void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
774                              ArrayRef<GlobalVariable *> ExtendedGlobals,
775                              ArrayRef<Constant *> MetadataInitializers);
776   void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
777                             ArrayRef<GlobalVariable *> ExtendedGlobals,
778                             ArrayRef<Constant *> MetadataInitializers,
779                             const std::string &UniqueModuleId);
780   void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
781                               ArrayRef<GlobalVariable *> ExtendedGlobals,
782                               ArrayRef<Constant *> MetadataInitializers);
783   void
784   InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
785                                      ArrayRef<GlobalVariable *> ExtendedGlobals,
786                                      ArrayRef<Constant *> MetadataInitializers);
787 
788   GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
789                                        StringRef OriginalName);
790   void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
791                                   StringRef InternalSuffix);
792   Instruction *CreateAsanModuleDtor(Module &M);
793 
794   bool ShouldInstrumentGlobal(GlobalVariable *G);
795   bool ShouldUseMachOGlobalsSection() const;
796   StringRef getGlobalMetadataSection() const;
797   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
798   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
799   size_t MinRedzoneSizeForGlobal() const {
800     return RedzoneSizeForScale(Mapping.Scale);
801   }
802   int GetAsanVersion(const Module &M) const;
803 
804   const GlobalsMetadata &GlobalsMD;
805   bool CompileKernel;
806   bool Recover;
807   bool UseGlobalsGC;
808   bool UsePrivateAlias;
809   bool UseOdrIndicator;
810   bool UseCtorComdat;
811   Type *IntptrTy;
812   LLVMContext *C;
813   Triple TargetTriple;
814   ShadowMapping Mapping;
815   FunctionCallee AsanPoisonGlobals;
816   FunctionCallee AsanUnpoisonGlobals;
817   FunctionCallee AsanRegisterGlobals;
818   FunctionCallee AsanUnregisterGlobals;
819   FunctionCallee AsanRegisterImageGlobals;
820   FunctionCallee AsanUnregisterImageGlobals;
821   FunctionCallee AsanRegisterElfGlobals;
822   FunctionCallee AsanUnregisterElfGlobals;
823 
824   Function *AsanCtorFunction = nullptr;
825   Function *AsanDtorFunction = nullptr;
826 };
827 
828 class ModuleAddressSanitizerLegacyPass : public ModulePass {
829 public:
830   static char ID;
831 
832   explicit ModuleAddressSanitizerLegacyPass(bool CompileKernel = false,
833                                             bool Recover = false,
834                                             bool UseGlobalGC = true,
835                                             bool UseOdrIndicator = false)
836       : ModulePass(ID), CompileKernel(CompileKernel), Recover(Recover),
837         UseGlobalGC(UseGlobalGC), UseOdrIndicator(UseOdrIndicator) {
838     initializeModuleAddressSanitizerLegacyPassPass(
839         *PassRegistry::getPassRegistry());
840   }
841 
842   StringRef getPassName() const override { return "ModuleAddressSanitizer"; }
843 
844   void getAnalysisUsage(AnalysisUsage &AU) const override {
845     AU.addRequired<ASanGlobalsMetadataWrapperPass>();
846   }
847 
848   bool runOnModule(Module &M) override {
849     GlobalsMetadata &GlobalsMD =
850         getAnalysis<ASanGlobalsMetadataWrapperPass>().getGlobalsMD();
851     ModuleAddressSanitizer ASanModule(M, &GlobalsMD, CompileKernel, Recover,
852                                       UseGlobalGC, UseOdrIndicator);
853     return ASanModule.instrumentModule(M);
854   }
855 
856 private:
857   bool CompileKernel;
858   bool Recover;
859   bool UseGlobalGC;
860   bool UseOdrIndicator;
861 };
862 
863 // Stack poisoning does not play well with exception handling.
864 // When an exception is thrown, we essentially bypass the code
865 // that unpoisones the stack. This is why the run-time library has
866 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
867 // stack in the interceptor. This however does not work inside the
868 // actual function which catches the exception. Most likely because the
869 // compiler hoists the load of the shadow value somewhere too high.
870 // This causes asan to report a non-existing bug on 453.povray.
871 // It sounds like an LLVM bug.
872 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
873   Function &F;
874   AddressSanitizer &ASan;
875   DIBuilder DIB;
876   LLVMContext *C;
877   Type *IntptrTy;
878   Type *IntptrPtrTy;
879   ShadowMapping Mapping;
880 
881   SmallVector<AllocaInst *, 16> AllocaVec;
882   SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
883   SmallVector<Instruction *, 8> RetVec;
884   unsigned StackAlignment;
885 
886   FunctionCallee AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
887       AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
888   FunctionCallee AsanSetShadowFunc[0x100] = {};
889   FunctionCallee AsanPoisonStackMemoryFunc, AsanUnpoisonStackMemoryFunc;
890   FunctionCallee AsanAllocaPoisonFunc, AsanAllocasUnpoisonFunc;
891 
892   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
893   struct AllocaPoisonCall {
894     IntrinsicInst *InsBefore;
895     AllocaInst *AI;
896     uint64_t Size;
897     bool DoPoison;
898   };
899   SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
900   SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
901   bool HasUntracedLifetimeIntrinsic = false;
902 
903   SmallVector<AllocaInst *, 1> DynamicAllocaVec;
904   SmallVector<IntrinsicInst *, 1> StackRestoreVec;
905   AllocaInst *DynamicAllocaLayout = nullptr;
906   IntrinsicInst *LocalEscapeCall = nullptr;
907 
908   // Maps Value to an AllocaInst from which the Value is originated.
909   using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
910   AllocaForValueMapTy AllocaForValue;
911 
912   bool HasNonEmptyInlineAsm = false;
913   bool HasReturnsTwiceCall = false;
914   std::unique_ptr<CallInst> EmptyInlineAsm;
915 
916   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
917       : F(F), ASan(ASan), DIB(*F.getParent(), /*AllowUnresolved*/ false),
918         C(ASan.C), IntptrTy(ASan.IntptrTy),
919         IntptrPtrTy(PointerType::get(IntptrTy, 0)), Mapping(ASan.Mapping),
920         StackAlignment(1 << Mapping.Scale),
921         EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
922 
923   bool runOnFunction() {
924     if (!ClStack) return false;
925 
926     if (ClRedzoneByvalArgs)
927       copyArgsPassedByValToAllocas();
928 
929     // Collect alloca, ret, lifetime instructions etc.
930     for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
931 
932     if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
933 
934     initializeCallbacks(*F.getParent());
935 
936     if (HasUntracedLifetimeIntrinsic) {
937       // If there are lifetime intrinsics which couldn't be traced back to an
938       // alloca, we may not know exactly when a variable enters scope, and
939       // therefore should "fail safe" by not poisoning them.
940       StaticAllocaPoisonCallVec.clear();
941       DynamicAllocaPoisonCallVec.clear();
942     }
943 
944     processDynamicAllocas();
945     processStaticAllocas();
946 
947     if (ClDebugStack) {
948       LLVM_DEBUG(dbgs() << F);
949     }
950     return true;
951   }
952 
953   // Arguments marked with the "byval" attribute are implicitly copied without
954   // using an alloca instruction.  To produce redzones for those arguments, we
955   // copy them a second time into memory allocated with an alloca instruction.
956   void copyArgsPassedByValToAllocas();
957 
958   // Finds all Alloca instructions and puts
959   // poisoned red zones around all of them.
960   // Then unpoison everything back before the function returns.
961   void processStaticAllocas();
962   void processDynamicAllocas();
963 
964   void createDynamicAllocasInitStorage();
965 
966   // ----------------------- Visitors.
967   /// Collect all Ret instructions.
968   void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
969 
970   /// Collect all Resume instructions.
971   void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
972 
973   /// Collect all CatchReturnInst instructions.
974   void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
975 
976   void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
977                                         Value *SavedStack) {
978     IRBuilder<> IRB(InstBefore);
979     Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
980     // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
981     // need to adjust extracted SP to compute the address of the most recent
982     // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
983     // this purpose.
984     if (!isa<ReturnInst>(InstBefore)) {
985       Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
986           InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
987           {IntptrTy});
988 
989       Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
990 
991       DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
992                                      DynamicAreaOffset);
993     }
994 
995     IRB.CreateCall(
996         AsanAllocasUnpoisonFunc,
997         {IRB.CreateLoad(IntptrTy, DynamicAllocaLayout), DynamicAreaPtr});
998   }
999 
1000   // Unpoison dynamic allocas redzones.
1001   void unpoisonDynamicAllocas() {
1002     for (auto &Ret : RetVec)
1003       unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
1004 
1005     for (auto &StackRestoreInst : StackRestoreVec)
1006       unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
1007                                        StackRestoreInst->getOperand(0));
1008   }
1009 
1010   // Deploy and poison redzones around dynamic alloca call. To do this, we
1011   // should replace this call with another one with changed parameters and
1012   // replace all its uses with new address, so
1013   //   addr = alloca type, old_size, align
1014   // is replaced by
1015   //   new_size = (old_size + additional_size) * sizeof(type)
1016   //   tmp = alloca i8, new_size, max(align, 32)
1017   //   addr = tmp + 32 (first 32 bytes are for the left redzone).
1018   // Additional_size is added to make new memory allocation contain not only
1019   // requested memory, but also left, partial and right redzones.
1020   void handleDynamicAllocaCall(AllocaInst *AI);
1021 
1022   /// Collect Alloca instructions we want (and can) handle.
1023   void visitAllocaInst(AllocaInst &AI) {
1024     if (!ASan.isInterestingAlloca(AI)) {
1025       if (AI.isStaticAlloca()) {
1026         // Skip over allocas that are present *before* the first instrumented
1027         // alloca, we don't want to move those around.
1028         if (AllocaVec.empty())
1029           return;
1030 
1031         StaticAllocasToMoveUp.push_back(&AI);
1032       }
1033       return;
1034     }
1035 
1036     StackAlignment = std::max(StackAlignment, AI.getAlignment());
1037     if (!AI.isStaticAlloca())
1038       DynamicAllocaVec.push_back(&AI);
1039     else
1040       AllocaVec.push_back(&AI);
1041   }
1042 
1043   /// Collect lifetime intrinsic calls to check for use-after-scope
1044   /// errors.
1045   void visitIntrinsicInst(IntrinsicInst &II) {
1046     Intrinsic::ID ID = II.getIntrinsicID();
1047     if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
1048     if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
1049     if (!ASan.UseAfterScope)
1050       return;
1051     if (!II.isLifetimeStartOrEnd())
1052       return;
1053     // Found lifetime intrinsic, add ASan instrumentation if necessary.
1054     auto *Size = cast<ConstantInt>(II.getArgOperand(0));
1055     // If size argument is undefined, don't do anything.
1056     if (Size->isMinusOne()) return;
1057     // Check that size doesn't saturate uint64_t and can
1058     // be stored in IntptrTy.
1059     const uint64_t SizeValue = Size->getValue().getLimitedValue();
1060     if (SizeValue == ~0ULL ||
1061         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
1062       return;
1063     // Find alloca instruction that corresponds to llvm.lifetime argument.
1064     AllocaInst *AI =
1065         llvm::findAllocaForValue(II.getArgOperand(1), AllocaForValue);
1066     if (!AI) {
1067       HasUntracedLifetimeIntrinsic = true;
1068       return;
1069     }
1070     // We're interested only in allocas we can handle.
1071     if (!ASan.isInterestingAlloca(*AI))
1072       return;
1073     bool DoPoison = (ID == Intrinsic::lifetime_end);
1074     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
1075     if (AI->isStaticAlloca())
1076       StaticAllocaPoisonCallVec.push_back(APC);
1077     else if (ClInstrumentDynamicAllocas)
1078       DynamicAllocaPoisonCallVec.push_back(APC);
1079   }
1080 
1081   void visitCallBase(CallBase &CB) {
1082     if (CallInst *CI = dyn_cast<CallInst>(&CB)) {
1083       HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1084                               !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1085                               &CB != ASan.LocalDynamicShadow;
1086       HasReturnsTwiceCall |= CI->canReturnTwice();
1087     }
1088   }
1089 
1090   // ---------------------- Helpers.
1091   void initializeCallbacks(Module &M);
1092 
1093   // Copies bytes from ShadowBytes into shadow memory for indexes where
1094   // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1095   // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1096   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1097                     IRBuilder<> &IRB, Value *ShadowBase);
1098   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1099                     size_t Begin, size_t End, IRBuilder<> &IRB,
1100                     Value *ShadowBase);
1101   void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1102                           ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1103                           size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1104 
1105   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
1106 
1107   Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1108                                bool Dynamic);
1109   PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1110                      Instruction *ThenTerm, Value *ValueIfFalse);
1111 };
1112 
1113 } // end anonymous namespace
1114 
1115 void LocationMetadata::parse(MDNode *MDN) {
1116   assert(MDN->getNumOperands() == 3);
1117   MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
1118   Filename = DIFilename->getString();
1119   LineNo = mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
1120   ColumnNo =
1121       mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
1122 }
1123 
1124 // FIXME: It would be cleaner to instead attach relevant metadata to the globals
1125 // we want to sanitize instead and reading this metadata on each pass over a
1126 // function instead of reading module level metadata at first.
1127 GlobalsMetadata::GlobalsMetadata(Module &M) {
1128   NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
1129   if (!Globals)
1130     return;
1131   for (auto MDN : Globals->operands()) {
1132     // Metadata node contains the global and the fields of "Entry".
1133     assert(MDN->getNumOperands() == 5);
1134     auto *V = mdconst::extract_or_null<Constant>(MDN->getOperand(0));
1135     // The optimizer may optimize away a global entirely.
1136     if (!V)
1137       continue;
1138     auto *StrippedV = V->stripPointerCasts();
1139     auto *GV = dyn_cast<GlobalVariable>(StrippedV);
1140     if (!GV)
1141       continue;
1142     // We can already have an entry for GV if it was merged with another
1143     // global.
1144     Entry &E = Entries[GV];
1145     if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
1146       E.SourceLoc.parse(Loc);
1147     if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
1148       E.Name = Name->getString();
1149     ConstantInt *IsDynInit = mdconst::extract<ConstantInt>(MDN->getOperand(3));
1150     E.IsDynInit |= IsDynInit->isOne();
1151     ConstantInt *IsBlacklisted =
1152         mdconst::extract<ConstantInt>(MDN->getOperand(4));
1153     E.IsBlacklisted |= IsBlacklisted->isOne();
1154   }
1155 }
1156 
1157 AnalysisKey ASanGlobalsMetadataAnalysis::Key;
1158 
1159 GlobalsMetadata ASanGlobalsMetadataAnalysis::run(Module &M,
1160                                                  ModuleAnalysisManager &AM) {
1161   return GlobalsMetadata(M);
1162 }
1163 
1164 AddressSanitizerPass::AddressSanitizerPass(bool CompileKernel, bool Recover,
1165                                            bool UseAfterScope)
1166     : CompileKernel(CompileKernel), Recover(Recover),
1167       UseAfterScope(UseAfterScope) {}
1168 
1169 PreservedAnalyses AddressSanitizerPass::run(Function &F,
1170                                             AnalysisManager<Function> &AM) {
1171   auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1172   Module &M = *F.getParent();
1173   if (auto *R = MAMProxy.getCachedResult<ASanGlobalsMetadataAnalysis>(M)) {
1174     const TargetLibraryInfo *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
1175     AddressSanitizer Sanitizer(M, R, CompileKernel, Recover, UseAfterScope);
1176     if (Sanitizer.instrumentFunction(F, TLI))
1177       return PreservedAnalyses::none();
1178     return PreservedAnalyses::all();
1179   }
1180 
1181   report_fatal_error(
1182       "The ASanGlobalsMetadataAnalysis is required to run before "
1183       "AddressSanitizer can run");
1184   return PreservedAnalyses::all();
1185 }
1186 
1187 ModuleAddressSanitizerPass::ModuleAddressSanitizerPass(bool CompileKernel,
1188                                                        bool Recover,
1189                                                        bool UseGlobalGC,
1190                                                        bool UseOdrIndicator)
1191     : CompileKernel(CompileKernel), Recover(Recover), UseGlobalGC(UseGlobalGC),
1192       UseOdrIndicator(UseOdrIndicator) {}
1193 
1194 PreservedAnalyses ModuleAddressSanitizerPass::run(Module &M,
1195                                                   AnalysisManager<Module> &AM) {
1196   GlobalsMetadata &GlobalsMD = AM.getResult<ASanGlobalsMetadataAnalysis>(M);
1197   ModuleAddressSanitizer Sanitizer(M, &GlobalsMD, CompileKernel, Recover,
1198                                    UseGlobalGC, UseOdrIndicator);
1199   if (Sanitizer.instrumentModule(M))
1200     return PreservedAnalyses::none();
1201   return PreservedAnalyses::all();
1202 }
1203 
1204 INITIALIZE_PASS(ASanGlobalsMetadataWrapperPass, "asan-globals-md",
1205                 "Read metadata to mark which globals should be instrumented "
1206                 "when running ASan.",
1207                 false, true)
1208 
1209 char AddressSanitizerLegacyPass::ID = 0;
1210 
1211 INITIALIZE_PASS_BEGIN(
1212     AddressSanitizerLegacyPass, "asan",
1213     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1214     false)
1215 INITIALIZE_PASS_DEPENDENCY(ASanGlobalsMetadataWrapperPass)
1216 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1217 INITIALIZE_PASS_END(
1218     AddressSanitizerLegacyPass, "asan",
1219     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1220     false)
1221 
1222 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
1223                                                        bool Recover,
1224                                                        bool UseAfterScope) {
1225   assert(!CompileKernel || Recover);
1226   return new AddressSanitizerLegacyPass(CompileKernel, Recover, UseAfterScope);
1227 }
1228 
1229 char ModuleAddressSanitizerLegacyPass::ID = 0;
1230 
1231 INITIALIZE_PASS(
1232     ModuleAddressSanitizerLegacyPass, "asan-module",
1233     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
1234     "ModulePass",
1235     false, false)
1236 
1237 ModulePass *llvm::createModuleAddressSanitizerLegacyPassPass(
1238     bool CompileKernel, bool Recover, bool UseGlobalsGC, bool UseOdrIndicator) {
1239   assert(!CompileKernel || Recover);
1240   return new ModuleAddressSanitizerLegacyPass(CompileKernel, Recover,
1241                                               UseGlobalsGC, UseOdrIndicator);
1242 }
1243 
1244 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
1245   size_t Res = countTrailingZeros(TypeSize / 8);
1246   assert(Res < kNumberOfAccessSizes);
1247   return Res;
1248 }
1249 
1250 /// Create a global describing a source location.
1251 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1252                                                        LocationMetadata MD) {
1253   Constant *LocData[] = {
1254       createPrivateGlobalForString(M, MD.Filename, true, kAsanGenPrefix),
1255       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1256       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1257   };
1258   auto LocStruct = ConstantStruct::getAnon(LocData);
1259   auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1260                                GlobalValue::PrivateLinkage, LocStruct,
1261                                kAsanGenPrefix);
1262   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1263   return GV;
1264 }
1265 
1266 /// Check if \p G has been created by a trusted compiler pass.
1267 static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1268   // Do not instrument @llvm.global_ctors, @llvm.used, etc.
1269   if (G->getName().startswith("llvm."))
1270     return true;
1271 
1272   // Do not instrument asan globals.
1273   if (G->getName().startswith(kAsanGenPrefix) ||
1274       G->getName().startswith(kSanCovGenPrefix) ||
1275       G->getName().startswith(kODRGenPrefix))
1276     return true;
1277 
1278   // Do not instrument gcov counter arrays.
1279   if (G->getName() == "__llvm_gcov_ctr")
1280     return true;
1281 
1282   return false;
1283 }
1284 
1285 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1286   // Shadow >> scale
1287   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
1288   if (Mapping.Offset == 0) return Shadow;
1289   // (Shadow >> scale) | offset
1290   Value *ShadowBase;
1291   if (LocalDynamicShadow)
1292     ShadowBase = LocalDynamicShadow;
1293   else
1294     ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1295   if (Mapping.OrShadowOffset)
1296     return IRB.CreateOr(Shadow, ShadowBase);
1297   else
1298     return IRB.CreateAdd(Shadow, ShadowBase);
1299 }
1300 
1301 // Instrument memset/memmove/memcpy
1302 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1303   IRBuilder<> IRB(MI);
1304   if (isa<MemTransferInst>(MI)) {
1305     IRB.CreateCall(
1306         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
1307         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1308          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1309          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1310   } else if (isa<MemSetInst>(MI)) {
1311     IRB.CreateCall(
1312         AsanMemset,
1313         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1314          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1315          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1316   }
1317   MI->eraseFromParent();
1318 }
1319 
1320 /// Check if we want (and can) handle this alloca.
1321 bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
1322   auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1323 
1324   if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1325     return PreviouslySeenAllocaInfo->getSecond();
1326 
1327   bool IsInteresting =
1328       (AI.getAllocatedType()->isSized() &&
1329        // alloca() may be called with 0 size, ignore it.
1330        ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
1331        // We are only interested in allocas not promotable to registers.
1332        // Promotable allocas are common under -O0.
1333        (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1334        // inalloca allocas are not treated as static, and we don't want
1335        // dynamic alloca instrumentation for them as well.
1336        !AI.isUsedWithInAlloca() &&
1337        // swifterror allocas are register promoted by ISel
1338        !AI.isSwiftError());
1339 
1340   ProcessedAllocas[&AI] = IsInteresting;
1341   return IsInteresting;
1342 }
1343 
1344 bool AddressSanitizer::ignoreAccess(Value *Ptr) {
1345   // Do not instrument acesses from different address spaces; we cannot deal
1346   // with them.
1347   Type *PtrTy = cast<PointerType>(Ptr->getType()->getScalarType());
1348   if (PtrTy->getPointerAddressSpace() != 0)
1349     return true;
1350 
1351   // Ignore swifterror addresses.
1352   // swifterror memory addresses are mem2reg promoted by instruction
1353   // selection. As such they cannot have regular uses like an instrumentation
1354   // function and it makes no sense to track them as memory.
1355   if (Ptr->isSwiftError())
1356     return true;
1357 
1358   // Treat memory accesses to promotable allocas as non-interesting since they
1359   // will not cause memory violations. This greatly speeds up the instrumented
1360   // executable at -O0.
1361   if (auto AI = dyn_cast_or_null<AllocaInst>(Ptr))
1362     if (ClSkipPromotableAllocas && !isInterestingAlloca(*AI))
1363       return true;
1364 
1365   return false;
1366 }
1367 
1368 void AddressSanitizer::getInterestingMemoryOperands(
1369     Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting) {
1370   // Skip memory accesses inserted by another instrumentation.
1371   if (I->hasMetadata("nosanitize"))
1372     return;
1373 
1374   // Do not instrument the load fetching the dynamic shadow address.
1375   if (LocalDynamicShadow == I)
1376     return;
1377 
1378   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1379     if (!ClInstrumentReads || ignoreAccess(LI->getPointerOperand()))
1380       return;
1381     Interesting.emplace_back(I, LI->getPointerOperandIndex(), false,
1382                              LI->getType(), LI->getAlignment());
1383   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1384     if (!ClInstrumentWrites || ignoreAccess(SI->getPointerOperand()))
1385       return;
1386     Interesting.emplace_back(I, SI->getPointerOperandIndex(), true,
1387                              SI->getValueOperand()->getType(),
1388                              SI->getAlignment());
1389   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1390     if (!ClInstrumentAtomics || ignoreAccess(RMW->getPointerOperand()))
1391       return;
1392     Interesting.emplace_back(I, RMW->getPointerOperandIndex(), true,
1393                              RMW->getValOperand()->getType(), 0);
1394   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
1395     if (!ClInstrumentAtomics || ignoreAccess(XCHG->getPointerOperand()))
1396       return;
1397     Interesting.emplace_back(I, XCHG->getPointerOperandIndex(), true,
1398                              XCHG->getCompareOperand()->getType(), 0);
1399   } else if (auto CI = dyn_cast<CallInst>(I)) {
1400     auto *F = CI->getCalledFunction();
1401     if (F && (F->getName().startswith("llvm.masked.load.") ||
1402               F->getName().startswith("llvm.masked.store."))) {
1403       bool IsWrite = F->getName().startswith("llvm.masked.store.");
1404       // Masked store has an initial operand for the value.
1405       unsigned OpOffset = IsWrite ? 1 : 0;
1406       if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)
1407         return;
1408 
1409       auto BasePtr = CI->getOperand(OpOffset);
1410       if (ignoreAccess(BasePtr))
1411         return;
1412       auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1413       unsigned Alignment = 1;
1414       // Otherwise no alignment guarantees. We probably got Undef.
1415       if (auto AlignmentConstant =
1416               dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1417         Alignment = (unsigned)AlignmentConstant->getZExtValue();
1418       Value *Mask = CI->getOperand(2 + OpOffset);
1419       Interesting.emplace_back(I, OpOffset, IsWrite, Ty, Alignment, Mask);
1420     } else {
1421       for (unsigned ArgNo = 0; ArgNo < CI->getNumArgOperands(); ArgNo++) {
1422         if (!ClInstrumentByval || !CI->isByValArgument(ArgNo) ||
1423             ignoreAccess(CI->getArgOperand(ArgNo)))
1424           continue;
1425         Type *Ty = CI->getParamByValType(ArgNo);
1426         Interesting.emplace_back(I, ArgNo, false, Ty, 1);
1427       }
1428     }
1429   }
1430 }
1431 
1432 static bool isPointerOperand(Value *V) {
1433   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1434 }
1435 
1436 // This is a rough heuristic; it may cause both false positives and
1437 // false negatives. The proper implementation requires cooperation with
1438 // the frontend.
1439 static bool isInterestingPointerComparison(Instruction *I) {
1440   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1441     if (!Cmp->isRelational())
1442       return false;
1443   } else {
1444     return false;
1445   }
1446   return isPointerOperand(I->getOperand(0)) &&
1447          isPointerOperand(I->getOperand(1));
1448 }
1449 
1450 // This is a rough heuristic; it may cause both false positives and
1451 // false negatives. The proper implementation requires cooperation with
1452 // the frontend.
1453 static bool isInterestingPointerSubtraction(Instruction *I) {
1454   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1455     if (BO->getOpcode() != Instruction::Sub)
1456       return false;
1457   } else {
1458     return false;
1459   }
1460   return isPointerOperand(I->getOperand(0)) &&
1461          isPointerOperand(I->getOperand(1));
1462 }
1463 
1464 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1465   // If a global variable does not have dynamic initialization we don't
1466   // have to instrument it.  However, if a global does not have initializer
1467   // at all, we assume it has dynamic initializer (in other TU).
1468   //
1469   // FIXME: Metadata should be attched directly to the global directly instead
1470   // of being added to llvm.asan.globals.
1471   return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
1472 }
1473 
1474 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1475     Instruction *I) {
1476   IRBuilder<> IRB(I);
1477   FunctionCallee F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1478   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1479   for (Value *&i : Param) {
1480     if (i->getType()->isPointerTy())
1481       i = IRB.CreatePointerCast(i, IntptrTy);
1482   }
1483   IRB.CreateCall(F, Param);
1484 }
1485 
1486 static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
1487                                 Instruction *InsertBefore, Value *Addr,
1488                                 unsigned Alignment, unsigned Granularity,
1489                                 uint32_t TypeSize, bool IsWrite,
1490                                 Value *SizeArgument, bool UseCalls,
1491                                 uint32_t Exp) {
1492   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1493   // if the data is properly aligned.
1494   if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1495        TypeSize == 128) &&
1496       (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1497     return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1498                                    nullptr, UseCalls, Exp);
1499   Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1500                                          IsWrite, nullptr, UseCalls, Exp);
1501 }
1502 
1503 static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1504                                         const DataLayout &DL, Type *IntptrTy,
1505                                         Value *Mask, Instruction *I,
1506                                         Value *Addr, unsigned Alignment,
1507                                         unsigned Granularity, uint32_t TypeSize,
1508                                         bool IsWrite, Value *SizeArgument,
1509                                         bool UseCalls, uint32_t Exp) {
1510   auto *VTy =
1511       cast<VectorType>(cast<PointerType>(Addr->getType())->getElementType());
1512   uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1513   unsigned Num = VTy->getNumElements();
1514   auto Zero = ConstantInt::get(IntptrTy, 0);
1515   for (unsigned Idx = 0; Idx < Num; ++Idx) {
1516     Value *InstrumentedAddress = nullptr;
1517     Instruction *InsertBefore = I;
1518     if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1519       // dyn_cast as we might get UndefValue
1520       if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1521         if (Masked->isZero())
1522           // Mask is constant false, so no instrumentation needed.
1523           continue;
1524         // If we have a true or undef value, fall through to doInstrumentAddress
1525         // with InsertBefore == I
1526       }
1527     } else {
1528       IRBuilder<> IRB(I);
1529       Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1530       Instruction *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1531       InsertBefore = ThenTerm;
1532     }
1533 
1534     IRBuilder<> IRB(InsertBefore);
1535     InstrumentedAddress =
1536         IRB.CreateGEP(VTy, Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1537     doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1538                         Granularity, ElemTypeSize, IsWrite, SizeArgument,
1539                         UseCalls, Exp);
1540   }
1541 }
1542 
1543 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1544                                      InterestingMemoryOperand &O, bool UseCalls,
1545                                      const DataLayout &DL) {
1546   Value *Addr = O.getPtr();
1547 
1548   // Optimization experiments.
1549   // The experiments can be used to evaluate potential optimizations that remove
1550   // instrumentation (assess false negatives). Instead of completely removing
1551   // some instrumentation, you set Exp to a non-zero value (mask of optimization
1552   // experiments that want to remove instrumentation of this instruction).
1553   // If Exp is non-zero, this pass will emit special calls into runtime
1554   // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1555   // make runtime terminate the program in a special way (with a different
1556   // exit status). Then you run the new compiler on a buggy corpus, collect
1557   // the special terminations (ideally, you don't see them at all -- no false
1558   // negatives) and make the decision on the optimization.
1559   uint32_t Exp = ClForceExperiment;
1560 
1561   if (ClOpt && ClOptGlobals) {
1562     // If initialization order checking is disabled, a simple access to a
1563     // dynamically initialized global is always valid.
1564     GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
1565     if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1566         isSafeAccess(ObjSizeVis, Addr, O.TypeSize)) {
1567       NumOptimizedAccessesToGlobalVar++;
1568       return;
1569     }
1570   }
1571 
1572   if (ClOpt && ClOptStack) {
1573     // A direct inbounds access to a stack variable is always valid.
1574     if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
1575         isSafeAccess(ObjSizeVis, Addr, O.TypeSize)) {
1576       NumOptimizedAccessesToStackVar++;
1577       return;
1578     }
1579   }
1580 
1581   if (O.IsWrite)
1582     NumInstrumentedWrites++;
1583   else
1584     NumInstrumentedReads++;
1585 
1586   unsigned Granularity = 1 << Mapping.Scale;
1587   if (O.MaybeMask) {
1588     instrumentMaskedLoadOrStore(this, DL, IntptrTy, O.MaybeMask, O.getInsn(),
1589                                 Addr, O.Alignment, Granularity, O.TypeSize,
1590                                 O.IsWrite, nullptr, UseCalls, Exp);
1591   } else {
1592     doInstrumentAddress(this, O.getInsn(), O.getInsn(), Addr, O.Alignment,
1593                         Granularity, O.TypeSize, O.IsWrite, nullptr, UseCalls,
1594                         Exp);
1595   }
1596 }
1597 
1598 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1599                                                  Value *Addr, bool IsWrite,
1600                                                  size_t AccessSizeIndex,
1601                                                  Value *SizeArgument,
1602                                                  uint32_t Exp) {
1603   IRBuilder<> IRB(InsertBefore);
1604   Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1605   CallInst *Call = nullptr;
1606   if (SizeArgument) {
1607     if (Exp == 0)
1608       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1609                             {Addr, SizeArgument});
1610     else
1611       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1612                             {Addr, SizeArgument, ExpVal});
1613   } else {
1614     if (Exp == 0)
1615       Call =
1616           IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1617     else
1618       Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1619                             {Addr, ExpVal});
1620   }
1621 
1622   // We don't do Call->setDoesNotReturn() because the BB already has
1623   // UnreachableInst at the end.
1624   // This EmptyAsm is required to avoid callback merge.
1625   IRB.CreateCall(EmptyAsm, {});
1626   return Call;
1627 }
1628 
1629 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1630                                            Value *ShadowValue,
1631                                            uint32_t TypeSize) {
1632   size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
1633   // Addr & (Granularity - 1)
1634   Value *LastAccessedByte =
1635       IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1636   // (Addr & (Granularity - 1)) + size - 1
1637   if (TypeSize / 8 > 1)
1638     LastAccessedByte = IRB.CreateAdd(
1639         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1640   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1641   LastAccessedByte =
1642       IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1643   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1644   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1645 }
1646 
1647 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1648                                          Instruction *InsertBefore, Value *Addr,
1649                                          uint32_t TypeSize, bool IsWrite,
1650                                          Value *SizeArgument, bool UseCalls,
1651                                          uint32_t Exp) {
1652   bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
1653 
1654   IRBuilder<> IRB(InsertBefore);
1655   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1656   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1657 
1658   if (UseCalls) {
1659     if (Exp == 0)
1660       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1661                      AddrLong);
1662     else
1663       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1664                      {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1665     return;
1666   }
1667 
1668   if (IsMyriad) {
1669     // Strip the cache bit and do range check.
1670     // AddrLong &= ~kMyriadCacheBitMask32
1671     AddrLong = IRB.CreateAnd(AddrLong, ~kMyriadCacheBitMask32);
1672     // Tag = AddrLong >> kMyriadTagShift
1673     Value *Tag = IRB.CreateLShr(AddrLong, kMyriadTagShift);
1674     // Tag == kMyriadDDRTag
1675     Value *TagCheck =
1676         IRB.CreateICmpEQ(Tag, ConstantInt::get(IntptrTy, kMyriadDDRTag));
1677 
1678     Instruction *TagCheckTerm =
1679         SplitBlockAndInsertIfThen(TagCheck, InsertBefore, false,
1680                                   MDBuilder(*C).createBranchWeights(1, 100000));
1681     assert(cast<BranchInst>(TagCheckTerm)->isUnconditional());
1682     IRB.SetInsertPoint(TagCheckTerm);
1683     InsertBefore = TagCheckTerm;
1684   }
1685 
1686   Type *ShadowTy =
1687       IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1688   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1689   Value *ShadowPtr = memToShadow(AddrLong, IRB);
1690   Value *CmpVal = Constant::getNullValue(ShadowTy);
1691   Value *ShadowValue =
1692       IRB.CreateLoad(ShadowTy, IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1693 
1694   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1695   size_t Granularity = 1ULL << Mapping.Scale;
1696   Instruction *CrashTerm = nullptr;
1697 
1698   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1699     // We use branch weights for the slow path check, to indicate that the slow
1700     // path is rarely taken. This seems to be the case for SPEC benchmarks.
1701     Instruction *CheckTerm = SplitBlockAndInsertIfThen(
1702         Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1703     assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1704     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1705     IRB.SetInsertPoint(CheckTerm);
1706     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1707     if (Recover) {
1708       CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1709     } else {
1710       BasicBlock *CrashBlock =
1711         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1712       CrashTerm = new UnreachableInst(*C, CrashBlock);
1713       BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1714       ReplaceInstWithInst(CheckTerm, NewTerm);
1715     }
1716   } else {
1717     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
1718   }
1719 
1720   Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1721                                          AccessSizeIndex, SizeArgument, Exp);
1722   Crash->setDebugLoc(OrigIns->getDebugLoc());
1723 }
1724 
1725 // Instrument unusual size or unusual alignment.
1726 // We can not do it with a single check, so we do 1-byte check for the first
1727 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1728 // to report the actual access size.
1729 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1730     Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1731     bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1732   IRBuilder<> IRB(InsertBefore);
1733   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1734   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1735   if (UseCalls) {
1736     if (Exp == 0)
1737       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1738                      {AddrLong, Size});
1739     else
1740       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1741                      {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1742   } else {
1743     Value *LastByte = IRB.CreateIntToPtr(
1744         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1745         Addr->getType());
1746     instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1747     instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
1748   }
1749 }
1750 
1751 void ModuleAddressSanitizer::poisonOneInitializer(Function &GlobalInit,
1752                                                   GlobalValue *ModuleName) {
1753   // Set up the arguments to our poison/unpoison functions.
1754   IRBuilder<> IRB(&GlobalInit.front(),
1755                   GlobalInit.front().getFirstInsertionPt());
1756 
1757   // Add a call to poison all external globals before the given function starts.
1758   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1759   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1760 
1761   // Add calls to unpoison all globals before each return instruction.
1762   for (auto &BB : GlobalInit.getBasicBlockList())
1763     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1764       CallInst::Create(AsanUnpoisonGlobals, "", RI);
1765 }
1766 
1767 void ModuleAddressSanitizer::createInitializerPoisonCalls(
1768     Module &M, GlobalValue *ModuleName) {
1769   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1770   if (!GV)
1771     return;
1772 
1773   ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1774   if (!CA)
1775     return;
1776 
1777   for (Use &OP : CA->operands()) {
1778     if (isa<ConstantAggregateZero>(OP)) continue;
1779     ConstantStruct *CS = cast<ConstantStruct>(OP);
1780 
1781     // Must have a function or null ptr.
1782     if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1783       if (F->getName() == kAsanModuleCtorName) continue;
1784       auto *Priority = cast<ConstantInt>(CS->getOperand(0));
1785       // Don't instrument CTORs that will run before asan.module_ctor.
1786       if (Priority->getLimitedValue() <= GetCtorAndDtorPriority(TargetTriple))
1787         continue;
1788       poisonOneInitializer(*F, ModuleName);
1789     }
1790   }
1791 }
1792 
1793 bool ModuleAddressSanitizer::ShouldInstrumentGlobal(GlobalVariable *G) {
1794   Type *Ty = G->getValueType();
1795   LLVM_DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1796 
1797   // FIXME: Metadata should be attched directly to the global directly instead
1798   // of being added to llvm.asan.globals.
1799   if (GlobalsMD.get(G).IsBlacklisted) return false;
1800   if (!Ty->isSized()) return false;
1801   if (!G->hasInitializer()) return false;
1802   // Only instrument globals of default address spaces
1803   if (G->getAddressSpace()) return false;
1804   if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
1805   // Two problems with thread-locals:
1806   //   - The address of the main thread's copy can't be computed at link-time.
1807   //   - Need to poison all copies, not just the main thread's one.
1808   if (G->isThreadLocal()) return false;
1809   // For now, just ignore this Global if the alignment is large.
1810   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1811 
1812   // For non-COFF targets, only instrument globals known to be defined by this
1813   // TU.
1814   // FIXME: We can instrument comdat globals on ELF if we are using the
1815   // GC-friendly metadata scheme.
1816   if (!TargetTriple.isOSBinFormatCOFF()) {
1817     if (!G->hasExactDefinition() || G->hasComdat())
1818       return false;
1819   } else {
1820     // On COFF, don't instrument non-ODR linkages.
1821     if (G->isInterposable())
1822       return false;
1823   }
1824 
1825   // If a comdat is present, it must have a selection kind that implies ODR
1826   // semantics: no duplicates, any, or exact match.
1827   if (Comdat *C = G->getComdat()) {
1828     switch (C->getSelectionKind()) {
1829     case Comdat::Any:
1830     case Comdat::ExactMatch:
1831     case Comdat::NoDuplicates:
1832       break;
1833     case Comdat::Largest:
1834     case Comdat::SameSize:
1835       return false;
1836     }
1837   }
1838 
1839   if (G->hasSection()) {
1840     // The kernel uses explicit sections for mostly special global variables
1841     // that we should not instrument. E.g. the kernel may rely on their layout
1842     // without redzones, or remove them at link time ("discard.*"), etc.
1843     if (CompileKernel)
1844       return false;
1845 
1846     StringRef Section = G->getSection();
1847 
1848     // Globals from llvm.metadata aren't emitted, do not instrument them.
1849     if (Section == "llvm.metadata") return false;
1850     // Do not instrument globals from special LLVM sections.
1851     if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
1852 
1853     // Do not instrument function pointers to initialization and termination
1854     // routines: dynamic linker will not properly handle redzones.
1855     if (Section.startswith(".preinit_array") ||
1856         Section.startswith(".init_array") ||
1857         Section.startswith(".fini_array")) {
1858       return false;
1859     }
1860 
1861     // On COFF, if the section name contains '$', it is highly likely that the
1862     // user is using section sorting to create an array of globals similar to
1863     // the way initialization callbacks are registered in .init_array and
1864     // .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones
1865     // to such globals is counterproductive, because the intent is that they
1866     // will form an array, and out-of-bounds accesses are expected.
1867     // See https://github.com/google/sanitizers/issues/305
1868     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1869     if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {
1870       LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "
1871                         << *G << "\n");
1872       return false;
1873     }
1874 
1875     if (TargetTriple.isOSBinFormatMachO()) {
1876       StringRef ParsedSegment, ParsedSection;
1877       unsigned TAA = 0, StubSize = 0;
1878       bool TAAParsed;
1879       std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1880           Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1881       assert(ErrorCode.empty() && "Invalid section specifier.");
1882 
1883       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1884       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1885       // them.
1886       if (ParsedSegment == "__OBJC" ||
1887           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1888         LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1889         return false;
1890       }
1891       // See https://github.com/google/sanitizers/issues/32
1892       // Constant CFString instances are compiled in the following way:
1893       //  -- the string buffer is emitted into
1894       //     __TEXT,__cstring,cstring_literals
1895       //  -- the constant NSConstantString structure referencing that buffer
1896       //     is placed into __DATA,__cfstring
1897       // Therefore there's no point in placing redzones into __DATA,__cfstring.
1898       // Moreover, it causes the linker to crash on OS X 10.7
1899       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1900         LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1901         return false;
1902       }
1903       // The linker merges the contents of cstring_literals and removes the
1904       // trailing zeroes.
1905       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1906         LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1907         return false;
1908       }
1909     }
1910   }
1911 
1912   return true;
1913 }
1914 
1915 // On Mach-O platforms, we emit global metadata in a separate section of the
1916 // binary in order to allow the linker to properly dead strip. This is only
1917 // supported on recent versions of ld64.
1918 bool ModuleAddressSanitizer::ShouldUseMachOGlobalsSection() const {
1919   if (!TargetTriple.isOSBinFormatMachO())
1920     return false;
1921 
1922   if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1923     return true;
1924   if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1925     return true;
1926   if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1927     return true;
1928 
1929   return false;
1930 }
1931 
1932 StringRef ModuleAddressSanitizer::getGlobalMetadataSection() const {
1933   switch (TargetTriple.getObjectFormat()) {
1934   case Triple::COFF:  return ".ASAN$GL";
1935   case Triple::ELF:   return "asan_globals";
1936   case Triple::MachO: return "__DATA,__asan_globals,regular";
1937   case Triple::Wasm:
1938   case Triple::XCOFF:
1939     report_fatal_error(
1940         "ModuleAddressSanitizer not implemented for object file format.");
1941   case Triple::UnknownObjectFormat:
1942     break;
1943   }
1944   llvm_unreachable("unsupported object format");
1945 }
1946 
1947 void ModuleAddressSanitizer::initializeCallbacks(Module &M) {
1948   IRBuilder<> IRB(*C);
1949 
1950   // Declare our poisoning and unpoisoning functions.
1951   AsanPoisonGlobals =
1952       M.getOrInsertFunction(kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy);
1953   AsanUnpoisonGlobals =
1954       M.getOrInsertFunction(kAsanUnpoisonGlobalsName, IRB.getVoidTy());
1955 
1956   // Declare functions that register/unregister globals.
1957   AsanRegisterGlobals = M.getOrInsertFunction(
1958       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
1959   AsanUnregisterGlobals = M.getOrInsertFunction(
1960       kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
1961 
1962   // Declare the functions that find globals in a shared object and then invoke
1963   // the (un)register function on them.
1964   AsanRegisterImageGlobals = M.getOrInsertFunction(
1965       kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
1966   AsanUnregisterImageGlobals = M.getOrInsertFunction(
1967       kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
1968 
1969   AsanRegisterElfGlobals =
1970       M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1971                             IntptrTy, IntptrTy, IntptrTy);
1972   AsanUnregisterElfGlobals =
1973       M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1974                             IntptrTy, IntptrTy, IntptrTy);
1975 }
1976 
1977 // Put the metadata and the instrumented global in the same group. This ensures
1978 // that the metadata is discarded if the instrumented global is discarded.
1979 void ModuleAddressSanitizer::SetComdatForGlobalMetadata(
1980     GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
1981   Module &M = *G->getParent();
1982   Comdat *C = G->getComdat();
1983   if (!C) {
1984     if (!G->hasName()) {
1985       // If G is unnamed, it must be internal. Give it an artificial name
1986       // so we can put it in a comdat.
1987       assert(G->hasLocalLinkage());
1988       G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1989     }
1990 
1991     if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1992       std::string Name = std::string(G->getName());
1993       Name += InternalSuffix;
1994       C = M.getOrInsertComdat(Name);
1995     } else {
1996       C = M.getOrInsertComdat(G->getName());
1997     }
1998 
1999     // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
2000     // linkage to internal linkage so that a symbol table entry is emitted. This
2001     // is necessary in order to create the comdat group.
2002     if (TargetTriple.isOSBinFormatCOFF()) {
2003       C->setSelectionKind(Comdat::NoDuplicates);
2004       if (G->hasPrivateLinkage())
2005         G->setLinkage(GlobalValue::InternalLinkage);
2006     }
2007     G->setComdat(C);
2008   }
2009 
2010   assert(G->hasComdat());
2011   Metadata->setComdat(G->getComdat());
2012 }
2013 
2014 // Create a separate metadata global and put it in the appropriate ASan
2015 // global registration section.
2016 GlobalVariable *
2017 ModuleAddressSanitizer::CreateMetadataGlobal(Module &M, Constant *Initializer,
2018                                              StringRef OriginalName) {
2019   auto Linkage = TargetTriple.isOSBinFormatMachO()
2020                      ? GlobalVariable::InternalLinkage
2021                      : GlobalVariable::PrivateLinkage;
2022   GlobalVariable *Metadata = new GlobalVariable(
2023       M, Initializer->getType(), false, Linkage, Initializer,
2024       Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
2025   Metadata->setSection(getGlobalMetadataSection());
2026   return Metadata;
2027 }
2028 
2029 Instruction *ModuleAddressSanitizer::CreateAsanModuleDtor(Module &M) {
2030   AsanDtorFunction =
2031       Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
2032                        GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
2033   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
2034 
2035   return ReturnInst::Create(*C, AsanDtorBB);
2036 }
2037 
2038 void ModuleAddressSanitizer::InstrumentGlobalsCOFF(
2039     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2040     ArrayRef<Constant *> MetadataInitializers) {
2041   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2042   auto &DL = M.getDataLayout();
2043 
2044   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2045   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2046     Constant *Initializer = MetadataInitializers[i];
2047     GlobalVariable *G = ExtendedGlobals[i];
2048     GlobalVariable *Metadata =
2049         CreateMetadataGlobal(M, Initializer, G->getName());
2050     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2051     Metadata->setMetadata(LLVMContext::MD_associated, MD);
2052     MetadataGlobals[i] = Metadata;
2053 
2054     // The MSVC linker always inserts padding when linking incrementally. We
2055     // cope with that by aligning each struct to its size, which must be a power
2056     // of two.
2057     unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
2058     assert(isPowerOf2_32(SizeOfGlobalStruct) &&
2059            "global metadata will not be padded appropriately");
2060     Metadata->setAlignment(assumeAligned(SizeOfGlobalStruct));
2061 
2062     SetComdatForGlobalMetadata(G, Metadata, "");
2063   }
2064 
2065   // Update llvm.compiler.used, adding the new metadata globals. This is
2066   // needed so that during LTO these variables stay alive.
2067   if (!MetadataGlobals.empty())
2068     appendToCompilerUsed(M, MetadataGlobals);
2069 }
2070 
2071 void ModuleAddressSanitizer::InstrumentGlobalsELF(
2072     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2073     ArrayRef<Constant *> MetadataInitializers,
2074     const std::string &UniqueModuleId) {
2075   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2076 
2077   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2078   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2079     GlobalVariable *G = ExtendedGlobals[i];
2080     GlobalVariable *Metadata =
2081         CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
2082     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2083     Metadata->setMetadata(LLVMContext::MD_associated, MD);
2084     MetadataGlobals[i] = Metadata;
2085 
2086     SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
2087   }
2088 
2089   // This should never be called when there are no globals, by the logic that
2090   // computes the UniqueModuleId string, which is "" when there are no globals.
2091   // It's important that this path is only used when there are actually some
2092   // globals, because that means that there will certainly be a live
2093   // `asan_globals` input section at link time and thus `__start_asan_globals`
2094   // and `__stop_asan_globals` symbols will definitely be defined at link time.
2095   // This means there's no need for the references to them to be weak, which
2096   // enables better code generation because ExternalWeakLinkage implies
2097   // isInterposable() and thus requires GOT indirection for PIC.  Since these
2098   // are known-defined hidden/dso_local symbols, direct PIC accesses without
2099   // dynamic relocation are always sufficient.
2100   assert(!MetadataGlobals.empty());
2101   assert(!UniqueModuleId.empty());
2102 
2103   // Update llvm.compiler.used, adding the new metadata globals. This is
2104   // needed so that during LTO these variables stay alive.
2105   appendToCompilerUsed(M, MetadataGlobals);
2106 
2107   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2108   // to look up the loaded image that contains it. Second, we can store in it
2109   // whether registration has already occurred, to prevent duplicate
2110   // registration.
2111   //
2112   // Common linkage ensures that there is only one global per shared library.
2113   GlobalVariable *RegisteredFlag = new GlobalVariable(
2114       M, IntptrTy, false, GlobalVariable::CommonLinkage,
2115       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2116   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2117 
2118   // Create start and stop symbols.  These are known to be defined by
2119   // the linker, see comment above.
2120   auto MakeStartStopGV = [&](const char *Prefix) {
2121     GlobalVariable *StartStop =
2122         new GlobalVariable(M, IntptrTy, false, GlobalVariable::ExternalLinkage,
2123                            nullptr, Prefix + getGlobalMetadataSection());
2124     StartStop->setVisibility(GlobalVariable::HiddenVisibility);
2125     assert(StartStop->isImplicitDSOLocal());
2126     return StartStop;
2127   };
2128   GlobalVariable *StartELFMetadata = MakeStartStopGV("__start_");
2129   GlobalVariable *StopELFMetadata = MakeStartStopGV("__stop_");
2130 
2131   // Create a call to register the globals with the runtime.
2132   IRB.CreateCall(AsanRegisterElfGlobals,
2133                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2134                   IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2135                   IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2136 
2137   // We also need to unregister globals at the end, e.g., when a shared library
2138   // gets closed.
2139   IRBuilder<> IRB_Dtor(CreateAsanModuleDtor(M));
2140   IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
2141                       {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2142                        IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2143                        IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2144 }
2145 
2146 void ModuleAddressSanitizer::InstrumentGlobalsMachO(
2147     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2148     ArrayRef<Constant *> MetadataInitializers) {
2149   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2150 
2151   // On recent Mach-O platforms, use a structure which binds the liveness of
2152   // the global variable to the metadata struct. Keep the list of "Liveness" GV
2153   // created to be added to llvm.compiler.used
2154   StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
2155   SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
2156 
2157   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2158     Constant *Initializer = MetadataInitializers[i];
2159     GlobalVariable *G = ExtendedGlobals[i];
2160     GlobalVariable *Metadata =
2161         CreateMetadataGlobal(M, Initializer, G->getName());
2162 
2163     // On recent Mach-O platforms, we emit the global metadata in a way that
2164     // allows the linker to properly strip dead globals.
2165     auto LivenessBinder =
2166         ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
2167                             ConstantExpr::getPointerCast(Metadata, IntptrTy));
2168     GlobalVariable *Liveness = new GlobalVariable(
2169         M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2170         Twine("__asan_binder_") + G->getName());
2171     Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2172     LivenessGlobals[i] = Liveness;
2173   }
2174 
2175   // Update llvm.compiler.used, adding the new liveness globals. This is
2176   // needed so that during LTO these variables stay alive. The alternative
2177   // would be to have the linker handling the LTO symbols, but libLTO
2178   // current API does not expose access to the section for each symbol.
2179   if (!LivenessGlobals.empty())
2180     appendToCompilerUsed(M, LivenessGlobals);
2181 
2182   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2183   // to look up the loaded image that contains it. Second, we can store in it
2184   // whether registration has already occurred, to prevent duplicate
2185   // registration.
2186   //
2187   // common linkage ensures that there is only one global per shared library.
2188   GlobalVariable *RegisteredFlag = new GlobalVariable(
2189       M, IntptrTy, false, GlobalVariable::CommonLinkage,
2190       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2191   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2192 
2193   IRB.CreateCall(AsanRegisterImageGlobals,
2194                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2195 
2196   // We also need to unregister globals at the end, e.g., when a shared library
2197   // gets closed.
2198   IRBuilder<> IRB_Dtor(CreateAsanModuleDtor(M));
2199   IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
2200                       {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2201 }
2202 
2203 void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(
2204     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2205     ArrayRef<Constant *> MetadataInitializers) {
2206   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2207   unsigned N = ExtendedGlobals.size();
2208   assert(N > 0);
2209 
2210   // On platforms that don't have a custom metadata section, we emit an array
2211   // of global metadata structures.
2212   ArrayType *ArrayOfGlobalStructTy =
2213       ArrayType::get(MetadataInitializers[0]->getType(), N);
2214   auto AllGlobals = new GlobalVariable(
2215       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2216       ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
2217   if (Mapping.Scale > 3)
2218     AllGlobals->setAlignment(Align(1ULL << Mapping.Scale));
2219 
2220   IRB.CreateCall(AsanRegisterGlobals,
2221                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2222                   ConstantInt::get(IntptrTy, N)});
2223 
2224   // We also need to unregister globals at the end, e.g., when a shared library
2225   // gets closed.
2226   IRBuilder<> IRB_Dtor(CreateAsanModuleDtor(M));
2227   IRB_Dtor.CreateCall(AsanUnregisterGlobals,
2228                       {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2229                        ConstantInt::get(IntptrTy, N)});
2230 }
2231 
2232 // This function replaces all global variables with new variables that have
2233 // trailing redzones. It also creates a function that poisons
2234 // redzones and inserts this function into llvm.global_ctors.
2235 // Sets *CtorComdat to true if the global registration code emitted into the
2236 // asan constructor is comdat-compatible.
2237 bool ModuleAddressSanitizer::InstrumentGlobals(IRBuilder<> &IRB, Module &M,
2238                                                bool *CtorComdat) {
2239   *CtorComdat = false;
2240 
2241   SmallVector<GlobalVariable *, 16> GlobalsToChange;
2242 
2243   for (auto &G : M.globals()) {
2244     if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
2245   }
2246 
2247   size_t n = GlobalsToChange.size();
2248   if (n == 0) {
2249     *CtorComdat = true;
2250     return false;
2251   }
2252 
2253   auto &DL = M.getDataLayout();
2254 
2255   // A global is described by a structure
2256   //   size_t beg;
2257   //   size_t size;
2258   //   size_t size_with_redzone;
2259   //   const char *name;
2260   //   const char *module_name;
2261   //   size_t has_dynamic_init;
2262   //   void *source_location;
2263   //   size_t odr_indicator;
2264   // We initialize an array of such structures and pass it to a run-time call.
2265   StructType *GlobalStructTy =
2266       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
2267                       IntptrTy, IntptrTy, IntptrTy);
2268   SmallVector<GlobalVariable *, 16> NewGlobals(n);
2269   SmallVector<Constant *, 16> Initializers(n);
2270 
2271   bool HasDynamicallyInitializedGlobals = false;
2272 
2273   // We shouldn't merge same module names, as this string serves as unique
2274   // module ID in runtime.
2275   GlobalVariable *ModuleName = createPrivateGlobalForString(
2276       M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
2277 
2278   for (size_t i = 0; i < n; i++) {
2279     static const uint64_t kMaxGlobalRedzone = 1 << 18;
2280     GlobalVariable *G = GlobalsToChange[i];
2281 
2282     // FIXME: Metadata should be attched directly to the global directly instead
2283     // of being added to llvm.asan.globals.
2284     auto MD = GlobalsMD.get(G);
2285     StringRef NameForGlobal = G->getName();
2286     // Create string holding the global name (use global name from metadata
2287     // if it's available, otherwise just write the name of global variable).
2288     GlobalVariable *Name = createPrivateGlobalForString(
2289         M, MD.Name.empty() ? NameForGlobal : MD.Name,
2290         /*AllowMerging*/ true, kAsanGenPrefix);
2291 
2292     Type *Ty = G->getValueType();
2293     uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
2294     uint64_t MinRZ = MinRedzoneSizeForGlobal();
2295     // MinRZ <= RZ <= kMaxGlobalRedzone
2296     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
2297     uint64_t RZ = std::max(
2298         MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
2299     uint64_t RightRedzoneSize = RZ;
2300     // Round up to MinRZ
2301     if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
2302     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
2303     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2304 
2305     StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2306     Constant *NewInitializer = ConstantStruct::get(
2307         NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
2308 
2309     // Create a new global variable with enough space for a redzone.
2310     GlobalValue::LinkageTypes Linkage = G->getLinkage();
2311     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2312       Linkage = GlobalValue::InternalLinkage;
2313     GlobalVariable *NewGlobal =
2314         new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2315                            "", G, G->getThreadLocalMode());
2316     NewGlobal->copyAttributesFrom(G);
2317     NewGlobal->setComdat(G->getComdat());
2318     NewGlobal->setAlignment(MaybeAlign(MinRZ));
2319     // Don't fold globals with redzones. ODR violation detector and redzone
2320     // poisoning implicitly creates a dependence on the global's address, so it
2321     // is no longer valid for it to be marked unnamed_addr.
2322     NewGlobal->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2323 
2324     // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2325     if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2326         G->isConstant()) {
2327       auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2328       if (Seq && Seq->isCString())
2329         NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2330     }
2331 
2332     // Transfer the debug info.  The payload starts at offset zero so we can
2333     // copy the debug info over as is.
2334     SmallVector<DIGlobalVariableExpression *, 1> GVs;
2335     G->getDebugInfo(GVs);
2336     for (auto *GV : GVs)
2337       NewGlobal->addDebugInfo(GV);
2338 
2339     Value *Indices2[2];
2340     Indices2[0] = IRB.getInt32(0);
2341     Indices2[1] = IRB.getInt32(0);
2342 
2343     G->replaceAllUsesWith(
2344         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
2345     NewGlobal->takeName(G);
2346     G->eraseFromParent();
2347     NewGlobals[i] = NewGlobal;
2348 
2349     Constant *SourceLoc;
2350     if (!MD.SourceLoc.empty()) {
2351       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2352       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2353     } else {
2354       SourceLoc = ConstantInt::get(IntptrTy, 0);
2355     }
2356 
2357     Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2358     GlobalValue *InstrumentedGlobal = NewGlobal;
2359 
2360     bool CanUsePrivateAliases =
2361         TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2362         TargetTriple.isOSBinFormatWasm();
2363     if (CanUsePrivateAliases && UsePrivateAlias) {
2364       // Create local alias for NewGlobal to avoid crash on ODR between
2365       // instrumented and non-instrumented libraries.
2366       InstrumentedGlobal =
2367           GlobalAlias::create(GlobalValue::PrivateLinkage, "", NewGlobal);
2368     }
2369 
2370     // ODR should not happen for local linkage.
2371     if (NewGlobal->hasLocalLinkage()) {
2372       ODRIndicator = ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1),
2373                                                IRB.getInt8PtrTy());
2374     } else if (UseOdrIndicator) {
2375       // With local aliases, we need to provide another externally visible
2376       // symbol __odr_asan_XXX to detect ODR violation.
2377       auto *ODRIndicatorSym =
2378           new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2379                              Constant::getNullValue(IRB.getInt8Ty()),
2380                              kODRGenPrefix + NameForGlobal, nullptr,
2381                              NewGlobal->getThreadLocalMode());
2382 
2383       // Set meaningful attributes for indicator symbol.
2384       ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2385       ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2386       ODRIndicatorSym->setAlignment(Align(1));
2387       ODRIndicator = ODRIndicatorSym;
2388     }
2389 
2390     Constant *Initializer = ConstantStruct::get(
2391         GlobalStructTy,
2392         ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
2393         ConstantInt::get(IntptrTy, SizeInBytes),
2394         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2395         ConstantExpr::getPointerCast(Name, IntptrTy),
2396         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
2397         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
2398         ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
2399 
2400     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
2401 
2402     LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
2403 
2404     Initializers[i] = Initializer;
2405   }
2406 
2407   // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2408   // ConstantMerge'ing them.
2409   SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2410   for (size_t i = 0; i < n; i++) {
2411     GlobalVariable *G = NewGlobals[i];
2412     if (G->getName().empty()) continue;
2413     GlobalsToAddToUsedList.push_back(G);
2414   }
2415   appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2416 
2417   std::string ELFUniqueModuleId =
2418       (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2419                                                         : "";
2420 
2421   if (!ELFUniqueModuleId.empty()) {
2422     InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2423     *CtorComdat = true;
2424   } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2425     InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2426   } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2427     InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2428   } else {
2429     InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2430   }
2431 
2432   // Create calls for poisoning before initializers run and unpoisoning after.
2433   if (HasDynamicallyInitializedGlobals)
2434     createInitializerPoisonCalls(M, ModuleName);
2435 
2436   LLVM_DEBUG(dbgs() << M);
2437   return true;
2438 }
2439 
2440 int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
2441   int LongSize = M.getDataLayout().getPointerSizeInBits();
2442   bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2443   int Version = 8;
2444   // 32-bit Android is one version ahead because of the switch to dynamic
2445   // shadow.
2446   Version += (LongSize == 32 && isAndroid);
2447   return Version;
2448 }
2449 
2450 bool ModuleAddressSanitizer::instrumentModule(Module &M) {
2451   initializeCallbacks(M);
2452 
2453   // Create a module constructor. A destructor is created lazily because not all
2454   // platforms, and not all modules need it.
2455   if (CompileKernel) {
2456     // The kernel always builds with its own runtime, and therefore does not
2457     // need the init and version check calls.
2458     AsanCtorFunction = createSanitizerCtor(M, kAsanModuleCtorName);
2459   } else {
2460     std::string AsanVersion = std::to_string(GetAsanVersion(M));
2461     std::string VersionCheckName =
2462         ClInsertVersionCheck ? (kAsanVersionCheckNamePrefix + AsanVersion) : "";
2463     std::tie(AsanCtorFunction, std::ignore) =
2464         createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName,
2465                                             kAsanInitName, /*InitArgTypes=*/{},
2466                                             /*InitArgs=*/{}, VersionCheckName);
2467   }
2468 
2469   bool CtorComdat = true;
2470   if (ClGlobals) {
2471     IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2472     InstrumentGlobals(IRB, M, &CtorComdat);
2473   }
2474 
2475   const uint64_t Priority = GetCtorAndDtorPriority(TargetTriple);
2476 
2477   // Put the constructor and destructor in comdat if both
2478   // (1) global instrumentation is not TU-specific
2479   // (2) target is ELF.
2480   if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2481     AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2482     appendToGlobalCtors(M, AsanCtorFunction, Priority, AsanCtorFunction);
2483     if (AsanDtorFunction) {
2484       AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2485       appendToGlobalDtors(M, AsanDtorFunction, Priority, AsanDtorFunction);
2486     }
2487   } else {
2488     appendToGlobalCtors(M, AsanCtorFunction, Priority);
2489     if (AsanDtorFunction)
2490       appendToGlobalDtors(M, AsanDtorFunction, Priority);
2491   }
2492 
2493   return true;
2494 }
2495 
2496 void AddressSanitizer::initializeCallbacks(Module &M) {
2497   IRBuilder<> IRB(*C);
2498   // Create __asan_report* callbacks.
2499   // IsWrite, TypeSize and Exp are encoded in the function name.
2500   for (int Exp = 0; Exp < 2; Exp++) {
2501     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2502       const std::string TypeStr = AccessIsWrite ? "store" : "load";
2503       const std::string ExpStr = Exp ? "exp_" : "";
2504       const std::string EndingStr = Recover ? "_noabort" : "";
2505 
2506       SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2507       SmallVector<Type *, 2> Args1{1, IntptrTy};
2508       if (Exp) {
2509         Type *ExpType = Type::getInt32Ty(*C);
2510         Args2.push_back(ExpType);
2511         Args1.push_back(ExpType);
2512       }
2513       AsanErrorCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2514           kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2515           FunctionType::get(IRB.getVoidTy(), Args2, false));
2516 
2517       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2518           ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2519           FunctionType::get(IRB.getVoidTy(), Args2, false));
2520 
2521       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2522            AccessSizeIndex++) {
2523         const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2524         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2525             M.getOrInsertFunction(
2526                 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2527                 FunctionType::get(IRB.getVoidTy(), Args1, false));
2528 
2529         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2530             M.getOrInsertFunction(
2531                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2532                 FunctionType::get(IRB.getVoidTy(), Args1, false));
2533       }
2534     }
2535   }
2536 
2537   const std::string MemIntrinCallbackPrefix =
2538       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
2539   AsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
2540                                       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2541                                       IRB.getInt8PtrTy(), IntptrTy);
2542   AsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
2543                                      IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2544                                      IRB.getInt8PtrTy(), IntptrTy);
2545   AsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
2546                                      IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2547                                      IRB.getInt32Ty(), IntptrTy);
2548 
2549   AsanHandleNoReturnFunc =
2550       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy());
2551 
2552   AsanPtrCmpFunction =
2553       M.getOrInsertFunction(kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy);
2554   AsanPtrSubFunction =
2555       M.getOrInsertFunction(kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy);
2556   // We insert an empty inline asm after __asan_report* to avoid callback merge.
2557   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2558                             StringRef(""), StringRef(""),
2559                             /*hasSideEffects=*/true);
2560   if (Mapping.InGlobal)
2561     AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2562                                            ArrayType::get(IRB.getInt8Ty(), 0));
2563 }
2564 
2565 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2566   // For each NSObject descendant having a +load method, this method is invoked
2567   // by the ObjC runtime before any of the static constructors is called.
2568   // Therefore we need to instrument such methods with a call to __asan_init
2569   // at the beginning in order to initialize our runtime before any access to
2570   // the shadow memory.
2571   // We cannot just ignore these methods, because they may call other
2572   // instrumented functions.
2573   if (F.getName().find(" load]") != std::string::npos) {
2574     FunctionCallee AsanInitFunction =
2575         declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
2576     IRBuilder<> IRB(&F.front(), F.front().begin());
2577     IRB.CreateCall(AsanInitFunction, {});
2578     return true;
2579   }
2580   return false;
2581 }
2582 
2583 bool AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2584   // Generate code only when dynamic addressing is needed.
2585   if (Mapping.Offset != kDynamicShadowSentinel)
2586     return false;
2587 
2588   IRBuilder<> IRB(&F.front().front());
2589   if (Mapping.InGlobal) {
2590     if (ClWithIfuncSuppressRemat) {
2591       // An empty inline asm with input reg == output reg.
2592       // An opaque pointer-to-int cast, basically.
2593       InlineAsm *Asm = InlineAsm::get(
2594           FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2595           StringRef(""), StringRef("=r,0"),
2596           /*hasSideEffects=*/false);
2597       LocalDynamicShadow =
2598           IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2599     } else {
2600       LocalDynamicShadow =
2601           IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2602     }
2603   } else {
2604     Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2605         kAsanShadowMemoryDynamicAddress, IntptrTy);
2606     LocalDynamicShadow = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
2607   }
2608   return true;
2609 }
2610 
2611 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2612   // Find the one possible call to llvm.localescape and pre-mark allocas passed
2613   // to it as uninteresting. This assumes we haven't started processing allocas
2614   // yet. This check is done up front because iterating the use list in
2615   // isInterestingAlloca would be algorithmically slower.
2616   assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2617 
2618   // Try to get the declaration of llvm.localescape. If it's not in the module,
2619   // we can exit early.
2620   if (!F.getParent()->getFunction("llvm.localescape")) return;
2621 
2622   // Look for a call to llvm.localescape call in the entry block. It can't be in
2623   // any other block.
2624   for (Instruction &I : F.getEntryBlock()) {
2625     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2626     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2627       // We found a call. Mark all the allocas passed in as uninteresting.
2628       for (Value *Arg : II->arg_operands()) {
2629         AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2630         assert(AI && AI->isStaticAlloca() &&
2631                "non-static alloca arg to localescape");
2632         ProcessedAllocas[AI] = false;
2633       }
2634       break;
2635     }
2636   }
2637 }
2638 
2639 bool AddressSanitizer::suppressInstrumentationSiteForDebug(int &Instrumented) {
2640   bool ShouldInstrument =
2641       ClDebugMin < 0 || ClDebugMax < 0 ||
2642       (Instrumented >= ClDebugMin && Instrumented <= ClDebugMax);
2643   Instrumented++;
2644   return !ShouldInstrument;
2645 }
2646 
2647 bool AddressSanitizer::instrumentFunction(Function &F,
2648                                           const TargetLibraryInfo *TLI) {
2649   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2650   if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2651   if (F.getName().startswith("__asan_")) return false;
2652 
2653   bool FunctionModified = false;
2654 
2655   // If needed, insert __asan_init before checking for SanitizeAddress attr.
2656   // This function needs to be called even if the function body is not
2657   // instrumented.
2658   if (maybeInsertAsanInitAtFunctionEntry(F))
2659     FunctionModified = true;
2660 
2661   // Leave if the function doesn't need instrumentation.
2662   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2663 
2664   LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2665 
2666   initializeCallbacks(*F.getParent());
2667 
2668   FunctionStateRAII CleanupObj(this);
2669 
2670   FunctionModified |= maybeInsertDynamicShadowAtFunctionEntry(F);
2671 
2672   // We can't instrument allocas used with llvm.localescape. Only static allocas
2673   // can be passed to that intrinsic.
2674   markEscapedLocalAllocas(F);
2675 
2676   // We want to instrument every address only once per basic block (unless there
2677   // are calls between uses).
2678   SmallPtrSet<Value *, 16> TempsToInstrument;
2679   SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;
2680   SmallVector<MemIntrinsic *, 16> IntrinToInstrument;
2681   SmallVector<Instruction *, 8> NoReturnCalls;
2682   SmallVector<BasicBlock *, 16> AllBlocks;
2683   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2684   int NumAllocas = 0;
2685 
2686   // Fill the set of memory operations to instrument.
2687   for (auto &BB : F) {
2688     AllBlocks.push_back(&BB);
2689     TempsToInstrument.clear();
2690     int NumInsnsPerBB = 0;
2691     for (auto &Inst : BB) {
2692       if (LooksLikeCodeInBug11395(&Inst)) return false;
2693       SmallVector<InterestingMemoryOperand, 1> InterestingOperands;
2694       getInterestingMemoryOperands(&Inst, InterestingOperands);
2695 
2696       if (!InterestingOperands.empty()) {
2697         for (auto &Operand : InterestingOperands) {
2698           if (ClOpt && ClOptSameTemp) {
2699             Value *Ptr = Operand.getPtr();
2700             // If we have a mask, skip instrumentation if we've already
2701             // instrumented the full object. But don't add to TempsToInstrument
2702             // because we might get another load/store with a different mask.
2703             if (Operand.MaybeMask) {
2704               if (TempsToInstrument.count(Ptr))
2705                 continue; // We've seen this (whole) temp in the current BB.
2706             } else {
2707               if (!TempsToInstrument.insert(Ptr).second)
2708                 continue; // We've seen this temp in the current BB.
2709             }
2710           }
2711           OperandsToInstrument.push_back(Operand);
2712           NumInsnsPerBB++;
2713         }
2714       } else if (((ClInvalidPointerPairs || ClInvalidPointerCmp) &&
2715                   isInterestingPointerComparison(&Inst)) ||
2716                  ((ClInvalidPointerPairs || ClInvalidPointerSub) &&
2717                   isInterestingPointerSubtraction(&Inst))) {
2718         PointerComparisonsOrSubtracts.push_back(&Inst);
2719       } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst)) {
2720         // ok, take it.
2721         IntrinToInstrument.push_back(MI);
2722         NumInsnsPerBB++;
2723       } else {
2724         if (isa<AllocaInst>(Inst)) NumAllocas++;
2725         if (auto *CB = dyn_cast<CallBase>(&Inst)) {
2726           // A call inside BB.
2727           TempsToInstrument.clear();
2728           if (CB->doesNotReturn() && !CB->hasMetadata("nosanitize"))
2729             NoReturnCalls.push_back(CB);
2730         }
2731         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2732           maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
2733       }
2734       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2735     }
2736   }
2737 
2738   bool UseCalls = (ClInstrumentationWithCallsThreshold >= 0 &&
2739                    OperandsToInstrument.size() + IntrinToInstrument.size() >
2740                        (unsigned)ClInstrumentationWithCallsThreshold);
2741   const DataLayout &DL = F.getParent()->getDataLayout();
2742   ObjectSizeOpts ObjSizeOpts;
2743   ObjSizeOpts.RoundToAlign = true;
2744   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
2745 
2746   // Instrument.
2747   int NumInstrumented = 0;
2748   for (auto &Operand : OperandsToInstrument) {
2749     if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2750       instrumentMop(ObjSizeVis, Operand, UseCalls,
2751                     F.getParent()->getDataLayout());
2752     FunctionModified = true;
2753   }
2754   for (auto Inst : IntrinToInstrument) {
2755     if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2756       instrumentMemIntrinsic(Inst);
2757     FunctionModified = true;
2758   }
2759 
2760   FunctionStackPoisoner FSP(F, *this);
2761   bool ChangedStack = FSP.runOnFunction();
2762 
2763   // We must unpoison the stack before NoReturn calls (throw, _exit, etc).
2764   // See e.g. https://github.com/google/sanitizers/issues/37
2765   for (auto CI : NoReturnCalls) {
2766     IRBuilder<> IRB(CI);
2767     IRB.CreateCall(AsanHandleNoReturnFunc, {});
2768   }
2769 
2770   for (auto Inst : PointerComparisonsOrSubtracts) {
2771     instrumentPointerComparisonOrSubtraction(Inst);
2772     FunctionModified = true;
2773   }
2774 
2775   if (ChangedStack || !NoReturnCalls.empty())
2776     FunctionModified = true;
2777 
2778   LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2779                     << F << "\n");
2780 
2781   return FunctionModified;
2782 }
2783 
2784 // Workaround for bug 11395: we don't want to instrument stack in functions
2785 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2786 // FIXME: remove once the bug 11395 is fixed.
2787 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2788   if (LongSize != 32) return false;
2789   CallInst *CI = dyn_cast<CallInst>(I);
2790   if (!CI || !CI->isInlineAsm()) return false;
2791   if (CI->getNumArgOperands() <= 5) return false;
2792   // We have inline assembly with quite a few arguments.
2793   return true;
2794 }
2795 
2796 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2797   IRBuilder<> IRB(*C);
2798   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2799     std::string Suffix = itostr(i);
2800     AsanStackMallocFunc[i] = M.getOrInsertFunction(
2801         kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy);
2802     AsanStackFreeFunc[i] =
2803         M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2804                               IRB.getVoidTy(), IntptrTy, IntptrTy);
2805   }
2806   if (ASan.UseAfterScope) {
2807     AsanPoisonStackMemoryFunc = M.getOrInsertFunction(
2808         kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2809     AsanUnpoisonStackMemoryFunc = M.getOrInsertFunction(
2810         kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2811   }
2812 
2813   for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2814     std::ostringstream Name;
2815     Name << kAsanSetShadowPrefix;
2816     Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2817     AsanSetShadowFunc[Val] =
2818         M.getOrInsertFunction(Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy);
2819   }
2820 
2821   AsanAllocaPoisonFunc = M.getOrInsertFunction(
2822       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
2823   AsanAllocasUnpoisonFunc = M.getOrInsertFunction(
2824       kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
2825 }
2826 
2827 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2828                                                ArrayRef<uint8_t> ShadowBytes,
2829                                                size_t Begin, size_t End,
2830                                                IRBuilder<> &IRB,
2831                                                Value *ShadowBase) {
2832   if (Begin >= End)
2833     return;
2834 
2835   const size_t LargestStoreSizeInBytes =
2836       std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2837 
2838   const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2839 
2840   // Poison given range in shadow using larges store size with out leading and
2841   // trailing zeros in ShadowMask. Zeros never change, so they need neither
2842   // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2843   // middle of a store.
2844   for (size_t i = Begin; i < End;) {
2845     if (!ShadowMask[i]) {
2846       assert(!ShadowBytes[i]);
2847       ++i;
2848       continue;
2849     }
2850 
2851     size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2852     // Fit store size into the range.
2853     while (StoreSizeInBytes > End - i)
2854       StoreSizeInBytes /= 2;
2855 
2856     // Minimize store size by trimming trailing zeros.
2857     for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2858       while (j <= StoreSizeInBytes / 2)
2859         StoreSizeInBytes /= 2;
2860     }
2861 
2862     uint64_t Val = 0;
2863     for (size_t j = 0; j < StoreSizeInBytes; j++) {
2864       if (IsLittleEndian)
2865         Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2866       else
2867         Val = (Val << 8) | ShadowBytes[i + j];
2868     }
2869 
2870     Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2871     Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
2872     IRB.CreateAlignedStore(
2873         Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()),
2874         Align(1));
2875 
2876     i += StoreSizeInBytes;
2877   }
2878 }
2879 
2880 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2881                                          ArrayRef<uint8_t> ShadowBytes,
2882                                          IRBuilder<> &IRB, Value *ShadowBase) {
2883   copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2884 }
2885 
2886 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2887                                          ArrayRef<uint8_t> ShadowBytes,
2888                                          size_t Begin, size_t End,
2889                                          IRBuilder<> &IRB, Value *ShadowBase) {
2890   assert(ShadowMask.size() == ShadowBytes.size());
2891   size_t Done = Begin;
2892   for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2893     if (!ShadowMask[i]) {
2894       assert(!ShadowBytes[i]);
2895       continue;
2896     }
2897     uint8_t Val = ShadowBytes[i];
2898     if (!AsanSetShadowFunc[Val])
2899       continue;
2900 
2901     // Skip same values.
2902     for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2903     }
2904 
2905     if (j - i >= ClMaxInlinePoisoningSize) {
2906       copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2907       IRB.CreateCall(AsanSetShadowFunc[Val],
2908                      {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2909                       ConstantInt::get(IntptrTy, j - i)});
2910       Done = j;
2911     }
2912   }
2913 
2914   copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2915 }
2916 
2917 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
2918 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2919 static int StackMallocSizeClass(uint64_t LocalStackSize) {
2920   assert(LocalStackSize <= kMaxStackMallocSize);
2921   uint64_t MaxSize = kMinStackMallocSize;
2922   for (int i = 0;; i++, MaxSize *= 2)
2923     if (LocalStackSize <= MaxSize) return i;
2924   llvm_unreachable("impossible LocalStackSize");
2925 }
2926 
2927 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
2928   Instruction *CopyInsertPoint = &F.front().front();
2929   if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2930     // Insert after the dynamic shadow location is determined
2931     CopyInsertPoint = CopyInsertPoint->getNextNode();
2932     assert(CopyInsertPoint);
2933   }
2934   IRBuilder<> IRB(CopyInsertPoint);
2935   const DataLayout &DL = F.getParent()->getDataLayout();
2936   for (Argument &Arg : F.args()) {
2937     if (Arg.hasByValAttr()) {
2938       Type *Ty = Arg.getParamByValType();
2939       const Align Alignment =
2940           DL.getValueOrABITypeAlignment(Arg.getParamAlign(), Ty);
2941 
2942       AllocaInst *AI = IRB.CreateAlloca(
2943           Ty, nullptr,
2944           (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
2945               ".byval");
2946       AI->setAlignment(Alignment);
2947       Arg.replaceAllUsesWith(AI);
2948 
2949       uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2950       IRB.CreateMemCpy(AI, Alignment, &Arg, Alignment, AllocSize);
2951     }
2952   }
2953 }
2954 
2955 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2956                                           Value *ValueIfTrue,
2957                                           Instruction *ThenTerm,
2958                                           Value *ValueIfFalse) {
2959   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2960   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2961   PHI->addIncoming(ValueIfFalse, CondBlock);
2962   BasicBlock *ThenBlock = ThenTerm->getParent();
2963   PHI->addIncoming(ValueIfTrue, ThenBlock);
2964   return PHI;
2965 }
2966 
2967 Value *FunctionStackPoisoner::createAllocaForLayout(
2968     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2969   AllocaInst *Alloca;
2970   if (Dynamic) {
2971     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2972                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2973                               "MyAlloca");
2974   } else {
2975     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2976                               nullptr, "MyAlloca");
2977     assert(Alloca->isStaticAlloca());
2978   }
2979   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2980   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2981   Alloca->setAlignment(Align(FrameAlignment));
2982   return IRB.CreatePointerCast(Alloca, IntptrTy);
2983 }
2984 
2985 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2986   BasicBlock &FirstBB = *F.begin();
2987   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2988   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2989   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2990   DynamicAllocaLayout->setAlignment(Align(32));
2991 }
2992 
2993 void FunctionStackPoisoner::processDynamicAllocas() {
2994   if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2995     assert(DynamicAllocaPoisonCallVec.empty());
2996     return;
2997   }
2998 
2999   // Insert poison calls for lifetime intrinsics for dynamic allocas.
3000   for (const auto &APC : DynamicAllocaPoisonCallVec) {
3001     assert(APC.InsBefore);
3002     assert(APC.AI);
3003     assert(ASan.isInterestingAlloca(*APC.AI));
3004     assert(!APC.AI->isStaticAlloca());
3005 
3006     IRBuilder<> IRB(APC.InsBefore);
3007     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
3008     // Dynamic allocas will be unpoisoned unconditionally below in
3009     // unpoisonDynamicAllocas.
3010     // Flag that we need unpoison static allocas.
3011   }
3012 
3013   // Handle dynamic allocas.
3014   createDynamicAllocasInitStorage();
3015   for (auto &AI : DynamicAllocaVec)
3016     handleDynamicAllocaCall(AI);
3017   unpoisonDynamicAllocas();
3018 }
3019 
3020 /// Collect instructions in the entry block after \p InsBefore which initialize
3021 /// permanent storage for a function argument. These instructions must remain in
3022 /// the entry block so that uninitialized values do not appear in backtraces. An
3023 /// added benefit is that this conserves spill slots. This does not move stores
3024 /// before instrumented / "interesting" allocas.
3025 static void findStoresToUninstrumentedArgAllocas(
3026     AddressSanitizer &ASan, Instruction &InsBefore,
3027     SmallVectorImpl<Instruction *> &InitInsts) {
3028   Instruction *Start = InsBefore.getNextNonDebugInstruction();
3029   for (Instruction *It = Start; It; It = It->getNextNonDebugInstruction()) {
3030     // Argument initialization looks like:
3031     // 1) store <Argument>, <Alloca> OR
3032     // 2) <CastArgument> = cast <Argument> to ...
3033     //    store <CastArgument> to <Alloca>
3034     // Do not consider any other kind of instruction.
3035     //
3036     // Note: This covers all known cases, but may not be exhaustive. An
3037     // alternative to pattern-matching stores is to DFS over all Argument uses:
3038     // this might be more general, but is probably much more complicated.
3039     if (isa<AllocaInst>(It) || isa<CastInst>(It))
3040       continue;
3041     if (auto *Store = dyn_cast<StoreInst>(It)) {
3042       // The store destination must be an alloca that isn't interesting for
3043       // ASan to instrument. These are moved up before InsBefore, and they're
3044       // not interesting because allocas for arguments can be mem2reg'd.
3045       auto *Alloca = dyn_cast<AllocaInst>(Store->getPointerOperand());
3046       if (!Alloca || ASan.isInterestingAlloca(*Alloca))
3047         continue;
3048 
3049       Value *Val = Store->getValueOperand();
3050       bool IsDirectArgInit = isa<Argument>(Val);
3051       bool IsArgInitViaCast =
3052           isa<CastInst>(Val) &&
3053           isa<Argument>(cast<CastInst>(Val)->getOperand(0)) &&
3054           // Check that the cast appears directly before the store. Otherwise
3055           // moving the cast before InsBefore may break the IR.
3056           Val == It->getPrevNonDebugInstruction();
3057       bool IsArgInit = IsDirectArgInit || IsArgInitViaCast;
3058       if (!IsArgInit)
3059         continue;
3060 
3061       if (IsArgInitViaCast)
3062         InitInsts.push_back(cast<Instruction>(Val));
3063       InitInsts.push_back(Store);
3064       continue;
3065     }
3066 
3067     // Do not reorder past unknown instructions: argument initialization should
3068     // only involve casts and stores.
3069     return;
3070   }
3071 }
3072 
3073 void FunctionStackPoisoner::processStaticAllocas() {
3074   if (AllocaVec.empty()) {
3075     assert(StaticAllocaPoisonCallVec.empty());
3076     return;
3077   }
3078 
3079   int StackMallocIdx = -1;
3080   DebugLoc EntryDebugLocation;
3081   if (auto SP = F.getSubprogram())
3082     EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
3083 
3084   Instruction *InsBefore = AllocaVec[0];
3085   IRBuilder<> IRB(InsBefore);
3086 
3087   // Make sure non-instrumented allocas stay in the entry block. Otherwise,
3088   // debug info is broken, because only entry-block allocas are treated as
3089   // regular stack slots.
3090   auto InsBeforeB = InsBefore->getParent();
3091   assert(InsBeforeB == &F.getEntryBlock());
3092   for (auto *AI : StaticAllocasToMoveUp)
3093     if (AI->getParent() == InsBeforeB)
3094       AI->moveBefore(InsBefore);
3095 
3096   // Move stores of arguments into entry-block allocas as well. This prevents
3097   // extra stack slots from being generated (to house the argument values until
3098   // they can be stored into the allocas). This also prevents uninitialized
3099   // values from being shown in backtraces.
3100   SmallVector<Instruction *, 8> ArgInitInsts;
3101   findStoresToUninstrumentedArgAllocas(ASan, *InsBefore, ArgInitInsts);
3102   for (Instruction *ArgInitInst : ArgInitInsts)
3103     ArgInitInst->moveBefore(InsBefore);
3104 
3105   // If we have a call to llvm.localescape, keep it in the entry block.
3106   if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
3107 
3108   SmallVector<ASanStackVariableDescription, 16> SVD;
3109   SVD.reserve(AllocaVec.size());
3110   for (AllocaInst *AI : AllocaVec) {
3111     ASanStackVariableDescription D = {AI->getName().data(),
3112                                       ASan.getAllocaSizeInBytes(*AI),
3113                                       0,
3114                                       AI->getAlignment(),
3115                                       AI,
3116                                       0,
3117                                       0};
3118     SVD.push_back(D);
3119   }
3120 
3121   // Minimal header size (left redzone) is 4 pointers,
3122   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
3123   size_t Granularity = 1ULL << Mapping.Scale;
3124   size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
3125   const ASanStackFrameLayout &L =
3126       ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
3127 
3128   // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
3129   DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
3130   for (auto &Desc : SVD)
3131     AllocaToSVDMap[Desc.AI] = &Desc;
3132 
3133   // Update SVD with information from lifetime intrinsics.
3134   for (const auto &APC : StaticAllocaPoisonCallVec) {
3135     assert(APC.InsBefore);
3136     assert(APC.AI);
3137     assert(ASan.isInterestingAlloca(*APC.AI));
3138     assert(APC.AI->isStaticAlloca());
3139 
3140     ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3141     Desc.LifetimeSize = Desc.Size;
3142     if (const DILocation *FnLoc = EntryDebugLocation.get()) {
3143       if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
3144         if (LifetimeLoc->getFile() == FnLoc->getFile())
3145           if (unsigned Line = LifetimeLoc->getLine())
3146             Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
3147       }
3148     }
3149   }
3150 
3151   auto DescriptionString = ComputeASanStackFrameDescription(SVD);
3152   LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
3153   uint64_t LocalStackSize = L.FrameSize;
3154   bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
3155                        LocalStackSize <= kMaxStackMallocSize;
3156   bool DoDynamicAlloca = ClDynamicAllocaStack;
3157   // Don't do dynamic alloca or stack malloc if:
3158   // 1) There is inline asm: too often it makes assumptions on which registers
3159   //    are available.
3160   // 2) There is a returns_twice call (typically setjmp), which is
3161   //    optimization-hostile, and doesn't play well with introduced indirect
3162   //    register-relative calculation of local variable addresses.
3163   DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
3164   DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
3165 
3166   Value *StaticAlloca =
3167       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
3168 
3169   Value *FakeStack;
3170   Value *LocalStackBase;
3171   Value *LocalStackBaseAlloca;
3172   uint8_t DIExprFlags = DIExpression::ApplyOffset;
3173 
3174   if (DoStackMalloc) {
3175     LocalStackBaseAlloca =
3176         IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
3177     // void *FakeStack = __asan_option_detect_stack_use_after_return
3178     //     ? __asan_stack_malloc_N(LocalStackSize)
3179     //     : nullptr;
3180     // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
3181     Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
3182         kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
3183     Value *UseAfterReturnIsEnabled = IRB.CreateICmpNE(
3184         IRB.CreateLoad(IRB.getInt32Ty(), OptionDetectUseAfterReturn),
3185         Constant::getNullValue(IRB.getInt32Ty()));
3186     Instruction *Term =
3187         SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
3188     IRBuilder<> IRBIf(Term);
3189     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3190     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
3191     Value *FakeStackValue =
3192         IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
3193                          ConstantInt::get(IntptrTy, LocalStackSize));
3194     IRB.SetInsertPoint(InsBefore);
3195     FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
3196                           ConstantInt::get(IntptrTy, 0));
3197 
3198     Value *NoFakeStack =
3199         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
3200     Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
3201     IRBIf.SetInsertPoint(Term);
3202     Value *AllocaValue =
3203         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
3204 
3205     IRB.SetInsertPoint(InsBefore);
3206     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
3207     IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
3208     DIExprFlags |= DIExpression::DerefBefore;
3209   } else {
3210     // void *FakeStack = nullptr;
3211     // void *LocalStackBase = alloca(LocalStackSize);
3212     FakeStack = ConstantInt::get(IntptrTy, 0);
3213     LocalStackBase =
3214         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
3215     LocalStackBaseAlloca = LocalStackBase;
3216   }
3217 
3218   // It shouldn't matter whether we pass an `alloca` or a `ptrtoint` as the
3219   // dbg.declare address opereand, but passing a `ptrtoint` seems to confuse
3220   // later passes and can result in dropped variable coverage in debug info.
3221   Value *LocalStackBaseAllocaPtr =
3222       isa<PtrToIntInst>(LocalStackBaseAlloca)
3223           ? cast<PtrToIntInst>(LocalStackBaseAlloca)->getPointerOperand()
3224           : LocalStackBaseAlloca;
3225   assert(isa<AllocaInst>(LocalStackBaseAllocaPtr) &&
3226          "Variable descriptions relative to ASan stack base will be dropped");
3227 
3228   // Replace Alloca instructions with base+offset.
3229   for (const auto &Desc : SVD) {
3230     AllocaInst *AI = Desc.AI;
3231     replaceDbgDeclare(AI, LocalStackBaseAllocaPtr, DIB, DIExprFlags,
3232                       Desc.Offset);
3233     Value *NewAllocaPtr = IRB.CreateIntToPtr(
3234         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
3235         AI->getType());
3236     AI->replaceAllUsesWith(NewAllocaPtr);
3237   }
3238 
3239   // The left-most redzone has enough space for at least 4 pointers.
3240   // Write the Magic value to redzone[0].
3241   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3242   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
3243                   BasePlus0);
3244   // Write the frame description constant to redzone[1].
3245   Value *BasePlus1 = IRB.CreateIntToPtr(
3246       IRB.CreateAdd(LocalStackBase,
3247                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3248       IntptrPtrTy);
3249   GlobalVariable *StackDescriptionGlobal =
3250       createPrivateGlobalForString(*F.getParent(), DescriptionString,
3251                                    /*AllowMerging*/ true, kAsanGenPrefix);
3252   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
3253   IRB.CreateStore(Description, BasePlus1);
3254   // Write the PC to redzone[2].
3255   Value *BasePlus2 = IRB.CreateIntToPtr(
3256       IRB.CreateAdd(LocalStackBase,
3257                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3258       IntptrPtrTy);
3259   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
3260 
3261   const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3262 
3263   // Poison the stack red zones at the entry.
3264   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3265   // As mask we must use most poisoned case: red zones and after scope.
3266   // As bytes we can use either the same or just red zones only.
3267   copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3268 
3269   if (!StaticAllocaPoisonCallVec.empty()) {
3270     const auto &ShadowInScope = GetShadowBytes(SVD, L);
3271 
3272     // Poison static allocas near lifetime intrinsics.
3273     for (const auto &APC : StaticAllocaPoisonCallVec) {
3274       const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3275       assert(Desc.Offset % L.Granularity == 0);
3276       size_t Begin = Desc.Offset / L.Granularity;
3277       size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3278 
3279       IRBuilder<> IRB(APC.InsBefore);
3280       copyToShadow(ShadowAfterScope,
3281                    APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3282                    IRB, ShadowBase);
3283     }
3284   }
3285 
3286   SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
3287   SmallVector<uint8_t, 64> ShadowAfterReturn;
3288 
3289   // (Un)poison the stack before all ret instructions.
3290   for (auto Ret : RetVec) {
3291     IRBuilder<> IRBRet(Ret);
3292     // Mark the current frame as retired.
3293     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3294                        BasePlus0);
3295     if (DoStackMalloc) {
3296       assert(StackMallocIdx >= 0);
3297       // if FakeStack != 0  // LocalStackBase == FakeStack
3298       //     // In use-after-return mode, poison the whole stack frame.
3299       //     if StackMallocIdx <= 4
3300       //         // For small sizes inline the whole thing:
3301       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
3302       //         **SavedFlagPtr(FakeStack) = 0
3303       //     else
3304       //         __asan_stack_free_N(FakeStack, LocalStackSize)
3305       // else
3306       //     <This is not a fake stack; unpoison the redzones>
3307       Value *Cmp =
3308           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
3309       Instruction *ThenTerm, *ElseTerm;
3310       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3311 
3312       IRBuilder<> IRBPoison(ThenTerm);
3313       if (StackMallocIdx <= 4) {
3314         int ClassSize = kMinStackMallocSize << StackMallocIdx;
3315         ShadowAfterReturn.resize(ClassSize / L.Granularity,
3316                                  kAsanStackUseAfterReturnMagic);
3317         copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3318                      ShadowBase);
3319         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
3320             FakeStack,
3321             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3322         Value *SavedFlagPtr = IRBPoison.CreateLoad(
3323             IntptrTy, IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3324         IRBPoison.CreateStore(
3325             Constant::getNullValue(IRBPoison.getInt8Ty()),
3326             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3327       } else {
3328         // For larger frames call __asan_stack_free_*.
3329         IRBPoison.CreateCall(
3330             AsanStackFreeFunc[StackMallocIdx],
3331             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
3332       }
3333 
3334       IRBuilder<> IRBElse(ElseTerm);
3335       copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3336     } else {
3337       copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3338     }
3339   }
3340 
3341   // We are done. Remove the old unused alloca instructions.
3342   for (auto AI : AllocaVec) AI->eraseFromParent();
3343 }
3344 
3345 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
3346                                          IRBuilder<> &IRB, bool DoPoison) {
3347   // For now just insert the call to ASan runtime.
3348   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3349   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
3350   IRB.CreateCall(
3351       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3352       {AddrArg, SizeArg});
3353 }
3354 
3355 // Handling llvm.lifetime intrinsics for a given %alloca:
3356 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3357 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3358 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3359 //     could be poisoned by previous llvm.lifetime.end instruction, as the
3360 //     variable may go in and out of scope several times, e.g. in loops).
3361 // (3) if we poisoned at least one %alloca in a function,
3362 //     unpoison the whole stack frame at function exit.
3363 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
3364   IRBuilder<> IRB(AI);
3365 
3366   const unsigned Alignment = std::max(kAllocaRzSize, AI->getAlignment());
3367   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3368 
3369   Value *Zero = Constant::getNullValue(IntptrTy);
3370   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3371   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
3372 
3373   // Since we need to extend alloca with additional memory to locate
3374   // redzones, and OldSize is number of allocated blocks with
3375   // ElementSize size, get allocated memory size in bytes by
3376   // OldSize * ElementSize.
3377   const unsigned ElementSize =
3378       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
3379   Value *OldSize =
3380       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3381                     ConstantInt::get(IntptrTy, ElementSize));
3382 
3383   // PartialSize = OldSize % 32
3384   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3385 
3386   // Misalign = kAllocaRzSize - PartialSize;
3387   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3388 
3389   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3390   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3391   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3392 
3393   // AdditionalChunkSize = Alignment + PartialPadding + kAllocaRzSize
3394   // Alignment is added to locate left redzone, PartialPadding for possible
3395   // partial redzone and kAllocaRzSize for right redzone respectively.
3396   Value *AdditionalChunkSize = IRB.CreateAdd(
3397       ConstantInt::get(IntptrTy, Alignment + kAllocaRzSize), PartialPadding);
3398 
3399   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3400 
3401   // Insert new alloca with new NewSize and Alignment params.
3402   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3403   NewAlloca->setAlignment(Align(Alignment));
3404 
3405   // NewAddress = Address + Alignment
3406   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3407                                     ConstantInt::get(IntptrTy, Alignment));
3408 
3409   // Insert __asan_alloca_poison call for new created alloca.
3410   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3411 
3412   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3413   // for unpoisoning stuff.
3414   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3415 
3416   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3417 
3418   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
3419   AI->replaceAllUsesWith(NewAddressPtr);
3420 
3421   // We are done. Erase old alloca from parent.
3422   AI->eraseFromParent();
3423 }
3424 
3425 // isSafeAccess returns true if Addr is always inbounds with respect to its
3426 // base object. For example, it is a field access or an array access with
3427 // constant inbounds index.
3428 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3429                                     Value *Addr, uint64_t TypeSize) const {
3430   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3431   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
3432   uint64_t Size = SizeOffset.first.getZExtValue();
3433   int64_t Offset = SizeOffset.second.getSExtValue();
3434   // Three checks are required to ensure safety:
3435   // . Offset >= 0  (since the offset is given from the base ptr)
3436   // . Size >= Offset  (unsigned)
3437   // . Size - Offset >= NeededSize  (unsigned)
3438   return Offset >= 0 && Size >= uint64_t(Offset) &&
3439          Size - uint64_t(Offset) >= TypeSize / 8;
3440 }
3441