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