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