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