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