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